codemirror.js 360 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent
  16. var platform = navigator.platform
  17. var gecko = /gecko\/\d/i.test(userAgent)
  18. var ie_upto10 = /MSIE \d/.test(userAgent)
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  20. var edge = /Edge\/(\d+)/.exec(userAgent)
  21. var ie = ie_upto10 || ie_11up || edge
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])
  23. var webkit = !edge && /WebKit\//.test(userAgent)
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  25. var chrome = !edge && /Chrome\//.test(userAgent)
  26. var presto = /Opera\//.test(userAgent)
  27. var safari = /Apple Computer/.test(navigator.vendor)
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  29. var phantom = /PhantomJS/.test(userAgent)
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
  31. var android = /Android/.test(userAgent)
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  34. var mac = ios || /Mac/.test(platform)
  35. var chromeOS = /\bCrOS\b/.test(userAgent)
  36. var windows = /win/i.test(platform)
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  38. if (presto_version) { presto_version = Number(presto_version[1]) }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  42. var captureRightClick = gecko || (ie && ie_version >= 9)
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className
  46. var match = classTest(cls).exec(current)
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length)
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  50. }
  51. }
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild) }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag)
  62. if (className) { e.className = className }
  63. if (style) { e.style.cssText = style }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style)
  71. e.setAttribute("role", "presentation")
  72. return e
  73. }
  74. var range
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange()
  77. r.setEnd(endNode || node, end)
  78. r.setStart(node, start)
  79. return r
  80. } }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange()
  83. try { r.moveToElementText(node.parentNode) }
  84. catch(e) { return r }
  85. r.collapse(true)
  86. r.moveEnd("character", end)
  87. r.moveStart("character", start)
  88. return r
  89. } }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement
  105. try {
  106. activeElement = document.activeElement
  107. } catch(e) {
  108. activeElement = document.body || null
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ")
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select() }
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1)
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {} }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop] } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/)
  145. if (end == -1) { end = string.length }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i)
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i
  152. n += tabSize - (n % tabSize)
  153. i = nextTab + 1
  154. }
  155. }
  156. var Delayed = function() {this.id = null};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id)
  159. this.id = setTimeout(f, ms)
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false};
  173. var sel_mouse = {origin: "*mouse"};
  174. var sel_move = {origin: "+move"};
  175. // The inverse of countColumn -- find the offset that corresponds to
  176. // a particular column.
  177. function findColumn(string, goal, tabSize) {
  178. for (var pos = 0, col = 0;;) {
  179. var nextTab = string.indexOf("\t", pos)
  180. if (nextTab == -1) { nextTab = string.length }
  181. var skipped = nextTab - pos
  182. if (nextTab == string.length || col + skipped >= goal)
  183. { return pos + Math.min(skipped, goal - col) }
  184. col += nextTab - pos
  185. col += tabSize - (col % tabSize)
  186. pos = nextTab + 1
  187. if (col >= goal) { return pos }
  188. }
  189. }
  190. var spaceStrs = [""]
  191. function spaceStr(n) {
  192. while (spaceStrs.length <= n)
  193. { spaceStrs.push(lst(spaceStrs) + " ") }
  194. return spaceStrs[n]
  195. }
  196. function lst(arr) { return arr[arr.length-1] }
  197. function map(array, f) {
  198. var out = []
  199. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  200. return out
  201. }
  202. function insertSorted(array, value, score) {
  203. var pos = 0, priority = score(value)
  204. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  205. array.splice(pos, 0, value)
  206. }
  207. function nothing() {}
  208. function createObj(base, props) {
  209. var inst
  210. if (Object.create) {
  211. inst = Object.create(base)
  212. } else {
  213. nothing.prototype = base
  214. inst = new nothing()
  215. }
  216. if (props) { copyObj(props, inst) }
  217. return inst
  218. }
  219. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  220. function isWordCharBasic(ch) {
  221. return /\w/.test(ch) || ch > "\x80" &&
  222. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  223. }
  224. function isWordChar(ch, helper) {
  225. if (!helper) { return isWordCharBasic(ch) }
  226. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  227. return helper.test(ch)
  228. }
  229. function isEmpty(obj) {
  230. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  231. return true
  232. }
  233. // Extending unicode characters. A series of a non-extending char +
  234. // any number of extending chars is treated as a single unit as far
  235. // as editing and measuring is concerned. This is not fully correct,
  236. // since some scripts/fonts/browsers also treat other configurations
  237. // of code points as a group.
  238. 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]/
  239. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  240. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  241. function skipExtendingChars(str, pos, dir) {
  242. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir }
  243. return pos
  244. }
  245. // Returns the value from the range [`from`; `to`] that satisfies
  246. // `pred` and is closest to `from`. Assumes that at least `to`
  247. // satisfies `pred`. Supports `from` being greater than `to`.
  248. function findFirst(pred, from, to) {
  249. // At any point we are certain `to` satisfies `pred`, don't know
  250. // whether `from` does.
  251. var dir = from > to ? -1 : 1
  252. for (;;) {
  253. if (from == to) { return from }
  254. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF)
  255. if (mid == from) { return pred(mid) ? from : to }
  256. if (pred(mid)) { to = mid }
  257. else { from = mid + dir }
  258. }
  259. }
  260. // The display handles the DOM integration, both for input reading
  261. // and content drawing. It holds references to DOM nodes and
  262. // display-related state.
  263. function Display(place, doc, input) {
  264. var d = this
  265. this.input = input
  266. // Covers bottom-right square when both scrollbars are present.
  267. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  268. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  269. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  270. // and h scrollbar is present.
  271. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  272. d.gutterFiller.setAttribute("cm-not-content", "true")
  273. // Will contain the actual code, positioned to cover the viewport.
  274. d.lineDiv = eltP("div", null, "CodeMirror-code")
  275. // Elements are added to these to represent selection and cursors.
  276. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  277. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  278. // A visibility: hidden element used to find the size of things.
  279. d.measure = elt("div", null, "CodeMirror-measure")
  280. // When lines outside of the viewport are measured, they are drawn in this.
  281. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  282. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  283. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  284. null, "position: relative; outline: none")
  285. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines")
  286. // Moved around its parent to cover visible view.
  287. d.mover = elt("div", [lines], null, "position: relative")
  288. // Set to the height of the document, allowing scrolling.
  289. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  290. d.sizerWidth = null
  291. // Behavior of elts with overflow: auto and padding is
  292. // inconsistent across browsers. This is used to ensure the
  293. // scrollable area is big enough.
  294. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  295. // Will contain the gutters, if any.
  296. d.gutters = elt("div", null, "CodeMirror-gutters")
  297. d.lineGutter = null
  298. // Actual scrollable element.
  299. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  300. d.scroller.setAttribute("tabIndex", "-1")
  301. // The element in which the editor lives.
  302. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  303. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  304. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  305. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  306. if (place) {
  307. if (place.appendChild) { place.appendChild(d.wrapper) }
  308. else { place(d.wrapper) }
  309. }
  310. // Current rendered range (may be bigger than the view window).
  311. d.viewFrom = d.viewTo = doc.first
  312. d.reportedViewFrom = d.reportedViewTo = doc.first
  313. // Information about the rendered lines.
  314. d.view = []
  315. d.renderedView = null
  316. // Holds info about a single rendered line when it was rendered
  317. // for measurement, while not in view.
  318. d.externalMeasured = null
  319. // Empty space (in pixels) above the view
  320. d.viewOffset = 0
  321. d.lastWrapHeight = d.lastWrapWidth = 0
  322. d.updateLineNumbers = null
  323. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  324. d.scrollbarsClipped = false
  325. // Used to only resize the line number gutter when necessary (when
  326. // the amount of lines crosses a boundary that makes its width change)
  327. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  328. // Set to true when a non-horizontal-scrolling line widget is
  329. // added. As an optimization, line widget aligning is skipped when
  330. // this is false.
  331. d.alignWidgets = false
  332. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  333. // Tracks the maximum line length so that the horizontal scrollbar
  334. // can be kept static when scrolling.
  335. d.maxLine = null
  336. d.maxLineLength = 0
  337. d.maxLineChanged = false
  338. // Used for measuring wheel scrolling granularity
  339. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  340. // True when shift is held down.
  341. d.shift = false
  342. // Used to track whether anything happened since the context menu
  343. // was opened.
  344. d.selForContextMenu = null
  345. d.activeTouch = null
  346. input.init(d)
  347. }
  348. // Find the line object corresponding to the given line number.
  349. function getLine(doc, n) {
  350. n -= doc.first
  351. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  352. var chunk = doc
  353. while (!chunk.lines) {
  354. for (var i = 0;; ++i) {
  355. var child = chunk.children[i], sz = child.chunkSize()
  356. if (n < sz) { chunk = child; break }
  357. n -= sz
  358. }
  359. }
  360. return chunk.lines[n]
  361. }
  362. // Get the part of a document between two positions, as an array of
  363. // strings.
  364. function getBetween(doc, start, end) {
  365. var out = [], n = start.line
  366. doc.iter(start.line, end.line + 1, function (line) {
  367. var text = line.text
  368. if (n == end.line) { text = text.slice(0, end.ch) }
  369. if (n == start.line) { text = text.slice(start.ch) }
  370. out.push(text)
  371. ++n
  372. })
  373. return out
  374. }
  375. // Get the lines between from and to, as array of strings.
  376. function getLines(doc, from, to) {
  377. var out = []
  378. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  379. return out
  380. }
  381. // Update the height of a line, propagating the height change
  382. // upwards to parent nodes.
  383. function updateLineHeight(line, height) {
  384. var diff = height - line.height
  385. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  386. }
  387. // Given a line object, find its line number by walking up through
  388. // its parent links.
  389. function lineNo(line) {
  390. if (line.parent == null) { return null }
  391. var cur = line.parent, no = indexOf(cur.lines, line)
  392. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  393. for (var i = 0;; ++i) {
  394. if (chunk.children[i] == cur) { break }
  395. no += chunk.children[i].chunkSize()
  396. }
  397. }
  398. return no + cur.first
  399. }
  400. // Find the line at the given vertical position, using the height
  401. // information in the document tree.
  402. function lineAtHeight(chunk, h) {
  403. var n = chunk.first
  404. outer: do {
  405. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  406. var child = chunk.children[i$1], ch = child.height
  407. if (h < ch) { chunk = child; continue outer }
  408. h -= ch
  409. n += child.chunkSize()
  410. }
  411. return n
  412. } while (!chunk.lines)
  413. var i = 0
  414. for (; i < chunk.lines.length; ++i) {
  415. var line = chunk.lines[i], lh = line.height
  416. if (h < lh) { break }
  417. h -= lh
  418. }
  419. return n + i
  420. }
  421. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  422. function lineNumberFor(options, i) {
  423. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  424. }
  425. // A Pos instance represents a position within the text.
  426. function Pos(line, ch, sticky) {
  427. if ( sticky === void 0 ) sticky = null;
  428. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  429. this.line = line
  430. this.ch = ch
  431. this.sticky = sticky
  432. }
  433. // Compare two positions, return 0 if they are the same, a negative
  434. // number when a is less, and a positive number otherwise.
  435. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  436. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  437. function copyPos(x) {return Pos(x.line, x.ch)}
  438. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  439. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  440. // Most of the external API clips given positions to make sure they
  441. // actually exist within the document.
  442. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  443. function clipPos(doc, pos) {
  444. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  445. var last = doc.first + doc.size - 1
  446. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  447. return clipToLen(pos, getLine(doc, pos.line).text.length)
  448. }
  449. function clipToLen(pos, linelen) {
  450. var ch = pos.ch
  451. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  452. else if (ch < 0) { return Pos(pos.line, 0) }
  453. else { return pos }
  454. }
  455. function clipPosArray(doc, array) {
  456. var out = []
  457. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  458. return out
  459. }
  460. // Optimize some code when these features are not used.
  461. var sawReadOnlySpans = false;
  462. var sawCollapsedSpans = false;
  463. function seeReadOnlySpans() {
  464. sawReadOnlySpans = true
  465. }
  466. function seeCollapsedSpans() {
  467. sawCollapsedSpans = true
  468. }
  469. // TEXTMARKER SPANS
  470. function MarkedSpan(marker, from, to) {
  471. this.marker = marker
  472. this.from = from; this.to = to
  473. }
  474. // Search an array of spans for a span matching the given marker.
  475. function getMarkedSpanFor(spans, marker) {
  476. if (spans) { for (var i = 0; i < spans.length; ++i) {
  477. var span = spans[i]
  478. if (span.marker == marker) { return span }
  479. } }
  480. }
  481. // Remove a span from an array, returning undefined if no spans are
  482. // left (we don't store arrays for lines without spans).
  483. function removeMarkedSpan(spans, span) {
  484. var r
  485. for (var i = 0; i < spans.length; ++i)
  486. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  487. return r
  488. }
  489. // Add a span to a line.
  490. function addMarkedSpan(line, span) {
  491. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  492. span.marker.attachLine(line)
  493. }
  494. // Used for the algorithm that adjusts markers for a change in the
  495. // document. These functions cut an array of spans at a given
  496. // character position, returning an array of remaining chunks (or
  497. // undefined if nothing remains).
  498. function markedSpansBefore(old, startCh, isInsert) {
  499. var nw
  500. if (old) { for (var i = 0; i < old.length; ++i) {
  501. var span = old[i], marker = span.marker
  502. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  503. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  504. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  505. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  506. }
  507. } }
  508. return nw
  509. }
  510. function markedSpansAfter(old, endCh, isInsert) {
  511. var nw
  512. if (old) { for (var i = 0; i < old.length; ++i) {
  513. var span = old[i], marker = span.marker
  514. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  515. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  516. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  517. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  518. span.to == null ? null : span.to - endCh))
  519. }
  520. } }
  521. return nw
  522. }
  523. // Given a change object, compute the new set of marker spans that
  524. // cover the line in which the change took place. Removes spans
  525. // entirely within the change, reconnects spans belonging to the
  526. // same marker that appear on both sides of the change, and cuts off
  527. // spans partially within the change. Returns an array of span
  528. // arrays with one element for each line in (after) the change.
  529. function stretchSpansOverChange(doc, change) {
  530. if (change.full) { return null }
  531. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  532. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  533. if (!oldFirst && !oldLast) { return null }
  534. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  535. // Get the spans that 'stick out' on both sides
  536. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  537. var last = markedSpansAfter(oldLast, endCh, isInsert)
  538. // Next, merge those two ends
  539. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  540. if (first) {
  541. // Fix up .to properties of first
  542. for (var i = 0; i < first.length; ++i) {
  543. var span = first[i]
  544. if (span.to == null) {
  545. var found = getMarkedSpanFor(last, span.marker)
  546. if (!found) { span.to = startCh }
  547. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  548. }
  549. }
  550. }
  551. if (last) {
  552. // Fix up .from in last (or move them into first in case of sameLine)
  553. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  554. var span$1 = last[i$1]
  555. if (span$1.to != null) { span$1.to += offset }
  556. if (span$1.from == null) {
  557. var found$1 = getMarkedSpanFor(first, span$1.marker)
  558. if (!found$1) {
  559. span$1.from = offset
  560. if (sameLine) { (first || (first = [])).push(span$1) }
  561. }
  562. } else {
  563. span$1.from += offset
  564. if (sameLine) { (first || (first = [])).push(span$1) }
  565. }
  566. }
  567. }
  568. // Make sure we didn't create any zero-length spans
  569. if (first) { first = clearEmptySpans(first) }
  570. if (last && last != first) { last = clearEmptySpans(last) }
  571. var newMarkers = [first]
  572. if (!sameLine) {
  573. // Fill gap with whole-line-spans
  574. var gap = change.text.length - 2, gapMarkers
  575. if (gap > 0 && first)
  576. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  577. { if (first[i$2].to == null)
  578. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  579. for (var i$3 = 0; i$3 < gap; ++i$3)
  580. { newMarkers.push(gapMarkers) }
  581. newMarkers.push(last)
  582. }
  583. return newMarkers
  584. }
  585. // Remove spans that are empty and don't have a clearWhenEmpty
  586. // option of false.
  587. function clearEmptySpans(spans) {
  588. for (var i = 0; i < spans.length; ++i) {
  589. var span = spans[i]
  590. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  591. { spans.splice(i--, 1) }
  592. }
  593. if (!spans.length) { return null }
  594. return spans
  595. }
  596. // Used to 'clip' out readOnly ranges when making a change.
  597. function removeReadOnlyRanges(doc, from, to) {
  598. var markers = null
  599. doc.iter(from.line, to.line + 1, function (line) {
  600. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  601. var mark = line.markedSpans[i].marker
  602. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  603. { (markers || (markers = [])).push(mark) }
  604. } }
  605. })
  606. if (!markers) { return null }
  607. var parts = [{from: from, to: to}]
  608. for (var i = 0; i < markers.length; ++i) {
  609. var mk = markers[i], m = mk.find(0)
  610. for (var j = 0; j < parts.length; ++j) {
  611. var p = parts[j]
  612. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  613. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  614. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  615. { newParts.push({from: p.from, to: m.from}) }
  616. if (dto > 0 || !mk.inclusiveRight && !dto)
  617. { newParts.push({from: m.to, to: p.to}) }
  618. parts.splice.apply(parts, newParts)
  619. j += newParts.length - 3
  620. }
  621. }
  622. return parts
  623. }
  624. // Connect or disconnect spans from a line.
  625. function detachMarkedSpans(line) {
  626. var spans = line.markedSpans
  627. if (!spans) { return }
  628. for (var i = 0; i < spans.length; ++i)
  629. { spans[i].marker.detachLine(line) }
  630. line.markedSpans = null
  631. }
  632. function attachMarkedSpans(line, spans) {
  633. if (!spans) { return }
  634. for (var i = 0; i < spans.length; ++i)
  635. { spans[i].marker.attachLine(line) }
  636. line.markedSpans = spans
  637. }
  638. // Helpers used when computing which overlapping collapsed span
  639. // counts as the larger one.
  640. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  641. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  642. // Returns a number indicating which of two overlapping collapsed
  643. // spans is larger (and thus includes the other). Falls back to
  644. // comparing ids when the spans cover exactly the same range.
  645. function compareCollapsedMarkers(a, b) {
  646. var lenDiff = a.lines.length - b.lines.length
  647. if (lenDiff != 0) { return lenDiff }
  648. var aPos = a.find(), bPos = b.find()
  649. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  650. if (fromCmp) { return -fromCmp }
  651. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  652. if (toCmp) { return toCmp }
  653. return b.id - a.id
  654. }
  655. // Find out whether a line ends or starts in a collapsed span. If
  656. // so, return the marker for that span.
  657. function collapsedSpanAtSide(line, start) {
  658. var sps = sawCollapsedSpans && line.markedSpans, found
  659. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  660. sp = sps[i]
  661. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  662. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  663. { found = sp.marker }
  664. } }
  665. return found
  666. }
  667. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  668. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  669. // Test whether there exists a collapsed span that partially
  670. // overlaps (covers the start or end, but not both) of a new span.
  671. // Such overlap is not allowed.
  672. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  673. var line = getLine(doc, lineNo)
  674. var sps = sawCollapsedSpans && line.markedSpans
  675. if (sps) { for (var i = 0; i < sps.length; ++i) {
  676. var sp = sps[i]
  677. if (!sp.marker.collapsed) { continue }
  678. var found = sp.marker.find(0)
  679. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  680. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  681. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  682. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  683. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  684. { return true }
  685. } }
  686. }
  687. // A visual line is a line as drawn on the screen. Folding, for
  688. // example, can cause multiple logical lines to appear on the same
  689. // visual line. This finds the start of the visual line that the
  690. // given line is part of (usually that is the line itself).
  691. function visualLine(line) {
  692. var merged
  693. while (merged = collapsedSpanAtStart(line))
  694. { line = merged.find(-1, true).line }
  695. return line
  696. }
  697. function visualLineEnd(line) {
  698. var merged
  699. while (merged = collapsedSpanAtEnd(line))
  700. { line = merged.find(1, true).line }
  701. return line
  702. }
  703. // Returns an array of logical lines that continue the visual line
  704. // started by the argument, or undefined if there are no such lines.
  705. function visualLineContinued(line) {
  706. var merged, lines
  707. while (merged = collapsedSpanAtEnd(line)) {
  708. line = merged.find(1, true).line
  709. ;(lines || (lines = [])).push(line)
  710. }
  711. return lines
  712. }
  713. // Get the line number of the start of the visual line that the
  714. // given line number is part of.
  715. function visualLineNo(doc, lineN) {
  716. var line = getLine(doc, lineN), vis = visualLine(line)
  717. if (line == vis) { return lineN }
  718. return lineNo(vis)
  719. }
  720. // Get the line number of the start of the next visual line after
  721. // the given line.
  722. function visualLineEndNo(doc, lineN) {
  723. if (lineN > doc.lastLine()) { return lineN }
  724. var line = getLine(doc, lineN), merged
  725. if (!lineIsHidden(doc, line)) { return lineN }
  726. while (merged = collapsedSpanAtEnd(line))
  727. { line = merged.find(1, true).line }
  728. return lineNo(line) + 1
  729. }
  730. // Compute whether a line is hidden. Lines count as hidden when they
  731. // are part of a visual line that starts with another line, or when
  732. // they are entirely covered by collapsed, non-widget span.
  733. function lineIsHidden(doc, line) {
  734. var sps = sawCollapsedSpans && line.markedSpans
  735. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  736. sp = sps[i]
  737. if (!sp.marker.collapsed) { continue }
  738. if (sp.from == null) { return true }
  739. if (sp.marker.widgetNode) { continue }
  740. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  741. { return true }
  742. } }
  743. }
  744. function lineIsHiddenInner(doc, line, span) {
  745. if (span.to == null) {
  746. var end = span.marker.find(1, true)
  747. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  748. }
  749. if (span.marker.inclusiveRight && span.to == line.text.length)
  750. { return true }
  751. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  752. sp = line.markedSpans[i]
  753. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  754. (sp.to == null || sp.to != span.from) &&
  755. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  756. lineIsHiddenInner(doc, line, sp)) { return true }
  757. }
  758. }
  759. // Find the height above the given line.
  760. function heightAtLine(lineObj) {
  761. lineObj = visualLine(lineObj)
  762. var h = 0, chunk = lineObj.parent
  763. for (var i = 0; i < chunk.lines.length; ++i) {
  764. var line = chunk.lines[i]
  765. if (line == lineObj) { break }
  766. else { h += line.height }
  767. }
  768. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  769. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  770. var cur = p.children[i$1]
  771. if (cur == chunk) { break }
  772. else { h += cur.height }
  773. }
  774. }
  775. return h
  776. }
  777. // Compute the character length of a line, taking into account
  778. // collapsed ranges (see markText) that might hide parts, and join
  779. // other lines onto it.
  780. function lineLength(line) {
  781. if (line.height == 0) { return 0 }
  782. var len = line.text.length, merged, cur = line
  783. while (merged = collapsedSpanAtStart(cur)) {
  784. var found = merged.find(0, true)
  785. cur = found.from.line
  786. len += found.from.ch - found.to.ch
  787. }
  788. cur = line
  789. while (merged = collapsedSpanAtEnd(cur)) {
  790. var found$1 = merged.find(0, true)
  791. len -= cur.text.length - found$1.from.ch
  792. cur = found$1.to.line
  793. len += cur.text.length - found$1.to.ch
  794. }
  795. return len
  796. }
  797. // Find the longest line in the document.
  798. function findMaxLine(cm) {
  799. var d = cm.display, doc = cm.doc
  800. d.maxLine = getLine(doc, doc.first)
  801. d.maxLineLength = lineLength(d.maxLine)
  802. d.maxLineChanged = true
  803. doc.iter(function (line) {
  804. var len = lineLength(line)
  805. if (len > d.maxLineLength) {
  806. d.maxLineLength = len
  807. d.maxLine = line
  808. }
  809. })
  810. }
  811. // BIDI HELPERS
  812. function iterateBidiSections(order, from, to, f) {
  813. if (!order) { return f(from, to, "ltr", 0) }
  814. var found = false
  815. for (var i = 0; i < order.length; ++i) {
  816. var part = order[i]
  817. if (part.from < to && part.to > from || from == to && part.to == from) {
  818. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i)
  819. found = true
  820. }
  821. }
  822. if (!found) { f(from, to, "ltr") }
  823. }
  824. var bidiOther = null
  825. function getBidiPartAt(order, ch, sticky) {
  826. var found
  827. bidiOther = null
  828. for (var i = 0; i < order.length; ++i) {
  829. var cur = order[i]
  830. if (cur.from < ch && cur.to > ch) { return i }
  831. if (cur.to == ch) {
  832. if (cur.from != cur.to && sticky == "before") { found = i }
  833. else { bidiOther = i }
  834. }
  835. if (cur.from == ch) {
  836. if (cur.from != cur.to && sticky != "before") { found = i }
  837. else { bidiOther = i }
  838. }
  839. }
  840. return found != null ? found : bidiOther
  841. }
  842. // Bidirectional ordering algorithm
  843. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  844. // that this (partially) implements.
  845. // One-char codes used for character types:
  846. // L (L): Left-to-Right
  847. // R (R): Right-to-Left
  848. // r (AL): Right-to-Left Arabic
  849. // 1 (EN): European Number
  850. // + (ES): European Number Separator
  851. // % (ET): European Number Terminator
  852. // n (AN): Arabic Number
  853. // , (CS): Common Number Separator
  854. // m (NSM): Non-Spacing Mark
  855. // b (BN): Boundary Neutral
  856. // s (B): Paragraph Separator
  857. // t (S): Segment Separator
  858. // w (WS): Whitespace
  859. // N (ON): Other Neutrals
  860. // Returns null if characters are ordered as they appear
  861. // (left-to-right), or an array of sections ({from, to, level}
  862. // objects) in the order in which they occur visually.
  863. var bidiOrdering = (function() {
  864. // Character types for codepoints 0 to 0xff
  865. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  866. // Character types for codepoints 0x600 to 0x6f9
  867. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  868. function charType(code) {
  869. if (code <= 0xf7) { return lowTypes.charAt(code) }
  870. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  871. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  872. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  873. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  874. else if (code == 0x200c) { return "b" }
  875. else { return "L" }
  876. }
  877. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  878. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  879. function BidiSpan(level, from, to) {
  880. this.level = level
  881. this.from = from; this.to = to
  882. }
  883. return function(str, direction) {
  884. var outerType = direction == "ltr" ? "L" : "R"
  885. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  886. var len = str.length, types = []
  887. for (var i = 0; i < len; ++i)
  888. { types.push(charType(str.charCodeAt(i))) }
  889. // W1. Examine each non-spacing mark (NSM) in the level run, and
  890. // change the type of the NSM to the type of the previous
  891. // character. If the NSM is at the start of the level run, it will
  892. // get the type of sor.
  893. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  894. var type = types[i$1]
  895. if (type == "m") { types[i$1] = prev }
  896. else { prev = type }
  897. }
  898. // W2. Search backwards from each instance of a European number
  899. // until the first strong type (R, L, AL, or sor) is found. If an
  900. // AL is found, change the type of the European number to Arabic
  901. // number.
  902. // W3. Change all ALs to R.
  903. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  904. var type$1 = types[i$2]
  905. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  906. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  907. }
  908. // W4. A single European separator between two European numbers
  909. // changes to a European number. A single common separator between
  910. // two numbers of the same type changes to that type.
  911. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  912. var type$2 = types[i$3]
  913. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  914. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  915. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  916. prev$1 = type$2
  917. }
  918. // W5. A sequence of European terminators adjacent to European
  919. // numbers changes to all European numbers.
  920. // W6. Otherwise, separators and terminators change to Other
  921. // Neutral.
  922. for (var i$4 = 0; i$4 < len; ++i$4) {
  923. var type$3 = types[i$4]
  924. if (type$3 == ",") { types[i$4] = "N" }
  925. else if (type$3 == "%") {
  926. var end = (void 0)
  927. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  928. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  929. for (var j = i$4; j < end; ++j) { types[j] = replace }
  930. i$4 = end - 1
  931. }
  932. }
  933. // W7. Search backwards from each instance of a European number
  934. // until the first strong type (R, L, or sor) is found. If an L is
  935. // found, then change the type of the European number to L.
  936. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  937. var type$4 = types[i$5]
  938. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  939. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  940. }
  941. // N1. A sequence of neutrals takes the direction of the
  942. // surrounding strong text if the text on both sides has the same
  943. // direction. European and Arabic numbers act as if they were R in
  944. // terms of their influence on neutrals. Start-of-level-run (sor)
  945. // and end-of-level-run (eor) are used at level run boundaries.
  946. // N2. Any remaining neutrals take the embedding direction.
  947. for (var i$6 = 0; i$6 < len; ++i$6) {
  948. if (isNeutral.test(types[i$6])) {
  949. var end$1 = (void 0)
  950. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  951. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  952. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  953. var replace$1 = before == after ? (before ? "L" : "R") : outerType
  954. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  955. i$6 = end$1 - 1
  956. }
  957. }
  958. // Here we depart from the documented algorithm, in order to avoid
  959. // building up an actual levels array. Since there are only three
  960. // levels (0, 1, 2) in an implementation that doesn't take
  961. // explicit embedding into account, we can build up the order on
  962. // the fly, without following the level-based algorithm.
  963. var order = [], m
  964. for (var i$7 = 0; i$7 < len;) {
  965. if (countsAsLeft.test(types[i$7])) {
  966. var start = i$7
  967. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  968. order.push(new BidiSpan(0, start, i$7))
  969. } else {
  970. var pos = i$7, at = order.length
  971. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  972. for (var j$2 = pos; j$2 < i$7;) {
  973. if (countsAsNum.test(types[j$2])) {
  974. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  975. var nstart = j$2
  976. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  977. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  978. pos = j$2
  979. } else { ++j$2 }
  980. }
  981. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  982. }
  983. }
  984. if (direction == "ltr") {
  985. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  986. order[0].from = m[0].length
  987. order.unshift(new BidiSpan(0, 0, m[0].length))
  988. }
  989. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  990. lst(order).to -= m[0].length
  991. order.push(new BidiSpan(0, len - m[0].length, len))
  992. }
  993. }
  994. return direction == "rtl" ? order.reverse() : order
  995. }
  996. })()
  997. // Get the bidi ordering for the given line (and cache it). Returns
  998. // false for lines that are fully left-to-right, and an array of
  999. // BidiSpan objects otherwise.
  1000. function getOrder(line, direction) {
  1001. var order = line.order
  1002. if (order == null) { order = line.order = bidiOrdering(line.text, direction) }
  1003. return order
  1004. }
  1005. // EVENT HANDLING
  1006. // Lightweight event framework. on/off also work on DOM nodes,
  1007. // registering native DOM handlers.
  1008. var noHandlers = []
  1009. var on = function(emitter, type, f) {
  1010. if (emitter.addEventListener) {
  1011. emitter.addEventListener(type, f, false)
  1012. } else if (emitter.attachEvent) {
  1013. emitter.attachEvent("on" + type, f)
  1014. } else {
  1015. var map = emitter._handlers || (emitter._handlers = {})
  1016. map[type] = (map[type] || noHandlers).concat(f)
  1017. }
  1018. }
  1019. function getHandlers(emitter, type) {
  1020. return emitter._handlers && emitter._handlers[type] || noHandlers
  1021. }
  1022. function off(emitter, type, f) {
  1023. if (emitter.removeEventListener) {
  1024. emitter.removeEventListener(type, f, false)
  1025. } else if (emitter.detachEvent) {
  1026. emitter.detachEvent("on" + type, f)
  1027. } else {
  1028. var map = emitter._handlers, arr = map && map[type]
  1029. if (arr) {
  1030. var index = indexOf(arr, f)
  1031. if (index > -1)
  1032. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1033. }
  1034. }
  1035. }
  1036. function signal(emitter, type /*, values...*/) {
  1037. var handlers = getHandlers(emitter, type)
  1038. if (!handlers.length) { return }
  1039. var args = Array.prototype.slice.call(arguments, 2)
  1040. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1041. }
  1042. // The DOM events that CodeMirror handles can be overridden by
  1043. // registering a (non-DOM) handler on the editor for the event name,
  1044. // and preventDefault-ing the event in that handler.
  1045. function signalDOMEvent(cm, e, override) {
  1046. if (typeof e == "string")
  1047. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1048. signal(cm, override || e.type, cm, e)
  1049. return e_defaultPrevented(e) || e.codemirrorIgnore
  1050. }
  1051. function signalCursorActivity(cm) {
  1052. var arr = cm._handlers && cm._handlers.cursorActivity
  1053. if (!arr) { return }
  1054. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1055. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1056. { set.push(arr[i]) } }
  1057. }
  1058. function hasHandler(emitter, type) {
  1059. return getHandlers(emitter, type).length > 0
  1060. }
  1061. // Add on and off methods to a constructor's prototype, to make
  1062. // registering events on such objects more convenient.
  1063. function eventMixin(ctor) {
  1064. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1065. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1066. }
  1067. // Due to the fact that we still support jurassic IE versions, some
  1068. // compatibility wrappers are needed.
  1069. function e_preventDefault(e) {
  1070. if (e.preventDefault) { e.preventDefault() }
  1071. else { e.returnValue = false }
  1072. }
  1073. function e_stopPropagation(e) {
  1074. if (e.stopPropagation) { e.stopPropagation() }
  1075. else { e.cancelBubble = true }
  1076. }
  1077. function e_defaultPrevented(e) {
  1078. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1079. }
  1080. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1081. function e_target(e) {return e.target || e.srcElement}
  1082. function e_button(e) {
  1083. var b = e.which
  1084. if (b == null) {
  1085. if (e.button & 1) { b = 1 }
  1086. else if (e.button & 2) { b = 3 }
  1087. else if (e.button & 4) { b = 2 }
  1088. }
  1089. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1090. return b
  1091. }
  1092. // Detect drag-and-drop
  1093. var dragAndDrop = function() {
  1094. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1095. // couldn't get it to work yet.
  1096. if (ie && ie_version < 9) { return false }
  1097. var div = elt('div')
  1098. return "draggable" in div || "dragDrop" in div
  1099. }()
  1100. var zwspSupported
  1101. function zeroWidthElement(measure) {
  1102. if (zwspSupported == null) {
  1103. var test = elt("span", "\u200b")
  1104. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1105. if (measure.firstChild.offsetHeight != 0)
  1106. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1107. }
  1108. var node = zwspSupported ? elt("span", "\u200b") :
  1109. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1110. node.setAttribute("cm-text", "")
  1111. return node
  1112. }
  1113. // Feature-detect IE's crummy client rect reporting for bidi text
  1114. var badBidiRects
  1115. function hasBadBidiRects(measure) {
  1116. if (badBidiRects != null) { return badBidiRects }
  1117. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1118. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1119. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1120. removeChildren(measure)
  1121. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1122. return badBidiRects = (r1.right - r0.right < 3)
  1123. }
  1124. // See if "".split is the broken IE version, if so, provide an
  1125. // alternative way to split lines.
  1126. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1127. var pos = 0, result = [], l = string.length
  1128. while (pos <= l) {
  1129. var nl = string.indexOf("\n", pos)
  1130. if (nl == -1) { nl = string.length }
  1131. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1132. var rt = line.indexOf("\r")
  1133. if (rt != -1) {
  1134. result.push(line.slice(0, rt))
  1135. pos += rt + 1
  1136. } else {
  1137. result.push(line)
  1138. pos = nl + 1
  1139. }
  1140. }
  1141. return result
  1142. } : function (string) { return string.split(/\r\n?|\n/); }
  1143. var hasSelection = window.getSelection ? function (te) {
  1144. try { return te.selectionStart != te.selectionEnd }
  1145. catch(e) { return false }
  1146. } : function (te) {
  1147. var range
  1148. try {range = te.ownerDocument.selection.createRange()}
  1149. catch(e) {}
  1150. if (!range || range.parentElement() != te) { return false }
  1151. return range.compareEndPoints("StartToEnd", range) != 0
  1152. }
  1153. var hasCopyEvent = (function () {
  1154. var e = elt("div")
  1155. if ("oncopy" in e) { return true }
  1156. e.setAttribute("oncopy", "return;")
  1157. return typeof e.oncopy == "function"
  1158. })()
  1159. var badZoomedRects = null
  1160. function hasBadZoomedRects(measure) {
  1161. if (badZoomedRects != null) { return badZoomedRects }
  1162. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1163. var normal = node.getBoundingClientRect()
  1164. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1165. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1166. }
  1167. var modes = {};
  1168. var mimeModes = {};
  1169. // Extra arguments are stored as the mode's dependencies, which is
  1170. // used by (legacy) mechanisms like loadmode.js to automatically
  1171. // load a mode. (Preferred mechanism is the require/define calls.)
  1172. function defineMode(name, mode) {
  1173. if (arguments.length > 2)
  1174. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1175. modes[name] = mode
  1176. }
  1177. function defineMIME(mime, spec) {
  1178. mimeModes[mime] = spec
  1179. }
  1180. // Given a MIME type, a {name, ...options} config object, or a name
  1181. // string, return a mode config object.
  1182. function resolveMode(spec) {
  1183. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1184. spec = mimeModes[spec]
  1185. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1186. var found = mimeModes[spec.name]
  1187. if (typeof found == "string") { found = {name: found} }
  1188. spec = createObj(found, spec)
  1189. spec.name = found.name
  1190. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1191. return resolveMode("application/xml")
  1192. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1193. return resolveMode("application/json")
  1194. }
  1195. if (typeof spec == "string") { return {name: spec} }
  1196. else { return spec || {name: "null"} }
  1197. }
  1198. // Given a mode spec (anything that resolveMode accepts), find and
  1199. // initialize an actual mode object.
  1200. function getMode(options, spec) {
  1201. spec = resolveMode(spec)
  1202. var mfactory = modes[spec.name]
  1203. if (!mfactory) { return getMode(options, "text/plain") }
  1204. var modeObj = mfactory(options, spec)
  1205. if (modeExtensions.hasOwnProperty(spec.name)) {
  1206. var exts = modeExtensions[spec.name]
  1207. for (var prop in exts) {
  1208. if (!exts.hasOwnProperty(prop)) { continue }
  1209. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1210. modeObj[prop] = exts[prop]
  1211. }
  1212. }
  1213. modeObj.name = spec.name
  1214. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1215. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1216. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1217. return modeObj
  1218. }
  1219. // This can be used to attach properties to mode objects from
  1220. // outside the actual mode definition.
  1221. var modeExtensions = {}
  1222. function extendMode(mode, properties) {
  1223. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1224. copyObj(properties, exts)
  1225. }
  1226. function copyState(mode, state) {
  1227. if (state === true) { return state }
  1228. if (mode.copyState) { return mode.copyState(state) }
  1229. var nstate = {}
  1230. for (var n in state) {
  1231. var val = state[n]
  1232. if (val instanceof Array) { val = val.concat([]) }
  1233. nstate[n] = val
  1234. }
  1235. return nstate
  1236. }
  1237. // Given a mode and a state (for that mode), find the inner mode and
  1238. // state at the position that the state refers to.
  1239. function innerMode(mode, state) {
  1240. var info
  1241. while (mode.innerMode) {
  1242. info = mode.innerMode(state)
  1243. if (!info || info.mode == mode) { break }
  1244. state = info.state
  1245. mode = info.mode
  1246. }
  1247. return info || {mode: mode, state: state}
  1248. }
  1249. function startState(mode, a1, a2) {
  1250. return mode.startState ? mode.startState(a1, a2) : true
  1251. }
  1252. // STRING STREAM
  1253. // Fed to the mode parsers, provides helper functions to make
  1254. // parsers more succinct.
  1255. var StringStream = function(string, tabSize, lineOracle) {
  1256. this.pos = this.start = 0
  1257. this.string = string
  1258. this.tabSize = tabSize || 8
  1259. this.lastColumnPos = this.lastColumnValue = 0
  1260. this.lineStart = 0
  1261. this.lineOracle = lineOracle
  1262. };
  1263. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1264. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1265. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1266. StringStream.prototype.next = function () {
  1267. if (this.pos < this.string.length)
  1268. { return this.string.charAt(this.pos++) }
  1269. };
  1270. StringStream.prototype.eat = function (match) {
  1271. var ch = this.string.charAt(this.pos)
  1272. var ok
  1273. if (typeof match == "string") { ok = ch == match }
  1274. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1275. if (ok) {++this.pos; return ch}
  1276. };
  1277. StringStream.prototype.eatWhile = function (match) {
  1278. var start = this.pos
  1279. while (this.eat(match)){}
  1280. return this.pos > start
  1281. };
  1282. StringStream.prototype.eatSpace = function () {
  1283. var this$1 = this;
  1284. var start = this.pos
  1285. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1286. return this.pos > start
  1287. };
  1288. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
  1289. StringStream.prototype.skipTo = function (ch) {
  1290. var found = this.string.indexOf(ch, this.pos)
  1291. if (found > -1) {this.pos = found; return true}
  1292. };
  1293. StringStream.prototype.backUp = function (n) {this.pos -= n};
  1294. StringStream.prototype.column = function () {
  1295. if (this.lastColumnPos < this.start) {
  1296. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1297. this.lastColumnPos = this.start
  1298. }
  1299. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1300. };
  1301. StringStream.prototype.indentation = function () {
  1302. return countColumn(this.string, null, this.tabSize) -
  1303. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1304. };
  1305. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1306. if (typeof pattern == "string") {
  1307. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1308. var substr = this.string.substr(this.pos, pattern.length)
  1309. if (cased(substr) == cased(pattern)) {
  1310. if (consume !== false) { this.pos += pattern.length }
  1311. return true
  1312. }
  1313. } else {
  1314. var match = this.string.slice(this.pos).match(pattern)
  1315. if (match && match.index > 0) { return null }
  1316. if (match && consume !== false) { this.pos += match[0].length }
  1317. return match
  1318. }
  1319. };
  1320. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1321. StringStream.prototype.hideFirstChars = function (n, inner) {
  1322. this.lineStart += n
  1323. try { return inner() }
  1324. finally { this.lineStart -= n }
  1325. };
  1326. StringStream.prototype.lookAhead = function (n) {
  1327. var oracle = this.lineOracle
  1328. return oracle && oracle.lookAhead(n)
  1329. };
  1330. StringStream.prototype.baseToken = function () {
  1331. var oracle = this.lineOracle
  1332. return oracle && oracle.baseToken(this.pos)
  1333. };
  1334. var SavedContext = function(state, lookAhead) {
  1335. this.state = state
  1336. this.lookAhead = lookAhead
  1337. };
  1338. var Context = function(doc, state, line, lookAhead) {
  1339. this.state = state
  1340. this.doc = doc
  1341. this.line = line
  1342. this.maxLookAhead = lookAhead || 0
  1343. this.baseTokens = null
  1344. this.baseTokenPos = 1
  1345. };
  1346. Context.prototype.lookAhead = function (n) {
  1347. var line = this.doc.getLine(this.line + n)
  1348. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n }
  1349. return line
  1350. };
  1351. Context.prototype.baseToken = function (n) {
  1352. var this$1 = this;
  1353. if (!this.baseTokens) { return null }
  1354. while (this.baseTokens[this.baseTokenPos] <= n)
  1355. { this$1.baseTokenPos += 2 }
  1356. var type = this.baseTokens[this.baseTokenPos + 1]
  1357. return {type: type && type.replace(/( |^)overlay .*/, ""),
  1358. size: this.baseTokens[this.baseTokenPos] - n}
  1359. };
  1360. Context.prototype.nextLine = function () {
  1361. this.line++
  1362. if (this.maxLookAhead > 0) { this.maxLookAhead-- }
  1363. };
  1364. Context.fromSaved = function (doc, saved, line) {
  1365. if (saved instanceof SavedContext)
  1366. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1367. else
  1368. { return new Context(doc, copyState(doc.mode, saved), line) }
  1369. };
  1370. Context.prototype.save = function (copy) {
  1371. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
  1372. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1373. };
  1374. // Compute a style array (an array starting with a mode generation
  1375. // -- for invalidation -- followed by pairs of end positions and
  1376. // style strings), which is used to highlight the tokens on the
  1377. // line.
  1378. function highlightLine(cm, line, context, forceToEnd) {
  1379. // A styles array always starts with a number identifying the
  1380. // mode/overlays that it is based on (for easy invalidation).
  1381. var st = [cm.state.modeGen], lineClasses = {}
  1382. // Compute the base array of styles
  1383. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1384. lineClasses, forceToEnd)
  1385. var state = context.state
  1386. // Run overlays, adjust style array.
  1387. var loop = function ( o ) {
  1388. context.baseTokens = st
  1389. var overlay = cm.state.overlays[o], i = 1, at = 0
  1390. context.state = true
  1391. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1392. var start = i
  1393. // Ensure there's a token end at the current position, and that i points at it
  1394. while (at < end) {
  1395. var i_end = st[i]
  1396. if (i_end > end)
  1397. { st.splice(i, 1, end, st[i+1], i_end) }
  1398. i += 2
  1399. at = Math.min(end, i_end)
  1400. }
  1401. if (!style) { return }
  1402. if (overlay.opaque) {
  1403. st.splice(start, i - start, end, "overlay " + style)
  1404. i = start + 2
  1405. } else {
  1406. for (; start < i; start += 2) {
  1407. var cur = st[start+1]
  1408. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1409. }
  1410. }
  1411. }, lineClasses)
  1412. context.state = state
  1413. context.baseTokens = null
  1414. context.baseTokenPos = 1
  1415. };
  1416. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1417. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1418. }
  1419. function getLineStyles(cm, line, updateFrontier) {
  1420. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1421. var context = getContextBefore(cm, lineNo(line))
  1422. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
  1423. var result = highlightLine(cm, line, context)
  1424. if (resetState) { context.state = resetState }
  1425. line.stateAfter = context.save(!resetState)
  1426. line.styles = result.styles
  1427. if (result.classes) { line.styleClasses = result.classes }
  1428. else if (line.styleClasses) { line.styleClasses = null }
  1429. if (updateFrontier === cm.doc.highlightFrontier)
  1430. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) }
  1431. }
  1432. return line.styles
  1433. }
  1434. function getContextBefore(cm, n, precise) {
  1435. var doc = cm.doc, display = cm.display
  1436. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1437. var start = findStartLine(cm, n, precise)
  1438. var saved = start > doc.first && getLine(doc, start - 1).stateAfter
  1439. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
  1440. doc.iter(start, n, function (line) {
  1441. processLine(cm, line.text, context)
  1442. var pos = context.line
  1443. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null
  1444. context.nextLine()
  1445. })
  1446. if (precise) { doc.modeFrontier = context.line }
  1447. return context
  1448. }
  1449. // Lightweight form of highlight -- proceed over this line and
  1450. // update state, but don't save a style array. Used for lines that
  1451. // aren't currently visible.
  1452. function processLine(cm, text, context, startAt) {
  1453. var mode = cm.doc.mode
  1454. var stream = new StringStream(text, cm.options.tabSize, context)
  1455. stream.start = stream.pos = startAt || 0
  1456. if (text == "") { callBlankLine(mode, context.state) }
  1457. while (!stream.eol()) {
  1458. readToken(mode, stream, context.state)
  1459. stream.start = stream.pos
  1460. }
  1461. }
  1462. function callBlankLine(mode, state) {
  1463. if (mode.blankLine) { return mode.blankLine(state) }
  1464. if (!mode.innerMode) { return }
  1465. var inner = innerMode(mode, state)
  1466. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1467. }
  1468. function readToken(mode, stream, state, inner) {
  1469. for (var i = 0; i < 10; i++) {
  1470. if (inner) { inner[0] = innerMode(mode, state).mode }
  1471. var style = mode.token(stream, state)
  1472. if (stream.pos > stream.start) { return style }
  1473. }
  1474. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1475. }
  1476. var Token = function(stream, type, state) {
  1477. this.start = stream.start; this.end = stream.pos
  1478. this.string = stream.current()
  1479. this.type = type || null
  1480. this.state = state
  1481. };
  1482. // Utility for getTokenAt and getLineTokens
  1483. function takeToken(cm, pos, precise, asArray) {
  1484. var doc = cm.doc, mode = doc.mode, style
  1485. pos = clipPos(doc, pos)
  1486. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)
  1487. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens
  1488. if (asArray) { tokens = [] }
  1489. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1490. stream.start = stream.pos
  1491. style = readToken(mode, stream, context.state)
  1492. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) }
  1493. }
  1494. return asArray ? tokens : new Token(stream, style, context.state)
  1495. }
  1496. function extractLineClasses(type, output) {
  1497. if (type) { for (;;) {
  1498. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1499. if (!lineClass) { break }
  1500. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1501. var prop = lineClass[1] ? "bgClass" : "textClass"
  1502. if (output[prop] == null)
  1503. { output[prop] = lineClass[2] }
  1504. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1505. { output[prop] += " " + lineClass[2] }
  1506. } }
  1507. return type
  1508. }
  1509. // Run the given mode's parser over a line, calling f for each token.
  1510. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1511. var flattenSpans = mode.flattenSpans
  1512. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1513. var curStart = 0, curStyle = null
  1514. var stream = new StringStream(text, cm.options.tabSize, context), style
  1515. var inner = cm.options.addModeClass && [null]
  1516. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) }
  1517. while (!stream.eol()) {
  1518. if (stream.pos > cm.options.maxHighlightLength) {
  1519. flattenSpans = false
  1520. if (forceToEnd) { processLine(cm, text, context, stream.pos) }
  1521. stream.pos = text.length
  1522. style = null
  1523. } else {
  1524. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
  1525. }
  1526. if (inner) {
  1527. var mName = inner[0].name
  1528. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1529. }
  1530. if (!flattenSpans || curStyle != style) {
  1531. while (curStart < stream.start) {
  1532. curStart = Math.min(stream.start, curStart + 5000)
  1533. f(curStart, curStyle)
  1534. }
  1535. curStyle = style
  1536. }
  1537. stream.start = stream.pos
  1538. }
  1539. while (curStart < stream.pos) {
  1540. // Webkit seems to refuse to render text nodes longer than 57444
  1541. // characters, and returns inaccurate measurements in nodes
  1542. // starting around 5000 chars.
  1543. var pos = Math.min(stream.pos, curStart + 5000)
  1544. f(pos, curStyle)
  1545. curStart = pos
  1546. }
  1547. }
  1548. // Finds the line to start with when starting a parse. Tries to
  1549. // find a line with a stateAfter, so that it can start with a
  1550. // valid state. If that fails, it returns the line with the
  1551. // smallest indentation, which tends to need the least context to
  1552. // parse correctly.
  1553. function findStartLine(cm, n, precise) {
  1554. var minindent, minline, doc = cm.doc
  1555. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1556. for (var search = n; search > lim; --search) {
  1557. if (search <= doc.first) { return doc.first }
  1558. var line = getLine(doc, search - 1), after = line.stateAfter
  1559. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1560. { return search }
  1561. var indented = countColumn(line.text, null, cm.options.tabSize)
  1562. if (minline == null || minindent > indented) {
  1563. minline = search - 1
  1564. minindent = indented
  1565. }
  1566. }
  1567. return minline
  1568. }
  1569. function retreatFrontier(doc, n) {
  1570. doc.modeFrontier = Math.min(doc.modeFrontier, n)
  1571. if (doc.highlightFrontier < n - 10) { return }
  1572. var start = doc.first
  1573. for (var line = n - 1; line > start; line--) {
  1574. var saved = getLine(doc, line).stateAfter
  1575. // change is on 3
  1576. // state on line 1 looked ahead 2 -- so saw 3
  1577. // test 1 + 2 < 3 should cover this
  1578. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1579. start = line + 1
  1580. break
  1581. }
  1582. }
  1583. doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
  1584. }
  1585. // LINE DATA STRUCTURE
  1586. // Line objects. These hold state related to a line, including
  1587. // highlighting info (the styles array).
  1588. var Line = function(text, markedSpans, estimateHeight) {
  1589. this.text = text
  1590. attachMarkedSpans(this, markedSpans)
  1591. this.height = estimateHeight ? estimateHeight(this) : 1
  1592. };
  1593. Line.prototype.lineNo = function () { return lineNo(this) };
  1594. eventMixin(Line)
  1595. // Change the content (text, markers) of a line. Automatically
  1596. // invalidates cached information and tries to re-estimate the
  1597. // line's height.
  1598. function updateLine(line, text, markedSpans, estimateHeight) {
  1599. line.text = text
  1600. if (line.stateAfter) { line.stateAfter = null }
  1601. if (line.styles) { line.styles = null }
  1602. if (line.order != null) { line.order = null }
  1603. detachMarkedSpans(line)
  1604. attachMarkedSpans(line, markedSpans)
  1605. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1606. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1607. }
  1608. // Detach a line from the document tree and its markers.
  1609. function cleanUpLine(line) {
  1610. line.parent = null
  1611. detachMarkedSpans(line)
  1612. }
  1613. // Convert a style as returned by a mode (either null, or a string
  1614. // containing one or more styles) to a CSS style. This is cached,
  1615. // and also looks for line-wide styles.
  1616. var styleToClassCache = {};
  1617. var styleToClassCacheWithMode = {};
  1618. function interpretTokenStyle(style, options) {
  1619. if (!style || /^\s*$/.test(style)) { return null }
  1620. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1621. return cache[style] ||
  1622. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1623. }
  1624. // Render the DOM representation of the text of a line. Also builds
  1625. // up a 'line map', which points at the DOM nodes that represent
  1626. // specific stretches of text, and is used by the measuring code.
  1627. // The returned object contains the DOM node, this map, and
  1628. // information about line-wide styles that were set by the mode.
  1629. function buildLineContent(cm, lineView) {
  1630. // The padding-right forces the element to have a 'border', which
  1631. // is needed on Webkit to be able to get line-level bounding
  1632. // rectangles for it (in measureChar).
  1633. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null)
  1634. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1635. col: 0, pos: 0, cm: cm,
  1636. trailingSpace: false,
  1637. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1638. lineView.measure = {}
  1639. // Iterate over the logical lines that make up this visual line.
  1640. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1641. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1642. builder.pos = 0
  1643. builder.addToken = buildToken
  1644. // Optionally wire in some hacks into the token-rendering
  1645. // algorithm, to deal with browser quirks.
  1646. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1647. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1648. builder.map = []
  1649. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1650. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1651. if (line.styleClasses) {
  1652. if (line.styleClasses.bgClass)
  1653. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1654. if (line.styleClasses.textClass)
  1655. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1656. }
  1657. // Ensure at least a single node is present, for measuring.
  1658. if (builder.map.length == 0)
  1659. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1660. // Store the map and a cache object for the current logical line
  1661. if (i == 0) {
  1662. lineView.measure.map = builder.map
  1663. lineView.measure.cache = {}
  1664. } else {
  1665. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1666. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1667. }
  1668. }
  1669. // See issue #2901
  1670. if (webkit) {
  1671. var last = builder.content.lastChild
  1672. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1673. { builder.content.className = "cm-tab-wrap-hack" }
  1674. }
  1675. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1676. if (builder.pre.className)
  1677. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1678. return builder
  1679. }
  1680. function defaultSpecialCharPlaceholder(ch) {
  1681. var token = elt("span", "\u2022", "cm-invalidchar")
  1682. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1683. token.setAttribute("aria-label", token.title)
  1684. return token
  1685. }
  1686. // Build up the DOM representation for a single token, and add it to
  1687. // the line map. Takes care to render special characters separately.
  1688. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1689. if (!text) { return }
  1690. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1691. var special = builder.cm.state.specialChars, mustWrap = false
  1692. var content
  1693. if (!special.test(text)) {
  1694. builder.col += text.length
  1695. content = document.createTextNode(displayText)
  1696. builder.map.push(builder.pos, builder.pos + text.length, content)
  1697. if (ie && ie_version < 9) { mustWrap = true }
  1698. builder.pos += text.length
  1699. } else {
  1700. content = document.createDocumentFragment()
  1701. var pos = 0
  1702. while (true) {
  1703. special.lastIndex = pos
  1704. var m = special.exec(text)
  1705. var skipped = m ? m.index - pos : text.length - pos
  1706. if (skipped) {
  1707. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1708. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1709. else { content.appendChild(txt) }
  1710. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1711. builder.col += skipped
  1712. builder.pos += skipped
  1713. }
  1714. if (!m) { break }
  1715. pos += skipped + 1
  1716. var txt$1 = (void 0)
  1717. if (m[0] == "\t") {
  1718. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1719. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1720. txt$1.setAttribute("role", "presentation")
  1721. txt$1.setAttribute("cm-text", "\t")
  1722. builder.col += tabWidth
  1723. } else if (m[0] == "\r" || m[0] == "\n") {
  1724. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1725. txt$1.setAttribute("cm-text", m[0])
  1726. builder.col += 1
  1727. } else {
  1728. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1729. txt$1.setAttribute("cm-text", m[0])
  1730. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1731. else { content.appendChild(txt$1) }
  1732. builder.col += 1
  1733. }
  1734. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1735. builder.pos++
  1736. }
  1737. }
  1738. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1739. if (style || startStyle || endStyle || mustWrap || css) {
  1740. var fullStyle = style || ""
  1741. if (startStyle) { fullStyle += startStyle }
  1742. if (endStyle) { fullStyle += endStyle }
  1743. var token = elt("span", [content], fullStyle, css)
  1744. if (title) { token.title = title }
  1745. return builder.content.appendChild(token)
  1746. }
  1747. builder.content.appendChild(content)
  1748. }
  1749. function splitSpaces(text, trailingBefore) {
  1750. if (text.length > 1 && !/ /.test(text)) { return text }
  1751. var spaceBefore = trailingBefore, result = ""
  1752. for (var i = 0; i < text.length; i++) {
  1753. var ch = text.charAt(i)
  1754. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1755. { ch = "\u00a0" }
  1756. result += ch
  1757. spaceBefore = ch == " "
  1758. }
  1759. return result
  1760. }
  1761. // Work around nonsense dimensions being reported for stretches of
  1762. // right-to-left text.
  1763. function buildTokenBadBidi(inner, order) {
  1764. return function (builder, text, style, startStyle, endStyle, title, css) {
  1765. style = style ? style + " cm-force-border" : "cm-force-border"
  1766. var start = builder.pos, end = start + text.length
  1767. for (;;) {
  1768. // Find the part that overlaps with the start of this text
  1769. var part = (void 0)
  1770. for (var i = 0; i < order.length; i++) {
  1771. part = order[i]
  1772. if (part.to > start && part.from <= start) { break }
  1773. }
  1774. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1775. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1776. startStyle = null
  1777. text = text.slice(part.to - start)
  1778. start = part.to
  1779. }
  1780. }
  1781. }
  1782. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1783. var widget = !ignoreWidget && marker.widgetNode
  1784. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1785. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1786. if (!widget)
  1787. { widget = builder.content.appendChild(document.createElement("span")) }
  1788. widget.setAttribute("cm-marker", marker.id)
  1789. }
  1790. if (widget) {
  1791. builder.cm.display.input.setUneditable(widget)
  1792. builder.content.appendChild(widget)
  1793. }
  1794. builder.pos += size
  1795. builder.trailingSpace = false
  1796. }
  1797. // Outputs a number of spans to make up a line, taking highlighting
  1798. // and marked text into account.
  1799. function insertLineContent(line, builder, styles) {
  1800. var spans = line.markedSpans, allText = line.text, at = 0
  1801. if (!spans) {
  1802. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1803. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1804. return
  1805. }
  1806. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1807. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1808. for (;;) {
  1809. if (nextChange == pos) { // Update current marker set
  1810. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1811. collapsed = null; nextChange = Infinity
  1812. var foundBookmarks = [], endStyles = (void 0)
  1813. for (var j = 0; j < spans.length; ++j) {
  1814. var sp = spans[j], m = sp.marker
  1815. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1816. foundBookmarks.push(m)
  1817. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1818. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1819. nextChange = sp.to
  1820. spanEndStyle = ""
  1821. }
  1822. if (m.className) { spanStyle += " " + m.className }
  1823. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1824. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1825. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1826. if (m.title && !title) { title = m.title }
  1827. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1828. { collapsed = sp }
  1829. } else if (sp.from > pos && nextChange > sp.from) {
  1830. nextChange = sp.from
  1831. }
  1832. }
  1833. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1834. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1835. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1836. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1837. if (collapsed && (collapsed.from || 0) == pos) {
  1838. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1839. collapsed.marker, collapsed.from == null)
  1840. if (collapsed.to == null) { return }
  1841. if (collapsed.to == pos) { collapsed = false }
  1842. }
  1843. }
  1844. if (pos >= len) { break }
  1845. var upto = Math.min(len, nextChange)
  1846. while (true) {
  1847. if (text) {
  1848. var end = pos + text.length
  1849. if (!collapsed) {
  1850. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1851. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1852. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1853. }
  1854. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1855. pos = end
  1856. spanStartStyle = ""
  1857. }
  1858. text = allText.slice(at, at = styles[i++])
  1859. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1860. }
  1861. }
  1862. }
  1863. // These objects are used to represent the visible (currently drawn)
  1864. // part of the document. A LineView may correspond to multiple
  1865. // logical lines, if those are connected by collapsed ranges.
  1866. function LineView(doc, line, lineN) {
  1867. // The starting line
  1868. this.line = line
  1869. // Continuing lines, if any
  1870. this.rest = visualLineContinued(line)
  1871. // Number of logical lines in this visual line
  1872. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1873. this.node = this.text = null
  1874. this.hidden = lineIsHidden(doc, line)
  1875. }
  1876. // Create a range of LineView objects for the given lines.
  1877. function buildViewArray(cm, from, to) {
  1878. var array = [], nextPos
  1879. for (var pos = from; pos < to; pos = nextPos) {
  1880. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1881. nextPos = pos + view.size
  1882. array.push(view)
  1883. }
  1884. return array
  1885. }
  1886. var operationGroup = null
  1887. function pushOperation(op) {
  1888. if (operationGroup) {
  1889. operationGroup.ops.push(op)
  1890. } else {
  1891. op.ownsGroup = operationGroup = {
  1892. ops: [op],
  1893. delayedCallbacks: []
  1894. }
  1895. }
  1896. }
  1897. function fireCallbacksForOps(group) {
  1898. // Calls delayed callbacks and cursorActivity handlers until no
  1899. // new ones appear
  1900. var callbacks = group.delayedCallbacks, i = 0
  1901. do {
  1902. for (; i < callbacks.length; i++)
  1903. { callbacks[i].call(null) }
  1904. for (var j = 0; j < group.ops.length; j++) {
  1905. var op = group.ops[j]
  1906. if (op.cursorActivityHandlers)
  1907. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1908. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1909. }
  1910. } while (i < callbacks.length)
  1911. }
  1912. function finishOperation(op, endCb) {
  1913. var group = op.ownsGroup
  1914. if (!group) { return }
  1915. try { fireCallbacksForOps(group) }
  1916. finally {
  1917. operationGroup = null
  1918. endCb(group)
  1919. }
  1920. }
  1921. var orphanDelayedCallbacks = null
  1922. // Often, we want to signal events at a point where we are in the
  1923. // middle of some work, but don't want the handler to start calling
  1924. // other methods on the editor, which might be in an inconsistent
  1925. // state or simply not expect any other events to happen.
  1926. // signalLater looks whether there are any handlers, and schedules
  1927. // them to be executed when the last operation ends, or, if no
  1928. // operation is active, when a timeout fires.
  1929. function signalLater(emitter, type /*, values...*/) {
  1930. var arr = getHandlers(emitter, type)
  1931. if (!arr.length) { return }
  1932. var args = Array.prototype.slice.call(arguments, 2), list
  1933. if (operationGroup) {
  1934. list = operationGroup.delayedCallbacks
  1935. } else if (orphanDelayedCallbacks) {
  1936. list = orphanDelayedCallbacks
  1937. } else {
  1938. list = orphanDelayedCallbacks = []
  1939. setTimeout(fireOrphanDelayed, 0)
  1940. }
  1941. var loop = function ( i ) {
  1942. list.push(function () { return arr[i].apply(null, args); })
  1943. };
  1944. for (var i = 0; i < arr.length; ++i)
  1945. loop( i );
  1946. }
  1947. function fireOrphanDelayed() {
  1948. var delayed = orphanDelayedCallbacks
  1949. orphanDelayedCallbacks = null
  1950. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1951. }
  1952. // When an aspect of a line changes, a string is added to
  1953. // lineView.changes. This updates the relevant part of the line's
  1954. // DOM structure.
  1955. function updateLineForChanges(cm, lineView, lineN, dims) {
  1956. for (var j = 0; j < lineView.changes.length; j++) {
  1957. var type = lineView.changes[j]
  1958. if (type == "text") { updateLineText(cm, lineView) }
  1959. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1960. else if (type == "class") { updateLineClasses(cm, lineView) }
  1961. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1962. }
  1963. lineView.changes = null
  1964. }
  1965. // Lines with gutter elements, widgets or a background class need to
  1966. // be wrapped, and have the extra elements added to the wrapper div
  1967. function ensureLineWrapped(lineView) {
  1968. if (lineView.node == lineView.text) {
  1969. lineView.node = elt("div", null, null, "position: relative")
  1970. if (lineView.text.parentNode)
  1971. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1972. lineView.node.appendChild(lineView.text)
  1973. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1974. }
  1975. return lineView.node
  1976. }
  1977. function updateLineBackground(cm, lineView) {
  1978. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1979. if (cls) { cls += " CodeMirror-linebackground" }
  1980. if (lineView.background) {
  1981. if (cls) { lineView.background.className = cls }
  1982. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1983. } else if (cls) {
  1984. var wrap = ensureLineWrapped(lineView)
  1985. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1986. cm.display.input.setUneditable(lineView.background)
  1987. }
  1988. }
  1989. // Wrapper around buildLineContent which will reuse the structure
  1990. // in display.externalMeasured when possible.
  1991. function getLineContent(cm, lineView) {
  1992. var ext = cm.display.externalMeasured
  1993. if (ext && ext.line == lineView.line) {
  1994. cm.display.externalMeasured = null
  1995. lineView.measure = ext.measure
  1996. return ext.built
  1997. }
  1998. return buildLineContent(cm, lineView)
  1999. }
  2000. // Redraw the line's text. Interacts with the background and text
  2001. // classes because the mode may output tokens that influence these
  2002. // classes.
  2003. function updateLineText(cm, lineView) {
  2004. var cls = lineView.text.className
  2005. var built = getLineContent(cm, lineView)
  2006. if (lineView.text == lineView.node) { lineView.node = built.pre }
  2007. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2008. lineView.text = built.pre
  2009. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2010. lineView.bgClass = built.bgClass
  2011. lineView.textClass = built.textClass
  2012. updateLineClasses(cm, lineView)
  2013. } else if (cls) {
  2014. lineView.text.className = cls
  2015. }
  2016. }
  2017. function updateLineClasses(cm, lineView) {
  2018. updateLineBackground(cm, lineView)
  2019. if (lineView.line.wrapClass)
  2020. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  2021. else if (lineView.node != lineView.text)
  2022. { lineView.node.className = "" }
  2023. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  2024. lineView.text.className = textClass || ""
  2025. }
  2026. function updateLineGutter(cm, lineView, lineN, dims) {
  2027. if (lineView.gutter) {
  2028. lineView.node.removeChild(lineView.gutter)
  2029. lineView.gutter = null
  2030. }
  2031. if (lineView.gutterBackground) {
  2032. lineView.node.removeChild(lineView.gutterBackground)
  2033. lineView.gutterBackground = null
  2034. }
  2035. if (lineView.line.gutterClass) {
  2036. var wrap = ensureLineWrapped(lineView)
  2037. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2038. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  2039. cm.display.input.setUneditable(lineView.gutterBackground)
  2040. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2041. }
  2042. var markers = lineView.line.gutterMarkers
  2043. if (cm.options.lineNumbers || markers) {
  2044. var wrap$1 = ensureLineWrapped(lineView)
  2045. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  2046. cm.display.input.setUneditable(gutterWrap)
  2047. wrap$1.insertBefore(gutterWrap, lineView.text)
  2048. if (lineView.line.gutterClass)
  2049. { gutterWrap.className += " " + lineView.line.gutterClass }
  2050. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2051. { lineView.lineNumber = gutterWrap.appendChild(
  2052. elt("div", lineNumberFor(cm.options, lineN),
  2053. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2054. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2055. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2056. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2057. if (found)
  2058. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2059. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2060. } }
  2061. }
  2062. }
  2063. function updateLineWidgets(cm, lineView, dims) {
  2064. if (lineView.alignable) { lineView.alignable = null }
  2065. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2066. next = node.nextSibling
  2067. if (node.className == "CodeMirror-linewidget")
  2068. { lineView.node.removeChild(node) }
  2069. }
  2070. insertLineWidgets(cm, lineView, dims)
  2071. }
  2072. // Build a line's DOM representation from scratch
  2073. function buildLineElement(cm, lineView, lineN, dims) {
  2074. var built = getLineContent(cm, lineView)
  2075. lineView.text = lineView.node = built.pre
  2076. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2077. if (built.textClass) { lineView.textClass = built.textClass }
  2078. updateLineClasses(cm, lineView)
  2079. updateLineGutter(cm, lineView, lineN, dims)
  2080. insertLineWidgets(cm, lineView, dims)
  2081. return lineView.node
  2082. }
  2083. // A lineView may contain multiple logical lines (when merged by
  2084. // collapsed spans). The widgets for all of them need to be drawn.
  2085. function insertLineWidgets(cm, lineView, dims) {
  2086. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2087. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2088. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2089. }
  2090. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2091. if (!line.widgets) { return }
  2092. var wrap = ensureLineWrapped(lineView)
  2093. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2094. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2095. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2096. positionLineWidget(widget, node, lineView, dims)
  2097. cm.display.input.setUneditable(node)
  2098. if (allowAbove && widget.above)
  2099. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2100. else
  2101. { wrap.appendChild(node) }
  2102. signalLater(widget, "redraw")
  2103. }
  2104. }
  2105. function positionLineWidget(widget, node, lineView, dims) {
  2106. if (widget.noHScroll) {
  2107. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2108. var width = dims.wrapperWidth
  2109. node.style.left = dims.fixedPos + "px"
  2110. if (!widget.coverGutter) {
  2111. width -= dims.gutterTotalWidth
  2112. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2113. }
  2114. node.style.width = width + "px"
  2115. }
  2116. if (widget.coverGutter) {
  2117. node.style.zIndex = 5
  2118. node.style.position = "relative"
  2119. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2120. }
  2121. }
  2122. function widgetHeight(widget) {
  2123. if (widget.height != null) { return widget.height }
  2124. var cm = widget.doc.cm
  2125. if (!cm) { return 0 }
  2126. if (!contains(document.body, widget.node)) {
  2127. var parentStyle = "position: relative;"
  2128. if (widget.coverGutter)
  2129. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2130. if (widget.noHScroll)
  2131. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2132. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2133. }
  2134. return widget.height = widget.node.parentNode.offsetHeight
  2135. }
  2136. // Return true when the given mouse event happened in a widget
  2137. function eventInWidget(display, e) {
  2138. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2139. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2140. (n.parentNode == display.sizer && n != display.mover))
  2141. { return true }
  2142. }
  2143. }
  2144. // POSITION MEASUREMENT
  2145. function paddingTop(display) {return display.lineSpace.offsetTop}
  2146. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2147. function paddingH(display) {
  2148. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2149. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2150. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2151. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2152. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2153. return data
  2154. }
  2155. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2156. function displayWidth(cm) {
  2157. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2158. }
  2159. function displayHeight(cm) {
  2160. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2161. }
  2162. // Ensure the lineView.wrapping.heights array is populated. This is
  2163. // an array of bottom offsets for the lines that make up a drawn
  2164. // line. When lineWrapping is on, there might be more than one
  2165. // height.
  2166. function ensureLineHeights(cm, lineView, rect) {
  2167. var wrapping = cm.options.lineWrapping
  2168. var curWidth = wrapping && displayWidth(cm)
  2169. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2170. var heights = lineView.measure.heights = []
  2171. if (wrapping) {
  2172. lineView.measure.width = curWidth
  2173. var rects = lineView.text.firstChild.getClientRects()
  2174. for (var i = 0; i < rects.length - 1; i++) {
  2175. var cur = rects[i], next = rects[i + 1]
  2176. if (Math.abs(cur.bottom - next.bottom) > 2)
  2177. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2178. }
  2179. }
  2180. heights.push(rect.bottom - rect.top)
  2181. }
  2182. }
  2183. // Find a line map (mapping character offsets to text nodes) and a
  2184. // measurement cache for the given line number. (A line view might
  2185. // contain multiple lines when collapsed ranges are present.)
  2186. function mapFromLineView(lineView, line, lineN) {
  2187. if (lineView.line == line)
  2188. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2189. for (var i = 0; i < lineView.rest.length; i++)
  2190. { if (lineView.rest[i] == line)
  2191. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2192. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2193. { if (lineNo(lineView.rest[i$1]) > lineN)
  2194. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2195. }
  2196. // Render a line into the hidden node display.externalMeasured. Used
  2197. // when measurement is needed for a line that's not in the viewport.
  2198. function updateExternalMeasurement(cm, line) {
  2199. line = visualLine(line)
  2200. var lineN = lineNo(line)
  2201. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2202. view.lineN = lineN
  2203. var built = view.built = buildLineContent(cm, view)
  2204. view.text = built.pre
  2205. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2206. return view
  2207. }
  2208. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2209. // for a given character.
  2210. function measureChar(cm, line, ch, bias) {
  2211. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2212. }
  2213. // Find a line view that corresponds to the given line number.
  2214. function findViewForLine(cm, lineN) {
  2215. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2216. { return cm.display.view[findViewIndex(cm, lineN)] }
  2217. var ext = cm.display.externalMeasured
  2218. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2219. { return ext }
  2220. }
  2221. // Measurement can be split in two steps, the set-up work that
  2222. // applies to the whole line, and the measurement of the actual
  2223. // character. Functions like coordsChar, that need to do a lot of
  2224. // measurements in a row, can thus ensure that the set-up work is
  2225. // only done once.
  2226. function prepareMeasureForLine(cm, line) {
  2227. var lineN = lineNo(line)
  2228. var view = findViewForLine(cm, lineN)
  2229. if (view && !view.text) {
  2230. view = null
  2231. } else if (view && view.changes) {
  2232. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2233. cm.curOp.forceUpdate = true
  2234. }
  2235. if (!view)
  2236. { view = updateExternalMeasurement(cm, line) }
  2237. var info = mapFromLineView(view, line, lineN)
  2238. return {
  2239. line: line, view: view, rect: null,
  2240. map: info.map, cache: info.cache, before: info.before,
  2241. hasHeights: false
  2242. }
  2243. }
  2244. // Given a prepared measurement object, measures the position of an
  2245. // actual character (or fetches it from the cache).
  2246. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2247. if (prepared.before) { ch = -1 }
  2248. var key = ch + (bias || ""), found
  2249. if (prepared.cache.hasOwnProperty(key)) {
  2250. found = prepared.cache[key]
  2251. } else {
  2252. if (!prepared.rect)
  2253. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2254. if (!prepared.hasHeights) {
  2255. ensureLineHeights(cm, prepared.view, prepared.rect)
  2256. prepared.hasHeights = true
  2257. }
  2258. found = measureCharInner(cm, prepared, ch, bias)
  2259. if (!found.bogus) { prepared.cache[key] = found }
  2260. }
  2261. return {left: found.left, right: found.right,
  2262. top: varHeight ? found.rtop : found.top,
  2263. bottom: varHeight ? found.rbottom : found.bottom}
  2264. }
  2265. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2266. function nodeAndOffsetInLineMap(map, ch, bias) {
  2267. var node, start, end, collapse, mStart, mEnd
  2268. // First, search the line map for the text node corresponding to,
  2269. // or closest to, the target character.
  2270. for (var i = 0; i < map.length; i += 3) {
  2271. mStart = map[i]
  2272. mEnd = map[i + 1]
  2273. if (ch < mStart) {
  2274. start = 0; end = 1
  2275. collapse = "left"
  2276. } else if (ch < mEnd) {
  2277. start = ch - mStart
  2278. end = start + 1
  2279. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2280. end = mEnd - mStart
  2281. start = end - 1
  2282. if (ch >= mEnd) { collapse = "right" }
  2283. }
  2284. if (start != null) {
  2285. node = map[i + 2]
  2286. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2287. { collapse = bias }
  2288. if (bias == "left" && start == 0)
  2289. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2290. node = map[(i -= 3) + 2]
  2291. collapse = "left"
  2292. } }
  2293. if (bias == "right" && start == mEnd - mStart)
  2294. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2295. node = map[(i += 3) + 2]
  2296. collapse = "right"
  2297. } }
  2298. break
  2299. }
  2300. }
  2301. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2302. }
  2303. function getUsefulRect(rects, bias) {
  2304. var rect = nullRect
  2305. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2306. if ((rect = rects[i]).left != rect.right) { break }
  2307. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2308. if ((rect = rects[i$1]).left != rect.right) { break }
  2309. } }
  2310. return rect
  2311. }
  2312. function measureCharInner(cm, prepared, ch, bias) {
  2313. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2314. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2315. var rect
  2316. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2317. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2318. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2319. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2320. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2321. { rect = node.parentNode.getBoundingClientRect() }
  2322. else
  2323. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2324. if (rect.left || rect.right || start == 0) { break }
  2325. end = start
  2326. start = start - 1
  2327. collapse = "right"
  2328. }
  2329. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2330. } else { // If it is a widget, simply get the box for the whole widget.
  2331. if (start > 0) { collapse = bias = "right" }
  2332. var rects
  2333. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2334. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2335. else
  2336. { rect = node.getBoundingClientRect() }
  2337. }
  2338. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2339. var rSpan = node.parentNode.getClientRects()[0]
  2340. if (rSpan)
  2341. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2342. else
  2343. { rect = nullRect }
  2344. }
  2345. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2346. var mid = (rtop + rbot) / 2
  2347. var heights = prepared.view.measure.heights
  2348. var i = 0
  2349. for (; i < heights.length - 1; i++)
  2350. { if (mid < heights[i]) { break } }
  2351. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2352. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2353. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2354. top: top, bottom: bot}
  2355. if (!rect.left && !rect.right) { result.bogus = true }
  2356. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2357. return result
  2358. }
  2359. // Work around problem with bounding client rects on ranges being
  2360. // returned incorrectly when zoomed on IE10 and below.
  2361. function maybeUpdateRectForZooming(measure, rect) {
  2362. if (!window.screen || screen.logicalXDPI == null ||
  2363. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2364. { return rect }
  2365. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2366. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2367. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2368. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2369. }
  2370. function clearLineMeasurementCacheFor(lineView) {
  2371. if (lineView.measure) {
  2372. lineView.measure.cache = {}
  2373. lineView.measure.heights = null
  2374. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2375. { lineView.measure.caches[i] = {} } }
  2376. }
  2377. }
  2378. function clearLineMeasurementCache(cm) {
  2379. cm.display.externalMeasure = null
  2380. removeChildren(cm.display.lineMeasure)
  2381. for (var i = 0; i < cm.display.view.length; i++)
  2382. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2383. }
  2384. function clearCaches(cm) {
  2385. clearLineMeasurementCache(cm)
  2386. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2387. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2388. cm.display.lineNumChars = null
  2389. }
  2390. function pageScrollX() {
  2391. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2392. // which causes page_Offset and bounding client rects to use
  2393. // different reference viewports and invalidate our calculations.
  2394. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2395. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2396. }
  2397. function pageScrollY() {
  2398. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2399. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2400. }
  2401. function widgetTopHeight(lineObj) {
  2402. var height = 0
  2403. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2404. { height += widgetHeight(lineObj.widgets[i]) } } }
  2405. return height
  2406. }
  2407. // Converts a {top, bottom, left, right} box from line-local
  2408. // coordinates into another coordinate system. Context may be one of
  2409. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2410. // or "page".
  2411. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2412. if (!includeWidgets) {
  2413. var height = widgetTopHeight(lineObj)
  2414. rect.top += height; rect.bottom += height
  2415. }
  2416. if (context == "line") { return rect }
  2417. if (!context) { context = "local" }
  2418. var yOff = heightAtLine(lineObj)
  2419. if (context == "local") { yOff += paddingTop(cm.display) }
  2420. else { yOff -= cm.display.viewOffset }
  2421. if (context == "page" || context == "window") {
  2422. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2423. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2424. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2425. rect.left += xOff; rect.right += xOff
  2426. }
  2427. rect.top += yOff; rect.bottom += yOff
  2428. return rect
  2429. }
  2430. // Coverts a box from "div" coords to another coordinate system.
  2431. // Context may be "window", "page", "div", or "local"./null.
  2432. function fromCoordSystem(cm, coords, context) {
  2433. if (context == "div") { return coords }
  2434. var left = coords.left, top = coords.top
  2435. // First move into "page" coordinate system
  2436. if (context == "page") {
  2437. left -= pageScrollX()
  2438. top -= pageScrollY()
  2439. } else if (context == "local" || !context) {
  2440. var localBox = cm.display.sizer.getBoundingClientRect()
  2441. left += localBox.left
  2442. top += localBox.top
  2443. }
  2444. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2445. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2446. }
  2447. function charCoords(cm, pos, context, lineObj, bias) {
  2448. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2449. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2450. }
  2451. // Returns a box for a given cursor position, which may have an
  2452. // 'other' property containing the position of the secondary cursor
  2453. // on a bidi boundary.
  2454. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2455. // and after `char - 1` in writing order of `char - 1`
  2456. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2457. // and before `char` in writing order of `char`
  2458. // Examples (upper-case letters are RTL, lower-case are LTR):
  2459. // Pos(0, 1, ...)
  2460. // before after
  2461. // ab a|b a|b
  2462. // aB a|B aB|
  2463. // Ab |Ab A|b
  2464. // AB B|A B|A
  2465. // Every position after the last character on a line is considered to stick
  2466. // to the last character on the line.
  2467. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2468. lineObj = lineObj || getLine(cm.doc, pos.line)
  2469. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2470. function get(ch, right) {
  2471. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2472. if (right) { m.left = m.right; } else { m.right = m.left }
  2473. return intoCoordSystem(cm, lineObj, m, context)
  2474. }
  2475. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
  2476. if (ch >= lineObj.text.length) {
  2477. ch = lineObj.text.length
  2478. sticky = "before"
  2479. } else if (ch <= 0) {
  2480. ch = 0
  2481. sticky = "after"
  2482. }
  2483. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2484. function getBidi(ch, partPos, invert) {
  2485. var part = order[partPos], right = part.level == 1
  2486. return get(invert ? ch - 1 : ch, right != invert)
  2487. }
  2488. var partPos = getBidiPartAt(order, ch, sticky)
  2489. var other = bidiOther
  2490. var val = getBidi(ch, partPos, sticky == "before")
  2491. if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
  2492. return val
  2493. }
  2494. // Used to cheaply estimate the coordinates for a position. Used for
  2495. // intermediate scroll updates.
  2496. function estimateCoords(cm, pos) {
  2497. var left = 0
  2498. pos = clipPos(cm.doc, pos)
  2499. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2500. var lineObj = getLine(cm.doc, pos.line)
  2501. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2502. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2503. }
  2504. // Positions returned by coordsChar contain some extra information.
  2505. // xRel is the relative x position of the input coordinates compared
  2506. // to the found position (so xRel > 0 means the coordinates are to
  2507. // the right of the character position, for example). When outside
  2508. // is true, that means the coordinates lie outside the line's
  2509. // vertical range.
  2510. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2511. var pos = Pos(line, ch, sticky)
  2512. pos.xRel = xRel
  2513. if (outside) { pos.outside = true }
  2514. return pos
  2515. }
  2516. // Compute the character position closest to the given coordinates.
  2517. // Input must be lineSpace-local ("div" coordinate system).
  2518. function coordsChar(cm, x, y) {
  2519. var doc = cm.doc
  2520. y += cm.display.viewOffset
  2521. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2522. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2523. if (lineN > last)
  2524. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2525. if (x < 0) { x = 0 }
  2526. var lineObj = getLine(doc, lineN)
  2527. for (;;) {
  2528. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2529. var merged = collapsedSpanAtEnd(lineObj)
  2530. var mergedPos = merged && merged.find(0, true)
  2531. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2532. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2533. else
  2534. { return found }
  2535. }
  2536. }
  2537. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2538. y -= widgetTopHeight(lineObj)
  2539. var end = lineObj.text.length
  2540. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0)
  2541. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end)
  2542. return {begin: begin, end: end}
  2543. }
  2544. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2545. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2546. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  2547. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2548. }
  2549. // Returns true if the given side of a box is after the given
  2550. // coordinates, in top-to-bottom, left-to-right order.
  2551. function boxIsAfter(box, x, y, left) {
  2552. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2553. }
  2554. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2555. // Move y into line-local coordinate space
  2556. y -= heightAtLine(lineObj)
  2557. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2558. // When directly calling `measureCharPrepared`, we have to adjust
  2559. // for the widgets at this line.
  2560. var widgetHeight = widgetTopHeight(lineObj)
  2561. var begin = 0, end = lineObj.text.length, ltr = true
  2562. var order = getOrder(lineObj, cm.doc.direction)
  2563. // If the line isn't plain left-to-right text, first figure out
  2564. // which bidi section the coordinates fall into.
  2565. if (order) {
  2566. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2567. (cm, lineObj, lineNo, preparedMeasure, order, x, y)
  2568. ltr = part.level != 1
  2569. // The awkward -1 offsets are needed because findFirst (called
  2570. // on these below) will treat its first bound as inclusive,
  2571. // second as exclusive, but we want to actually address the
  2572. // characters in the part's range
  2573. begin = ltr ? part.from : part.to - 1
  2574. end = ltr ? part.to : part.from - 1
  2575. }
  2576. // A binary search to find the first character whose bounding box
  2577. // starts after the coordinates. If we run across any whose box wrap
  2578. // the coordinates, store that.
  2579. var chAround = null, boxAround = null
  2580. var ch = findFirst(function (ch) {
  2581. var box = measureCharPrepared(cm, preparedMeasure, ch)
  2582. box.top += widgetHeight; box.bottom += widgetHeight
  2583. if (!boxIsAfter(box, x, y, false)) { return false }
  2584. if (box.top <= y && box.left <= x) {
  2585. chAround = ch
  2586. boxAround = box
  2587. }
  2588. return true
  2589. }, begin, end)
  2590. var baseX, sticky, outside = false
  2591. // If a box around the coordinates was found, use that
  2592. if (boxAround) {
  2593. // Distinguish coordinates nearer to the left or right side of the box
  2594. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr
  2595. ch = chAround + (atStart ? 0 : 1)
  2596. sticky = atStart ? "after" : "before"
  2597. baseX = atLeft ? boxAround.left : boxAround.right
  2598. } else {
  2599. // (Adjust for extended bound, if necessary.)
  2600. if (!ltr && (ch == end || ch == begin)) { ch++ }
  2601. // To determine which side to associate with, get the box to the
  2602. // left of the character and compare it's vertical position to the
  2603. // coordinates
  2604. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2605. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2606. "after" : "before"
  2607. // Now get accurate coordinates for this place, in order to get a
  2608. // base X position
  2609. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure)
  2610. baseX = coords.left
  2611. outside = y < coords.top || y >= coords.bottom
  2612. }
  2613. ch = skipExtendingChars(lineObj.text, ch, 1)
  2614. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2615. }
  2616. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2617. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2618. // situation, we can take this ordering to correspond to the visual
  2619. // ordering. This finds the first part whose end is after the given
  2620. // coordinates.
  2621. var index = findFirst(function (i) {
  2622. var part = order[i], ltr = part.level != 1
  2623. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2624. "line", lineObj, preparedMeasure), x, y, true)
  2625. }, 0, order.length - 1)
  2626. var part = order[index]
  2627. // If this isn't the first part, the part's start is also after
  2628. // the coordinates, and the coordinates aren't on the same line as
  2629. // that start, move one part back.
  2630. if (index > 0) {
  2631. var ltr = part.level != 1
  2632. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2633. "line", lineObj, preparedMeasure)
  2634. if (boxIsAfter(start, x, y, true) && start.top > y)
  2635. { part = order[index - 1] }
  2636. }
  2637. return part
  2638. }
  2639. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2640. // In a wrapped line, rtl text on wrapping boundaries can do things
  2641. // that don't correspond to the ordering in our `order` array at
  2642. // all, so a binary search doesn't work, and we want to return a
  2643. // part that only spans one line so that the binary search in
  2644. // coordsCharInner is safe. As such, we first find the extent of the
  2645. // wrapped line, and then do a flat search in which we discard any
  2646. // spans that aren't on the line.
  2647. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2648. var begin = ref.begin;
  2649. var end = ref.end;
  2650. if (/\s/.test(lineObj.text.charAt(end - 1))) { end-- }
  2651. var part = null, closestDist = null
  2652. for (var i = 0; i < order.length; i++) {
  2653. var p = order[i]
  2654. if (p.from >= end || p.to <= begin) { continue }
  2655. var ltr = p.level != 1
  2656. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right
  2657. // Weigh against spans ending before this, so that they are only
  2658. // picked if nothing ends after
  2659. var dist = endX < x ? x - endX + 1e9 : endX - x
  2660. if (!part || closestDist > dist) {
  2661. part = p
  2662. closestDist = dist
  2663. }
  2664. }
  2665. if (!part) { part = order[order.length - 1] }
  2666. // Clip the part to the wrapped line.
  2667. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level} }
  2668. if (part.to > end) { part = {from: part.from, to: end, level: part.level} }
  2669. return part
  2670. }
  2671. var measureText
  2672. // Compute the default text height.
  2673. function textHeight(display) {
  2674. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2675. if (measureText == null) {
  2676. measureText = elt("pre")
  2677. // Measure a bunch of lines, for browsers that compute
  2678. // fractional heights.
  2679. for (var i = 0; i < 49; ++i) {
  2680. measureText.appendChild(document.createTextNode("x"))
  2681. measureText.appendChild(elt("br"))
  2682. }
  2683. measureText.appendChild(document.createTextNode("x"))
  2684. }
  2685. removeChildrenAndAdd(display.measure, measureText)
  2686. var height = measureText.offsetHeight / 50
  2687. if (height > 3) { display.cachedTextHeight = height }
  2688. removeChildren(display.measure)
  2689. return height || 1
  2690. }
  2691. // Compute the default character width.
  2692. function charWidth(display) {
  2693. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2694. var anchor = elt("span", "xxxxxxxxxx")
  2695. var pre = elt("pre", [anchor])
  2696. removeChildrenAndAdd(display.measure, pre)
  2697. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2698. if (width > 2) { display.cachedCharWidth = width }
  2699. return width || 10
  2700. }
  2701. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2702. // view, so that we don't interleave reading and writing to the DOM.
  2703. function getDimensions(cm) {
  2704. var d = cm.display, left = {}, width = {}
  2705. var gutterLeft = d.gutters.clientLeft
  2706. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2707. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2708. width[cm.options.gutters[i]] = n.clientWidth
  2709. }
  2710. return {fixedPos: compensateForHScroll(d),
  2711. gutterTotalWidth: d.gutters.offsetWidth,
  2712. gutterLeft: left,
  2713. gutterWidth: width,
  2714. wrapperWidth: d.wrapper.clientWidth}
  2715. }
  2716. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2717. // but using getBoundingClientRect to get a sub-pixel-accurate
  2718. // result.
  2719. function compensateForHScroll(display) {
  2720. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2721. }
  2722. // Returns a function that estimates the height of a line, to use as
  2723. // first approximation until the line becomes visible (and is thus
  2724. // properly measurable).
  2725. function estimateHeight(cm) {
  2726. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2727. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2728. return function (line) {
  2729. if (lineIsHidden(cm.doc, line)) { return 0 }
  2730. var widgetsHeight = 0
  2731. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2732. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2733. } }
  2734. if (wrapping)
  2735. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2736. else
  2737. { return widgetsHeight + th }
  2738. }
  2739. }
  2740. function estimateLineHeights(cm) {
  2741. var doc = cm.doc, est = estimateHeight(cm)
  2742. doc.iter(function (line) {
  2743. var estHeight = est(line)
  2744. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2745. })
  2746. }
  2747. // Given a mouse event, find the corresponding position. If liberal
  2748. // is false, it checks whether a gutter or scrollbar was clicked,
  2749. // and returns null if it was. forRect is used by rectangular
  2750. // selections, and tries to estimate a character position even for
  2751. // coordinates beyond the right of the text.
  2752. function posFromMouse(cm, e, liberal, forRect) {
  2753. var display = cm.display
  2754. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2755. var x, y, space = display.lineSpace.getBoundingClientRect()
  2756. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2757. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2758. catch (e) { return null }
  2759. var coords = coordsChar(cm, x, y), line
  2760. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2761. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2762. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2763. }
  2764. return coords
  2765. }
  2766. // Find the view element corresponding to a given line. Return null
  2767. // when the line isn't visible.
  2768. function findViewIndex(cm, n) {
  2769. if (n >= cm.display.viewTo) { return null }
  2770. n -= cm.display.viewFrom
  2771. if (n < 0) { return null }
  2772. var view = cm.display.view
  2773. for (var i = 0; i < view.length; i++) {
  2774. n -= view[i].size
  2775. if (n < 0) { return i }
  2776. }
  2777. }
  2778. function updateSelection(cm) {
  2779. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2780. }
  2781. function prepareSelection(cm, primary) {
  2782. if ( primary === void 0 ) primary = true;
  2783. var doc = cm.doc, result = {}
  2784. var curFragment = result.cursors = document.createDocumentFragment()
  2785. var selFragment = result.selection = document.createDocumentFragment()
  2786. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2787. if (!primary && i == doc.sel.primIndex) { continue }
  2788. var range = doc.sel.ranges[i]
  2789. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2790. var collapsed = range.empty()
  2791. if (collapsed || cm.options.showCursorWhenSelecting)
  2792. { drawSelectionCursor(cm, range.head, curFragment) }
  2793. if (!collapsed)
  2794. { drawSelectionRange(cm, range, selFragment) }
  2795. }
  2796. return result
  2797. }
  2798. // Draws a cursor for the given range
  2799. function drawSelectionCursor(cm, head, output) {
  2800. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2801. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2802. cursor.style.left = pos.left + "px"
  2803. cursor.style.top = pos.top + "px"
  2804. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2805. if (pos.other) {
  2806. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2807. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2808. otherCursor.style.display = ""
  2809. otherCursor.style.left = pos.other.left + "px"
  2810. otherCursor.style.top = pos.other.top + "px"
  2811. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2812. }
  2813. }
  2814. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2815. // Draws the given range as a highlighted selection
  2816. function drawSelectionRange(cm, range, output) {
  2817. var display = cm.display, doc = cm.doc
  2818. var fragment = document.createDocumentFragment()
  2819. var padding = paddingH(cm.display), leftSide = padding.left
  2820. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2821. var docLTR = doc.direction == "ltr"
  2822. function add(left, top, width, bottom) {
  2823. if (top < 0) { top = 0 }
  2824. top = Math.round(top)
  2825. bottom = Math.round(bottom)
  2826. 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")))
  2827. }
  2828. function drawForLine(line, fromArg, toArg) {
  2829. var lineObj = getLine(doc, line)
  2830. var lineLen = lineObj.text.length
  2831. var start, end
  2832. function coords(ch, bias) {
  2833. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2834. }
  2835. function wrapX(pos, dir, side) {
  2836. var extent = wrappedLineExtentChar(cm, lineObj, null, pos)
  2837. var prop = (dir == "ltr") == (side == "after") ? "left" : "right"
  2838. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1)
  2839. return coords(ch, prop)[prop]
  2840. }
  2841. var order = getOrder(lineObj, doc.direction)
  2842. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2843. var ltr = dir == "ltr"
  2844. var fromPos = coords(from, ltr ? "left" : "right")
  2845. var toPos = coords(to - 1, ltr ? "right" : "left")
  2846. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen
  2847. var first = i == 0, last = !order || i == order.length - 1
  2848. if (toPos.top - fromPos.top <= 3) { // Single line
  2849. var openLeft = (docLTR ? openStart : openEnd) && first
  2850. var openRight = (docLTR ? openEnd : openStart) && last
  2851. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left
  2852. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right
  2853. add(left, fromPos.top, right - left, fromPos.bottom)
  2854. } else { // Multiple lines
  2855. var topLeft, topRight, botLeft, botRight
  2856. if (ltr) {
  2857. topLeft = docLTR && openStart && first ? leftSide : fromPos.left
  2858. topRight = docLTR ? rightSide : wrapX(from, dir, "before")
  2859. botLeft = docLTR ? leftSide : wrapX(to, dir, "after")
  2860. botRight = docLTR && openEnd && last ? rightSide : toPos.right
  2861. } else {
  2862. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before")
  2863. topRight = !docLTR && openStart && first ? rightSide : fromPos.right
  2864. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left
  2865. botRight = !docLTR ? rightSide : wrapX(to, dir, "after")
  2866. }
  2867. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom)
  2868. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top) }
  2869. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom)
  2870. }
  2871. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos }
  2872. if (cmpCoords(toPos, start) < 0) { start = toPos }
  2873. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos }
  2874. if (cmpCoords(toPos, end) < 0) { end = toPos }
  2875. })
  2876. return {start: start, end: end}
  2877. }
  2878. var sFrom = range.from(), sTo = range.to()
  2879. if (sFrom.line == sTo.line) {
  2880. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2881. } else {
  2882. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2883. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2884. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2885. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2886. if (singleVLine) {
  2887. if (leftEnd.top < rightStart.top - 2) {
  2888. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2889. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2890. } else {
  2891. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2892. }
  2893. }
  2894. if (leftEnd.bottom < rightStart.top)
  2895. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2896. }
  2897. output.appendChild(fragment)
  2898. }
  2899. // Cursor-blinking
  2900. function restartBlink(cm) {
  2901. if (!cm.state.focused) { return }
  2902. var display = cm.display
  2903. clearInterval(display.blinker)
  2904. var on = true
  2905. display.cursorDiv.style.visibility = ""
  2906. if (cm.options.cursorBlinkRate > 0)
  2907. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2908. cm.options.cursorBlinkRate) }
  2909. else if (cm.options.cursorBlinkRate < 0)
  2910. { display.cursorDiv.style.visibility = "hidden" }
  2911. }
  2912. function ensureFocus(cm) {
  2913. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2914. }
  2915. function delayBlurEvent(cm) {
  2916. cm.state.delayingBlurEvent = true
  2917. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2918. cm.state.delayingBlurEvent = false
  2919. onBlur(cm)
  2920. } }, 100)
  2921. }
  2922. function onFocus(cm, e) {
  2923. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2924. if (cm.options.readOnly == "nocursor") { return }
  2925. if (!cm.state.focused) {
  2926. signal(cm, "focus", cm, e)
  2927. cm.state.focused = true
  2928. addClass(cm.display.wrapper, "CodeMirror-focused")
  2929. // This test prevents this from firing when a context
  2930. // menu is closed (since the input reset would kill the
  2931. // select-all detection hack)
  2932. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2933. cm.display.input.reset()
  2934. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2935. }
  2936. cm.display.input.receivedFocus()
  2937. }
  2938. restartBlink(cm)
  2939. }
  2940. function onBlur(cm, e) {
  2941. if (cm.state.delayingBlurEvent) { return }
  2942. if (cm.state.focused) {
  2943. signal(cm, "blur", cm, e)
  2944. cm.state.focused = false
  2945. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2946. }
  2947. clearInterval(cm.display.blinker)
  2948. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2949. }
  2950. // Read the actual heights of the rendered lines, and update their
  2951. // stored heights to match.
  2952. function updateHeightsInViewport(cm) {
  2953. var display = cm.display
  2954. var prevBottom = display.lineDiv.offsetTop
  2955. for (var i = 0; i < display.view.length; i++) {
  2956. var cur = display.view[i], height = (void 0)
  2957. if (cur.hidden) { continue }
  2958. if (ie && ie_version < 8) {
  2959. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2960. height = bot - prevBottom
  2961. prevBottom = bot
  2962. } else {
  2963. var box = cur.node.getBoundingClientRect()
  2964. height = box.bottom - box.top
  2965. }
  2966. var diff = cur.line.height - height
  2967. if (height < 2) { height = textHeight(display) }
  2968. if (diff > .005 || diff < -.005) {
  2969. updateLineHeight(cur.line, height)
  2970. updateWidgetHeight(cur.line)
  2971. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2972. { updateWidgetHeight(cur.rest[j]) } }
  2973. }
  2974. }
  2975. }
  2976. // Read and store the height of line widgets associated with the
  2977. // given line.
  2978. function updateWidgetHeight(line) {
  2979. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  2980. var w = line.widgets[i], parent = w.node.parentNode
  2981. if (parent) { w.height = parent.offsetHeight }
  2982. } }
  2983. }
  2984. // Compute the lines that are visible in a given viewport (defaults
  2985. // the the current scroll position). viewport may contain top,
  2986. // height, and ensure (see op.scrollToPos) properties.
  2987. function visibleLines(display, doc, viewport) {
  2988. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2989. top = Math.floor(top - paddingTop(display))
  2990. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2991. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2992. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2993. // forces those lines into the viewport (if possible).
  2994. if (viewport && viewport.ensure) {
  2995. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2996. if (ensureFrom < from) {
  2997. from = ensureFrom
  2998. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2999. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3000. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  3001. to = ensureTo
  3002. }
  3003. }
  3004. return {from: from, to: Math.max(to, from + 1)}
  3005. }
  3006. // Re-align line numbers and gutter marks to compensate for
  3007. // horizontal scrolling.
  3008. function alignHorizontally(cm) {
  3009. var display = cm.display, view = display.view
  3010. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3011. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  3012. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  3013. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3014. if (cm.options.fixedGutter) {
  3015. if (view[i].gutter)
  3016. { view[i].gutter.style.left = left }
  3017. if (view[i].gutterBackground)
  3018. { view[i].gutterBackground.style.left = left }
  3019. }
  3020. var align = view[i].alignable
  3021. if (align) { for (var j = 0; j < align.length; j++)
  3022. { align[j].style.left = left } }
  3023. } }
  3024. if (cm.options.fixedGutter)
  3025. { display.gutters.style.left = (comp + gutterW) + "px" }
  3026. }
  3027. // Used to ensure that the line number gutter is still the right
  3028. // size for the current document size. Returns true when an update
  3029. // is needed.
  3030. function maybeUpdateLineNumberWidth(cm) {
  3031. if (!cm.options.lineNumbers) { return false }
  3032. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  3033. if (last.length != display.lineNumChars) {
  3034. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3035. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  3036. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  3037. display.lineGutter.style.width = ""
  3038. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  3039. display.lineNumWidth = display.lineNumInnerWidth + padding
  3040. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  3041. display.lineGutter.style.width = display.lineNumWidth + "px"
  3042. updateGutterSpace(cm)
  3043. return true
  3044. }
  3045. return false
  3046. }
  3047. // SCROLLING THINGS INTO VIEW
  3048. // If an editor sits on the top or bottom of the window, partially
  3049. // scrolled out of view, this ensures that the cursor is visible.
  3050. function maybeScrollWindow(cm, rect) {
  3051. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3052. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3053. if (rect.top + box.top < 0) { doScroll = true }
  3054. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3055. if (doScroll != null && !phantom) {
  3056. 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;"))
  3057. cm.display.lineSpace.appendChild(scrollNode)
  3058. scrollNode.scrollIntoView(doScroll)
  3059. cm.display.lineSpace.removeChild(scrollNode)
  3060. }
  3061. }
  3062. // Scroll a given position into view (immediately), verifying that
  3063. // it actually became visible (as line heights are accurately
  3064. // measured, the position of something may 'drift' during drawing).
  3065. function scrollPosIntoView(cm, pos, end, margin) {
  3066. if (margin == null) { margin = 0 }
  3067. var rect
  3068. if (!cm.options.lineWrapping && pos == end) {
  3069. // Set pos and end to the cursor positions around the character pos sticks to
  3070. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3071. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3072. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos
  3073. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos
  3074. }
  3075. for (var limit = 0; limit < 5; limit++) {
  3076. var changed = false
  3077. var coords = cursorCoords(cm, pos)
  3078. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3079. rect = {left: Math.min(coords.left, endCoords.left),
  3080. top: Math.min(coords.top, endCoords.top) - margin,
  3081. right: Math.max(coords.left, endCoords.left),
  3082. bottom: Math.max(coords.bottom, endCoords.bottom) + margin}
  3083. var scrollPos = calculateScrollPos(cm, rect)
  3084. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3085. if (scrollPos.scrollTop != null) {
  3086. updateScrollTop(cm, scrollPos.scrollTop)
  3087. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3088. }
  3089. if (scrollPos.scrollLeft != null) {
  3090. setScrollLeft(cm, scrollPos.scrollLeft)
  3091. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3092. }
  3093. if (!changed) { break }
  3094. }
  3095. return rect
  3096. }
  3097. // Scroll a given set of coordinates into view (immediately).
  3098. function scrollIntoView(cm, rect) {
  3099. var scrollPos = calculateScrollPos(cm, rect)
  3100. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) }
  3101. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3102. }
  3103. // Calculate a new scroll position needed to scroll the given
  3104. // rectangle into view. Returns an object with scrollTop and
  3105. // scrollLeft properties. When these are undefined, the
  3106. // vertical/horizontal position does not need to be adjusted.
  3107. function calculateScrollPos(cm, rect) {
  3108. var display = cm.display, snapMargin = textHeight(cm.display)
  3109. if (rect.top < 0) { rect.top = 0 }
  3110. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3111. var screen = displayHeight(cm), result = {}
  3112. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen }
  3113. var docBottom = cm.doc.height + paddingVert(display)
  3114. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin
  3115. if (rect.top < screentop) {
  3116. result.scrollTop = atTop ? 0 : rect.top
  3117. } else if (rect.bottom > screentop + screen) {
  3118. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
  3119. if (newTop != screentop) { result.scrollTop = newTop }
  3120. }
  3121. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3122. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3123. var tooWide = rect.right - rect.left > screenw
  3124. if (tooWide) { rect.right = rect.left + screenw }
  3125. if (rect.left < 10)
  3126. { result.scrollLeft = 0 }
  3127. else if (rect.left < screenleft)
  3128. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) }
  3129. else if (rect.right > screenw + screenleft - 3)
  3130. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw }
  3131. return result
  3132. }
  3133. // Store a relative adjustment to the scroll position in the current
  3134. // operation (to be applied when the operation finishes).
  3135. function addToScrollTop(cm, top) {
  3136. if (top == null) { return }
  3137. resolveScrollToPos(cm)
  3138. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
  3139. }
  3140. // Make sure that at the end of the operation the current cursor is
  3141. // shown.
  3142. function ensureCursorVisible(cm) {
  3143. resolveScrollToPos(cm)
  3144. var cur = cm.getCursor()
  3145. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}
  3146. }
  3147. function scrollToCoords(cm, x, y) {
  3148. if (x != null || y != null) { resolveScrollToPos(cm) }
  3149. if (x != null) { cm.curOp.scrollLeft = x }
  3150. if (y != null) { cm.curOp.scrollTop = y }
  3151. }
  3152. function scrollToRange(cm, range) {
  3153. resolveScrollToPos(cm)
  3154. cm.curOp.scrollToPos = range
  3155. }
  3156. // When an operation has its scrollToPos property set, and another
  3157. // scroll action is applied before the end of the operation, this
  3158. // 'simulates' scrolling that position into view in a cheap way, so
  3159. // that the effect of intermediate scroll commands is not ignored.
  3160. function resolveScrollToPos(cm) {
  3161. var range = cm.curOp.scrollToPos
  3162. if (range) {
  3163. cm.curOp.scrollToPos = null
  3164. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3165. scrollToCoordsRange(cm, from, to, range.margin)
  3166. }
  3167. }
  3168. function scrollToCoordsRange(cm, from, to, margin) {
  3169. var sPos = calculateScrollPos(cm, {
  3170. left: Math.min(from.left, to.left),
  3171. top: Math.min(from.top, to.top) - margin,
  3172. right: Math.max(from.right, to.right),
  3173. bottom: Math.max(from.bottom, to.bottom) + margin
  3174. })
  3175. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
  3176. }
  3177. // Sync the scrollable area and scrollbars, ensure the viewport
  3178. // covers the visible area.
  3179. function updateScrollTop(cm, val) {
  3180. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3181. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  3182. setScrollTop(cm, val, true)
  3183. if (gecko) { updateDisplaySimple(cm) }
  3184. startWorker(cm, 100)
  3185. }
  3186. function setScrollTop(cm, val, forceScroll) {
  3187. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)
  3188. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3189. cm.doc.scrollTop = val
  3190. cm.display.scrollbars.setScrollTop(val)
  3191. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  3192. }
  3193. // Sync scroller and scrollbar, ensure the gutter elements are
  3194. // aligned.
  3195. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3196. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  3197. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3198. cm.doc.scrollLeft = val
  3199. alignHorizontally(cm)
  3200. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  3201. cm.display.scrollbars.setScrollLeft(val)
  3202. }
  3203. // SCROLLBARS
  3204. // Prepare DOM reads needed to update the scrollbars. Done in one
  3205. // shot to minimize update/measure roundtrips.
  3206. function measureForScrollbars(cm) {
  3207. var d = cm.display, gutterW = d.gutters.offsetWidth
  3208. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  3209. return {
  3210. clientHeight: d.scroller.clientHeight,
  3211. viewHeight: d.wrapper.clientHeight,
  3212. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3213. viewWidth: d.wrapper.clientWidth,
  3214. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3215. docHeight: docH,
  3216. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3217. nativeBarWidth: d.nativeBarWidth,
  3218. gutterWidth: gutterW
  3219. }
  3220. }
  3221. var NativeScrollbars = function(place, scroll, cm) {
  3222. this.cm = cm
  3223. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3224. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3225. place(vert); place(horiz)
  3226. on(vert, "scroll", function () {
  3227. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3228. })
  3229. on(horiz, "scroll", function () {
  3230. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3231. })
  3232. this.checkedZeroWidth = false
  3233. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3234. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3235. };
  3236. NativeScrollbars.prototype.update = function (measure) {
  3237. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3238. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3239. var sWidth = measure.nativeBarWidth
  3240. if (needsV) {
  3241. this.vert.style.display = "block"
  3242. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3243. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3244. // A bug in IE8 can cause this value to be negative, so guard it.
  3245. this.vert.firstChild.style.height =
  3246. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3247. } else {
  3248. this.vert.style.display = ""
  3249. this.vert.firstChild.style.height = "0"
  3250. }
  3251. if (needsH) {
  3252. this.horiz.style.display = "block"
  3253. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3254. this.horiz.style.left = measure.barLeft + "px"
  3255. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3256. this.horiz.firstChild.style.width =
  3257. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3258. } else {
  3259. this.horiz.style.display = ""
  3260. this.horiz.firstChild.style.width = "0"
  3261. }
  3262. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3263. if (sWidth == 0) { this.zeroWidthHack() }
  3264. this.checkedZeroWidth = true
  3265. }
  3266. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3267. };
  3268. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3269. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3270. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") }
  3271. };
  3272. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3273. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3274. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") }
  3275. };
  3276. NativeScrollbars.prototype.zeroWidthHack = function () {
  3277. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3278. this.horiz.style.height = this.vert.style.width = w
  3279. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3280. this.disableHoriz = new Delayed
  3281. this.disableVert = new Delayed
  3282. };
  3283. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3284. bar.style.pointerEvents = "auto"
  3285. function maybeDisable() {
  3286. // To find out whether the scrollbar is still visible, we
  3287. // check whether the element under the pixel in the bottom
  3288. // right corner of the scrollbar box is the scrollbar box
  3289. // itself (when the bar is still visible) or its filler child
  3290. // (when the bar is hidden). If it is still visible, we keep
  3291. // it enabled, if it's hidden, we disable pointer events.
  3292. var box = bar.getBoundingClientRect()
  3293. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3294. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
  3295. if (elt != bar) { bar.style.pointerEvents = "none" }
  3296. else { delay.set(1000, maybeDisable) }
  3297. }
  3298. delay.set(1000, maybeDisable)
  3299. };
  3300. NativeScrollbars.prototype.clear = function () {
  3301. var parent = this.horiz.parentNode
  3302. parent.removeChild(this.horiz)
  3303. parent.removeChild(this.vert)
  3304. };
  3305. var NullScrollbars = function () {};
  3306. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3307. NullScrollbars.prototype.setScrollLeft = function () {};
  3308. NullScrollbars.prototype.setScrollTop = function () {};
  3309. NullScrollbars.prototype.clear = function () {};
  3310. function updateScrollbars(cm, measure) {
  3311. if (!measure) { measure = measureForScrollbars(cm) }
  3312. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3313. updateScrollbarsInner(cm, measure)
  3314. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3315. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3316. { updateHeightsInViewport(cm) }
  3317. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3318. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3319. }
  3320. }
  3321. // Re-synchronize the fake scrollbars with the actual size of the
  3322. // content.
  3323. function updateScrollbarsInner(cm, measure) {
  3324. var d = cm.display
  3325. var sizes = d.scrollbars.update(measure)
  3326. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3327. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3328. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3329. if (sizes.right && sizes.bottom) {
  3330. d.scrollbarFiller.style.display = "block"
  3331. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3332. d.scrollbarFiller.style.width = sizes.right + "px"
  3333. } else { d.scrollbarFiller.style.display = "" }
  3334. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3335. d.gutterFiller.style.display = "block"
  3336. d.gutterFiller.style.height = sizes.bottom + "px"
  3337. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3338. } else { d.gutterFiller.style.display = "" }
  3339. }
  3340. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3341. function initScrollbars(cm) {
  3342. if (cm.display.scrollbars) {
  3343. cm.display.scrollbars.clear()
  3344. if (cm.display.scrollbars.addClass)
  3345. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3346. }
  3347. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3348. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3349. // Prevent clicks in the scrollbars from killing focus
  3350. on(node, "mousedown", function () {
  3351. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3352. })
  3353. node.setAttribute("cm-not-content", "true")
  3354. }, function (pos, axis) {
  3355. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3356. else { updateScrollTop(cm, pos) }
  3357. }, cm)
  3358. if (cm.display.scrollbars.addClass)
  3359. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3360. }
  3361. // Operations are used to wrap a series of changes to the editor
  3362. // state in such a way that each change won't have to update the
  3363. // cursor and display (which would be awkward, slow, and
  3364. // error-prone). Instead, display updates are batched and then all
  3365. // combined and executed at once.
  3366. var nextOpId = 0
  3367. // Start a new operation.
  3368. function startOperation(cm) {
  3369. cm.curOp = {
  3370. cm: cm,
  3371. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3372. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3373. forceUpdate: false, // Used to force a redraw
  3374. updateInput: null, // Whether to reset the input textarea
  3375. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3376. changeObjs: null, // Accumulated changes, for firing change events
  3377. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3378. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3379. selectionChanged: false, // Whether the selection needs to be redrawn
  3380. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3381. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3382. scrollToPos: null, // Used to scroll to a specific position
  3383. focus: false,
  3384. id: ++nextOpId // Unique ID
  3385. }
  3386. pushOperation(cm.curOp)
  3387. }
  3388. // Finish an operation, updating the display and signalling delayed events
  3389. function endOperation(cm) {
  3390. var op = cm.curOp
  3391. finishOperation(op, function (group) {
  3392. for (var i = 0; i < group.ops.length; i++)
  3393. { group.ops[i].cm.curOp = null }
  3394. endOperations(group)
  3395. })
  3396. }
  3397. // The DOM updates done when an operation finishes are batched so
  3398. // that the minimum number of relayouts are required.
  3399. function endOperations(group) {
  3400. var ops = group.ops
  3401. for (var i = 0; i < ops.length; i++) // Read DOM
  3402. { endOperation_R1(ops[i]) }
  3403. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3404. { endOperation_W1(ops[i$1]) }
  3405. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3406. { endOperation_R2(ops[i$2]) }
  3407. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3408. { endOperation_W2(ops[i$3]) }
  3409. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3410. { endOperation_finish(ops[i$4]) }
  3411. }
  3412. function endOperation_R1(op) {
  3413. var cm = op.cm, display = cm.display
  3414. maybeClipScrollbars(cm)
  3415. if (op.updateMaxLine) { findMaxLine(cm) }
  3416. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3417. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3418. op.scrollToPos.to.line >= display.viewTo) ||
  3419. display.maxLineChanged && cm.options.lineWrapping
  3420. op.update = op.mustUpdate &&
  3421. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3422. }
  3423. function endOperation_W1(op) {
  3424. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3425. }
  3426. function endOperation_R2(op) {
  3427. var cm = op.cm, display = cm.display
  3428. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3429. op.barMeasure = measureForScrollbars(cm)
  3430. // If the max line changed since it was last measured, measure it,
  3431. // and ensure the document's width matches it.
  3432. // updateDisplay_W2 will use these properties to do the actual resizing
  3433. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3434. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3435. cm.display.sizerWidth = op.adjustWidthTo
  3436. op.barMeasure.scrollWidth =
  3437. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3438. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3439. }
  3440. if (op.updatedDisplay || op.selectionChanged)
  3441. { op.preparedSelection = display.input.prepareSelection() }
  3442. }
  3443. function endOperation_W2(op) {
  3444. var cm = op.cm
  3445. if (op.adjustWidthTo != null) {
  3446. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3447. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3448. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3449. cm.display.maxLineChanged = false
  3450. }
  3451. var takeFocus = op.focus && op.focus == activeElt()
  3452. if (op.preparedSelection)
  3453. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3454. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3455. { updateScrollbars(cm, op.barMeasure) }
  3456. if (op.updatedDisplay)
  3457. { setDocumentHeight(cm, op.barMeasure) }
  3458. if (op.selectionChanged) { restartBlink(cm) }
  3459. if (cm.state.focused && op.updateInput)
  3460. { cm.display.input.reset(op.typing) }
  3461. if (takeFocus) { ensureFocus(op.cm) }
  3462. }
  3463. function endOperation_finish(op) {
  3464. var cm = op.cm, display = cm.display, doc = cm.doc
  3465. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3466. // Abort mouse wheel delta measurement, when scrolling explicitly
  3467. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3468. { display.wheelStartX = display.wheelStartY = null }
  3469. // Propagate the scroll position to the actual DOM scroller
  3470. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) }
  3471. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) }
  3472. // If we need to scroll a specific position into view, do so.
  3473. if (op.scrollToPos) {
  3474. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3475. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3476. maybeScrollWindow(cm, rect)
  3477. }
  3478. // Fire events for markers that are hidden/unidden by editing or
  3479. // undoing
  3480. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3481. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3482. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3483. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3484. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3485. if (display.wrapper.offsetHeight)
  3486. { doc.scrollTop = cm.display.scroller.scrollTop }
  3487. // Fire change events, and delayed event handlers
  3488. if (op.changeObjs)
  3489. { signal(cm, "changes", cm, op.changeObjs) }
  3490. if (op.update)
  3491. { op.update.finish() }
  3492. }
  3493. // Run the given function in an operation
  3494. function runInOp(cm, f) {
  3495. if (cm.curOp) { return f() }
  3496. startOperation(cm)
  3497. try { return f() }
  3498. finally { endOperation(cm) }
  3499. }
  3500. // Wraps a function in an operation. Returns the wrapped function.
  3501. function operation(cm, f) {
  3502. return function() {
  3503. if (cm.curOp) { return f.apply(cm, arguments) }
  3504. startOperation(cm)
  3505. try { return f.apply(cm, arguments) }
  3506. finally { endOperation(cm) }
  3507. }
  3508. }
  3509. // Used to add methods to editor and doc instances, wrapping them in
  3510. // operations.
  3511. function methodOp(f) {
  3512. return function() {
  3513. if (this.curOp) { return f.apply(this, arguments) }
  3514. startOperation(this)
  3515. try { return f.apply(this, arguments) }
  3516. finally { endOperation(this) }
  3517. }
  3518. }
  3519. function docMethodOp(f) {
  3520. return function() {
  3521. var cm = this.cm
  3522. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3523. startOperation(cm)
  3524. try { return f.apply(this, arguments) }
  3525. finally { endOperation(cm) }
  3526. }
  3527. }
  3528. // Updates the display.view data structure for a given change to the
  3529. // document. From and to are in pre-change coordinates. Lendiff is
  3530. // the amount of lines added or subtracted by the change. This is
  3531. // used for changes that span multiple lines, or change the way
  3532. // lines are divided into visual lines. regLineChange (below)
  3533. // registers single-line changes.
  3534. function regChange(cm, from, to, lendiff) {
  3535. if (from == null) { from = cm.doc.first }
  3536. if (to == null) { to = cm.doc.first + cm.doc.size }
  3537. if (!lendiff) { lendiff = 0 }
  3538. var display = cm.display
  3539. if (lendiff && to < display.viewTo &&
  3540. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3541. { display.updateLineNumbers = from }
  3542. cm.curOp.viewChanged = true
  3543. if (from >= display.viewTo) { // Change after
  3544. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3545. { resetView(cm) }
  3546. } else if (to <= display.viewFrom) { // Change before
  3547. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3548. resetView(cm)
  3549. } else {
  3550. display.viewFrom += lendiff
  3551. display.viewTo += lendiff
  3552. }
  3553. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3554. resetView(cm)
  3555. } else if (from <= display.viewFrom) { // Top overlap
  3556. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3557. if (cut) {
  3558. display.view = display.view.slice(cut.index)
  3559. display.viewFrom = cut.lineN
  3560. display.viewTo += lendiff
  3561. } else {
  3562. resetView(cm)
  3563. }
  3564. } else if (to >= display.viewTo) { // Bottom overlap
  3565. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3566. if (cut$1) {
  3567. display.view = display.view.slice(0, cut$1.index)
  3568. display.viewTo = cut$1.lineN
  3569. } else {
  3570. resetView(cm)
  3571. }
  3572. } else { // Gap in the middle
  3573. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3574. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3575. if (cutTop && cutBot) {
  3576. display.view = display.view.slice(0, cutTop.index)
  3577. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3578. .concat(display.view.slice(cutBot.index))
  3579. display.viewTo += lendiff
  3580. } else {
  3581. resetView(cm)
  3582. }
  3583. }
  3584. var ext = display.externalMeasured
  3585. if (ext) {
  3586. if (to < ext.lineN)
  3587. { ext.lineN += lendiff }
  3588. else if (from < ext.lineN + ext.size)
  3589. { display.externalMeasured = null }
  3590. }
  3591. }
  3592. // Register a change to a single line. Type must be one of "text",
  3593. // "gutter", "class", "widget"
  3594. function regLineChange(cm, line, type) {
  3595. cm.curOp.viewChanged = true
  3596. var display = cm.display, ext = cm.display.externalMeasured
  3597. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3598. { display.externalMeasured = null }
  3599. if (line < display.viewFrom || line >= display.viewTo) { return }
  3600. var lineView = display.view[findViewIndex(cm, line)]
  3601. if (lineView.node == null) { return }
  3602. var arr = lineView.changes || (lineView.changes = [])
  3603. if (indexOf(arr, type) == -1) { arr.push(type) }
  3604. }
  3605. // Clear the view.
  3606. function resetView(cm) {
  3607. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3608. cm.display.view = []
  3609. cm.display.viewOffset = 0
  3610. }
  3611. function viewCuttingPoint(cm, oldN, newN, dir) {
  3612. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3613. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3614. { return {index: index, lineN: newN} }
  3615. var n = cm.display.viewFrom
  3616. for (var i = 0; i < index; i++)
  3617. { n += view[i].size }
  3618. if (n != oldN) {
  3619. if (dir > 0) {
  3620. if (index == view.length - 1) { return null }
  3621. diff = (n + view[index].size) - oldN
  3622. index++
  3623. } else {
  3624. diff = n - oldN
  3625. }
  3626. oldN += diff; newN += diff
  3627. }
  3628. while (visualLineNo(cm.doc, newN) != newN) {
  3629. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3630. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3631. index += dir
  3632. }
  3633. return {index: index, lineN: newN}
  3634. }
  3635. // Force the view to cover a given range, adding empty view element
  3636. // or clipping off existing ones as needed.
  3637. function adjustView(cm, from, to) {
  3638. var display = cm.display, view = display.view
  3639. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3640. display.view = buildViewArray(cm, from, to)
  3641. display.viewFrom = from
  3642. } else {
  3643. if (display.viewFrom > from)
  3644. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3645. else if (display.viewFrom < from)
  3646. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3647. display.viewFrom = from
  3648. if (display.viewTo < to)
  3649. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3650. else if (display.viewTo > to)
  3651. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3652. }
  3653. display.viewTo = to
  3654. }
  3655. // Count the number of lines in the view whose DOM representation is
  3656. // out of date (or nonexistent).
  3657. function countDirtyView(cm) {
  3658. var view = cm.display.view, dirty = 0
  3659. for (var i = 0; i < view.length; i++) {
  3660. var lineView = view[i]
  3661. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3662. }
  3663. return dirty
  3664. }
  3665. // HIGHLIGHT WORKER
  3666. function startWorker(cm, time) {
  3667. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3668. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3669. }
  3670. function highlightWorker(cm) {
  3671. var doc = cm.doc
  3672. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3673. var end = +new Date + cm.options.workTime
  3674. var context = getContextBefore(cm, doc.highlightFrontier)
  3675. var changedLines = []
  3676. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3677. if (context.line >= cm.display.viewFrom) { // Visible
  3678. var oldStyles = line.styles
  3679. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
  3680. var highlighted = highlightLine(cm, line, context, true)
  3681. if (resetState) { context.state = resetState }
  3682. line.styles = highlighted.styles
  3683. var oldCls = line.styleClasses, newCls = highlighted.classes
  3684. if (newCls) { line.styleClasses = newCls }
  3685. else if (oldCls) { line.styleClasses = null }
  3686. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3687. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3688. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3689. if (ischange) { changedLines.push(context.line) }
  3690. line.stateAfter = context.save()
  3691. context.nextLine()
  3692. } else {
  3693. if (line.text.length <= cm.options.maxHighlightLength)
  3694. { processLine(cm, line.text, context) }
  3695. line.stateAfter = context.line % 5 == 0 ? context.save() : null
  3696. context.nextLine()
  3697. }
  3698. if (+new Date > end) {
  3699. startWorker(cm, cm.options.workDelay)
  3700. return true
  3701. }
  3702. })
  3703. doc.highlightFrontier = context.line
  3704. doc.modeFrontier = Math.max(doc.modeFrontier, context.line)
  3705. if (changedLines.length) { runInOp(cm, function () {
  3706. for (var i = 0; i < changedLines.length; i++)
  3707. { regLineChange(cm, changedLines[i], "text") }
  3708. }) }
  3709. }
  3710. // DISPLAY DRAWING
  3711. var DisplayUpdate = function(cm, viewport, force) {
  3712. var display = cm.display
  3713. this.viewport = viewport
  3714. // Store some values that we'll need later (but don't want to force a relayout for)
  3715. this.visible = visibleLines(display, cm.doc, viewport)
  3716. this.editorIsHidden = !display.wrapper.offsetWidth
  3717. this.wrapperHeight = display.wrapper.clientHeight
  3718. this.wrapperWidth = display.wrapper.clientWidth
  3719. this.oldDisplayWidth = displayWidth(cm)
  3720. this.force = force
  3721. this.dims = getDimensions(cm)
  3722. this.events = []
  3723. };
  3724. DisplayUpdate.prototype.signal = function (emitter, type) {
  3725. if (hasHandler(emitter, type))
  3726. { this.events.push(arguments) }
  3727. };
  3728. DisplayUpdate.prototype.finish = function () {
  3729. var this$1 = this;
  3730. for (var i = 0; i < this.events.length; i++)
  3731. { signal.apply(null, this$1.events[i]) }
  3732. };
  3733. function maybeClipScrollbars(cm) {
  3734. var display = cm.display
  3735. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3736. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3737. display.heightForcer.style.height = scrollGap(cm) + "px"
  3738. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3739. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3740. display.scrollbarsClipped = true
  3741. }
  3742. }
  3743. function selectionSnapshot(cm) {
  3744. if (cm.hasFocus()) { return null }
  3745. var active = activeElt()
  3746. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3747. var result = {activeElt: active}
  3748. if (window.getSelection) {
  3749. var sel = window.getSelection()
  3750. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3751. result.anchorNode = sel.anchorNode
  3752. result.anchorOffset = sel.anchorOffset
  3753. result.focusNode = sel.focusNode
  3754. result.focusOffset = sel.focusOffset
  3755. }
  3756. }
  3757. return result
  3758. }
  3759. function restoreSelection(snapshot) {
  3760. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3761. snapshot.activeElt.focus()
  3762. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3763. var sel = window.getSelection(), range = document.createRange()
  3764. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)
  3765. range.collapse(false)
  3766. sel.removeAllRanges()
  3767. sel.addRange(range)
  3768. sel.extend(snapshot.focusNode, snapshot.focusOffset)
  3769. }
  3770. }
  3771. // Does the actual updating of the line display. Bails out
  3772. // (returning false) when there is nothing to be done and forced is
  3773. // false.
  3774. function updateDisplayIfNeeded(cm, update) {
  3775. var display = cm.display, doc = cm.doc
  3776. if (update.editorIsHidden) {
  3777. resetView(cm)
  3778. return false
  3779. }
  3780. // Bail out if the visible area is already rendered and nothing changed.
  3781. if (!update.force &&
  3782. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3783. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3784. display.renderedView == display.view && countDirtyView(cm) == 0)
  3785. { return false }
  3786. if (maybeUpdateLineNumberWidth(cm)) {
  3787. resetView(cm)
  3788. update.dims = getDimensions(cm)
  3789. }
  3790. // Compute a suitable new viewport (from & to)
  3791. var end = doc.first + doc.size
  3792. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3793. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3794. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3795. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3796. if (sawCollapsedSpans) {
  3797. from = visualLineNo(cm.doc, from)
  3798. to = visualLineEndNo(cm.doc, to)
  3799. }
  3800. var different = from != display.viewFrom || to != display.viewTo ||
  3801. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3802. adjustView(cm, from, to)
  3803. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3804. // Position the mover div to align with the current scroll position
  3805. cm.display.mover.style.top = display.viewOffset + "px"
  3806. var toUpdate = countDirtyView(cm)
  3807. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3808. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3809. { return false }
  3810. // For big changes, we hide the enclosing element during the
  3811. // update, since that speeds up the operations on most browsers.
  3812. var selSnapshot = selectionSnapshot(cm)
  3813. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3814. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3815. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3816. display.renderedView = display.view
  3817. // There might have been a widget with a focused element that got
  3818. // hidden or updated, if so re-focus it.
  3819. restoreSelection(selSnapshot)
  3820. // Prevent selection and cursors from interfering with the scroll
  3821. // width and height.
  3822. removeChildren(display.cursorDiv)
  3823. removeChildren(display.selectionDiv)
  3824. display.gutters.style.height = display.sizer.style.minHeight = 0
  3825. if (different) {
  3826. display.lastWrapHeight = update.wrapperHeight
  3827. display.lastWrapWidth = update.wrapperWidth
  3828. startWorker(cm, 400)
  3829. }
  3830. display.updateLineNumbers = null
  3831. return true
  3832. }
  3833. function postUpdateDisplay(cm, update) {
  3834. var viewport = update.viewport
  3835. for (var first = true;; first = false) {
  3836. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3837. // Clip forced viewport to actual scrollable area.
  3838. if (viewport && viewport.top != null)
  3839. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3840. // Updated line heights might result in the drawn area not
  3841. // actually covering the viewport. Keep looping until it does.
  3842. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3843. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3844. { break }
  3845. }
  3846. if (!updateDisplayIfNeeded(cm, update)) { break }
  3847. updateHeightsInViewport(cm)
  3848. var barMeasure = measureForScrollbars(cm)
  3849. updateSelection(cm)
  3850. updateScrollbars(cm, barMeasure)
  3851. setDocumentHeight(cm, barMeasure)
  3852. update.force = false
  3853. }
  3854. update.signal(cm, "update", cm)
  3855. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3856. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3857. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3858. }
  3859. }
  3860. function updateDisplaySimple(cm, viewport) {
  3861. var update = new DisplayUpdate(cm, viewport)
  3862. if (updateDisplayIfNeeded(cm, update)) {
  3863. updateHeightsInViewport(cm)
  3864. postUpdateDisplay(cm, update)
  3865. var barMeasure = measureForScrollbars(cm)
  3866. updateSelection(cm)
  3867. updateScrollbars(cm, barMeasure)
  3868. setDocumentHeight(cm, barMeasure)
  3869. update.finish()
  3870. }
  3871. }
  3872. // Sync the actual display DOM structure with display.view, removing
  3873. // nodes for lines that are no longer in view, and creating the ones
  3874. // that are not there yet, and updating the ones that are out of
  3875. // date.
  3876. function patchDisplay(cm, updateNumbersFrom, dims) {
  3877. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3878. var container = display.lineDiv, cur = container.firstChild
  3879. function rm(node) {
  3880. var next = node.nextSibling
  3881. // Works around a throw-scroll bug in OS X Webkit
  3882. if (webkit && mac && cm.display.currentWheelTarget == node)
  3883. { node.style.display = "none" }
  3884. else
  3885. { node.parentNode.removeChild(node) }
  3886. return next
  3887. }
  3888. var view = display.view, lineN = display.viewFrom
  3889. // Loop over the elements in the view, syncing cur (the DOM nodes
  3890. // in display.lineDiv) with the view as we go.
  3891. for (var i = 0; i < view.length; i++) {
  3892. var lineView = view[i]
  3893. if (lineView.hidden) {
  3894. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3895. var node = buildLineElement(cm, lineView, lineN, dims)
  3896. container.insertBefore(node, cur)
  3897. } else { // Already drawn
  3898. while (cur != lineView.node) { cur = rm(cur) }
  3899. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3900. updateNumbersFrom <= lineN && lineView.lineNumber
  3901. if (lineView.changes) {
  3902. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3903. updateLineForChanges(cm, lineView, lineN, dims)
  3904. }
  3905. if (updateNumber) {
  3906. removeChildren(lineView.lineNumber)
  3907. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3908. }
  3909. cur = lineView.node.nextSibling
  3910. }
  3911. lineN += lineView.size
  3912. }
  3913. while (cur) { cur = rm(cur) }
  3914. }
  3915. function updateGutterSpace(cm) {
  3916. var width = cm.display.gutters.offsetWidth
  3917. cm.display.sizer.style.marginLeft = width + "px"
  3918. }
  3919. function setDocumentHeight(cm, measure) {
  3920. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3921. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3922. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3923. }
  3924. // Rebuild the gutter elements, ensure the margin to the left of the
  3925. // code matches their width.
  3926. function updateGutters(cm) {
  3927. var gutters = cm.display.gutters, specs = cm.options.gutters
  3928. removeChildren(gutters)
  3929. var i = 0
  3930. for (; i < specs.length; ++i) {
  3931. var gutterClass = specs[i]
  3932. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3933. if (gutterClass == "CodeMirror-linenumbers") {
  3934. cm.display.lineGutter = gElt
  3935. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3936. }
  3937. }
  3938. gutters.style.display = i ? "" : "none"
  3939. updateGutterSpace(cm)
  3940. }
  3941. // Make sure the gutters options contains the element
  3942. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3943. function setGuttersForLineNumbers(options) {
  3944. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3945. if (found == -1 && options.lineNumbers) {
  3946. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3947. } else if (found > -1 && !options.lineNumbers) {
  3948. options.gutters = options.gutters.slice(0)
  3949. options.gutters.splice(found, 1)
  3950. }
  3951. }
  3952. var wheelSamples = 0;
  3953. var wheelPixelsPerUnit = null;
  3954. // Fill in a browser-detected starting value on browsers where we
  3955. // know one. These don't have to be accurate -- the result of them
  3956. // being wrong would just be a slight flicker on the first wheel
  3957. // scroll (if it is large enough).
  3958. if (ie) { wheelPixelsPerUnit = -.53 }
  3959. else if (gecko) { wheelPixelsPerUnit = 15 }
  3960. else if (chrome) { wheelPixelsPerUnit = -.7 }
  3961. else if (safari) { wheelPixelsPerUnit = -1/3 }
  3962. function wheelEventDelta(e) {
  3963. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  3964. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  3965. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  3966. else if (dy == null) { dy = e.wheelDelta }
  3967. return {x: dx, y: dy}
  3968. }
  3969. function wheelEventPixels(e) {
  3970. var delta = wheelEventDelta(e)
  3971. delta.x *= wheelPixelsPerUnit
  3972. delta.y *= wheelPixelsPerUnit
  3973. return delta
  3974. }
  3975. function onScrollWheel(cm, e) {
  3976. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  3977. var display = cm.display, scroll = display.scroller
  3978. // Quit if there's nothing to scroll here
  3979. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  3980. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  3981. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3982. // Webkit browsers on OS X abort momentum scrolls when the target
  3983. // of the scroll event is removed from the scrollable element.
  3984. // This hack (see related code in patchDisplay) makes sure the
  3985. // element is kept around.
  3986. if (dy && mac && webkit) {
  3987. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3988. for (var i = 0; i < view.length; i++) {
  3989. if (view[i].node == cur) {
  3990. cm.display.currentWheelTarget = cur
  3991. break outer
  3992. }
  3993. }
  3994. }
  3995. }
  3996. // On some browsers, horizontal scrolling will cause redraws to
  3997. // happen before the gutter has been realigned, causing it to
  3998. // wriggle around in a most unseemly way. When we have an
  3999. // estimated pixels/delta value, we just handle horizontal
  4000. // scrolling entirely here. It'll be slightly off from native, but
  4001. // better than glitching out.
  4002. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4003. if (dy && canScrollY)
  4004. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) }
  4005. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit))
  4006. // Only prevent default scrolling if vertical scrolling is
  4007. // actually possible. Otherwise, it causes vertical scroll
  4008. // jitter on OSX trackpads when deltaX is small and deltaY
  4009. // is large (issue #3579)
  4010. if (!dy || (dy && canScrollY))
  4011. { e_preventDefault(e) }
  4012. display.wheelStartX = null // Abort measurement, if in progress
  4013. return
  4014. }
  4015. // 'Project' the visible viewport to cover the area that is being
  4016. // scrolled into view (if we know enough to estimate it).
  4017. if (dy && wheelPixelsPerUnit != null) {
  4018. var pixels = dy * wheelPixelsPerUnit
  4019. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  4020. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  4021. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  4022. updateDisplaySimple(cm, {top: top, bottom: bot})
  4023. }
  4024. if (wheelSamples < 20) {
  4025. if (display.wheelStartX == null) {
  4026. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  4027. display.wheelDX = dx; display.wheelDY = dy
  4028. setTimeout(function () {
  4029. if (display.wheelStartX == null) { return }
  4030. var movedX = scroll.scrollLeft - display.wheelStartX
  4031. var movedY = scroll.scrollTop - display.wheelStartY
  4032. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4033. (movedX && display.wheelDX && movedX / display.wheelDX)
  4034. display.wheelStartX = display.wheelStartY = null
  4035. if (!sample) { return }
  4036. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  4037. ++wheelSamples
  4038. }, 200)
  4039. } else {
  4040. display.wheelDX += dx; display.wheelDY += dy
  4041. }
  4042. }
  4043. }
  4044. // Selection objects are immutable. A new one is created every time
  4045. // the selection changes. A selection is one or more non-overlapping
  4046. // (and non-touching) ranges, sorted, and an integer that indicates
  4047. // which one is the primary selection (the one that's scrolled into
  4048. // view, that getCursor returns, etc).
  4049. var Selection = function(ranges, primIndex) {
  4050. this.ranges = ranges
  4051. this.primIndex = primIndex
  4052. };
  4053. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4054. Selection.prototype.equals = function (other) {
  4055. var this$1 = this;
  4056. if (other == this) { return true }
  4057. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4058. for (var i = 0; i < this.ranges.length; i++) {
  4059. var here = this$1.ranges[i], there = other.ranges[i]
  4060. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4061. }
  4062. return true
  4063. };
  4064. Selection.prototype.deepCopy = function () {
  4065. var this$1 = this;
  4066. var out = []
  4067. for (var i = 0; i < this.ranges.length; i++)
  4068. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  4069. return new Selection(out, this.primIndex)
  4070. };
  4071. Selection.prototype.somethingSelected = function () {
  4072. var this$1 = this;
  4073. for (var i = 0; i < this.ranges.length; i++)
  4074. { if (!this$1.ranges[i].empty()) { return true } }
  4075. return false
  4076. };
  4077. Selection.prototype.contains = function (pos, end) {
  4078. var this$1 = this;
  4079. if (!end) { end = pos }
  4080. for (var i = 0; i < this.ranges.length; i++) {
  4081. var range = this$1.ranges[i]
  4082. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4083. { return i }
  4084. }
  4085. return -1
  4086. };
  4087. var Range = function(anchor, head) {
  4088. this.anchor = anchor; this.head = head
  4089. };
  4090. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4091. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4092. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4093. // Take an unsorted, potentially overlapping set of ranges, and
  4094. // build a selection out of it. 'Consumes' ranges array (modifying
  4095. // it).
  4096. function normalizeSelection(ranges, primIndex) {
  4097. var prim = ranges[primIndex]
  4098. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  4099. primIndex = indexOf(ranges, prim)
  4100. for (var i = 1; i < ranges.length; i++) {
  4101. var cur = ranges[i], prev = ranges[i - 1]
  4102. if (cmp(prev.to(), cur.from()) >= 0) {
  4103. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  4104. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  4105. if (i <= primIndex) { --primIndex }
  4106. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  4107. }
  4108. }
  4109. return new Selection(ranges, primIndex)
  4110. }
  4111. function simpleSelection(anchor, head) {
  4112. return new Selection([new Range(anchor, head || anchor)], 0)
  4113. }
  4114. // Compute the position of the end of a change (its 'to' property
  4115. // refers to the pre-change end).
  4116. function changeEnd(change) {
  4117. if (!change.text) { return change.to }
  4118. return Pos(change.from.line + change.text.length - 1,
  4119. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4120. }
  4121. // Adjust a position to refer to the post-change position of the
  4122. // same text, or the end of the change if the change covers it.
  4123. function adjustForChange(pos, change) {
  4124. if (cmp(pos, change.from) < 0) { return pos }
  4125. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4126. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  4127. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  4128. return Pos(line, ch)
  4129. }
  4130. function computeSelAfterChange(doc, change) {
  4131. var out = []
  4132. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4133. var range = doc.sel.ranges[i]
  4134. out.push(new Range(adjustForChange(range.anchor, change),
  4135. adjustForChange(range.head, change)))
  4136. }
  4137. return normalizeSelection(out, doc.sel.primIndex)
  4138. }
  4139. function offsetPos(pos, old, nw) {
  4140. if (pos.line == old.line)
  4141. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4142. else
  4143. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4144. }
  4145. // Used by replaceSelections to allow moving the selection to the
  4146. // start or around the replaced test. Hint may be "start" or "around".
  4147. function computeReplacedSel(doc, changes, hint) {
  4148. var out = []
  4149. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  4150. for (var i = 0; i < changes.length; i++) {
  4151. var change = changes[i]
  4152. var from = offsetPos(change.from, oldPrev, newPrev)
  4153. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  4154. oldPrev = change.to
  4155. newPrev = to
  4156. if (hint == "around") {
  4157. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  4158. out[i] = new Range(inv ? to : from, inv ? from : to)
  4159. } else {
  4160. out[i] = new Range(from, from)
  4161. }
  4162. }
  4163. return new Selection(out, doc.sel.primIndex)
  4164. }
  4165. // Used to get the editor into a consistent state again when options change.
  4166. function loadMode(cm) {
  4167. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  4168. resetModeState(cm)
  4169. }
  4170. function resetModeState(cm) {
  4171. cm.doc.iter(function (line) {
  4172. if (line.stateAfter) { line.stateAfter = null }
  4173. if (line.styles) { line.styles = null }
  4174. })
  4175. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first
  4176. startWorker(cm, 100)
  4177. cm.state.modeGen++
  4178. if (cm.curOp) { regChange(cm) }
  4179. }
  4180. // DOCUMENT DATA STRUCTURE
  4181. // By default, updates that start and end at the beginning of a line
  4182. // are treated specially, in order to make the association of line
  4183. // widgets and marker elements with the text behave more intuitive.
  4184. function isWholeLineUpdate(doc, change) {
  4185. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4186. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4187. }
  4188. // Perform a change on the document data structure.
  4189. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4190. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4191. function update(line, text, spans) {
  4192. updateLine(line, text, spans, estimateHeight)
  4193. signalLater(line, "change", line, change)
  4194. }
  4195. function linesFor(start, end) {
  4196. var result = []
  4197. for (var i = start; i < end; ++i)
  4198. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  4199. return result
  4200. }
  4201. var from = change.from, to = change.to, text = change.text
  4202. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  4203. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  4204. // Adjust the line structure
  4205. if (change.full) {
  4206. doc.insert(0, linesFor(0, text.length))
  4207. doc.remove(text.length, doc.size - text.length)
  4208. } else if (isWholeLineUpdate(doc, change)) {
  4209. // This is a whole-line replace. Treated specially to make
  4210. // sure line objects move the way they are supposed to.
  4211. var added = linesFor(0, text.length - 1)
  4212. update(lastLine, lastLine.text, lastSpans)
  4213. if (nlines) { doc.remove(from.line, nlines) }
  4214. if (added.length) { doc.insert(from.line, added) }
  4215. } else if (firstLine == lastLine) {
  4216. if (text.length == 1) {
  4217. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4218. } else {
  4219. var added$1 = linesFor(1, text.length - 1)
  4220. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4221. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4222. doc.insert(from.line + 1, added$1)
  4223. }
  4224. } else if (text.length == 1) {
  4225. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4226. doc.remove(from.line + 1, nlines)
  4227. } else {
  4228. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4229. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4230. var added$2 = linesFor(1, text.length - 1)
  4231. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4232. doc.insert(from.line + 1, added$2)
  4233. }
  4234. signalLater(doc, "change", doc, change)
  4235. }
  4236. // Call f for all linked documents.
  4237. function linkedDocs(doc, f, sharedHistOnly) {
  4238. function propagate(doc, skip, sharedHist) {
  4239. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4240. var rel = doc.linked[i]
  4241. if (rel.doc == skip) { continue }
  4242. var shared = sharedHist && rel.sharedHist
  4243. if (sharedHistOnly && !shared) { continue }
  4244. f(rel.doc, shared)
  4245. propagate(rel.doc, doc, shared)
  4246. } }
  4247. }
  4248. propagate(doc, null, true)
  4249. }
  4250. // Attach a document to an editor.
  4251. function attachDoc(cm, doc) {
  4252. if (doc.cm) { throw new Error("This document is already in use.") }
  4253. cm.doc = doc
  4254. doc.cm = cm
  4255. estimateLineHeights(cm)
  4256. loadMode(cm)
  4257. setDirectionClass(cm)
  4258. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4259. cm.options.mode = doc.modeOption
  4260. regChange(cm)
  4261. }
  4262. function setDirectionClass(cm) {
  4263. ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl")
  4264. }
  4265. function directionChanged(cm) {
  4266. runInOp(cm, function () {
  4267. setDirectionClass(cm)
  4268. regChange(cm)
  4269. })
  4270. }
  4271. function History(startGen) {
  4272. // Arrays of change events and selections. Doing something adds an
  4273. // event to done and clears undo. Undoing moves events from done
  4274. // to undone, redoing moves them in the other direction.
  4275. this.done = []; this.undone = []
  4276. this.undoDepth = Infinity
  4277. // Used to track when changes can be merged into a single undo
  4278. // event
  4279. this.lastModTime = this.lastSelTime = 0
  4280. this.lastOp = this.lastSelOp = null
  4281. this.lastOrigin = this.lastSelOrigin = null
  4282. // Used by the isClean() method
  4283. this.generation = this.maxGeneration = startGen || 1
  4284. }
  4285. // Create a history change event from an updateDoc-style change
  4286. // object.
  4287. function historyChangeFromChange(doc, change) {
  4288. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4289. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4290. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4291. return histChange
  4292. }
  4293. // Pop all selection events off the end of a history array. Stop at
  4294. // a change event.
  4295. function clearSelectionEvents(array) {
  4296. while (array.length) {
  4297. var last = lst(array)
  4298. if (last.ranges) { array.pop() }
  4299. else { break }
  4300. }
  4301. }
  4302. // Find the top change event in the history. Pop off selection
  4303. // events that are in the way.
  4304. function lastChangeEvent(hist, force) {
  4305. if (force) {
  4306. clearSelectionEvents(hist.done)
  4307. return lst(hist.done)
  4308. } else if (hist.done.length && !lst(hist.done).ranges) {
  4309. return lst(hist.done)
  4310. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4311. hist.done.pop()
  4312. return lst(hist.done)
  4313. }
  4314. }
  4315. // Register a change in the history. Merges changes that are within
  4316. // a single operation, or are close together with an origin that
  4317. // allows merging (starting with "+") into a single event.
  4318. function addChangeToHistory(doc, change, selAfter, opId) {
  4319. var hist = doc.history
  4320. hist.undone.length = 0
  4321. var time = +new Date, cur
  4322. var last
  4323. if ((hist.lastOp == opId ||
  4324. hist.lastOrigin == change.origin && change.origin &&
  4325. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4326. change.origin.charAt(0) == "*")) &&
  4327. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4328. // Merge this change into the last event
  4329. last = lst(cur.changes)
  4330. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4331. // Optimized case for simple insertion -- don't want to add
  4332. // new changesets for every character typed
  4333. last.to = changeEnd(change)
  4334. } else {
  4335. // Add new sub-event
  4336. cur.changes.push(historyChangeFromChange(doc, change))
  4337. }
  4338. } else {
  4339. // Can not be merged, start a new event.
  4340. var before = lst(hist.done)
  4341. if (!before || !before.ranges)
  4342. { pushSelectionToHistory(doc.sel, hist.done) }
  4343. cur = {changes: [historyChangeFromChange(doc, change)],
  4344. generation: hist.generation}
  4345. hist.done.push(cur)
  4346. while (hist.done.length > hist.undoDepth) {
  4347. hist.done.shift()
  4348. if (!hist.done[0].ranges) { hist.done.shift() }
  4349. }
  4350. }
  4351. hist.done.push(selAfter)
  4352. hist.generation = ++hist.maxGeneration
  4353. hist.lastModTime = hist.lastSelTime = time
  4354. hist.lastOp = hist.lastSelOp = opId
  4355. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4356. if (!last) { signal(doc, "historyAdded") }
  4357. }
  4358. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4359. var ch = origin.charAt(0)
  4360. return ch == "*" ||
  4361. ch == "+" &&
  4362. prev.ranges.length == sel.ranges.length &&
  4363. prev.somethingSelected() == sel.somethingSelected() &&
  4364. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4365. }
  4366. // Called whenever the selection changes, sets the new selection as
  4367. // the pending selection in the history, and pushes the old pending
  4368. // selection into the 'done' array when it was significantly
  4369. // different (in number of selected ranges, emptiness, or time).
  4370. function addSelectionToHistory(doc, sel, opId, options) {
  4371. var hist = doc.history, origin = options && options.origin
  4372. // A new event is started when the previous origin does not match
  4373. // the current, or the origins don't allow matching. Origins
  4374. // starting with * are always merged, those starting with + are
  4375. // merged when similar and close together in time.
  4376. if (opId == hist.lastSelOp ||
  4377. (origin && hist.lastSelOrigin == origin &&
  4378. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4379. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4380. { hist.done[hist.done.length - 1] = sel }
  4381. else
  4382. { pushSelectionToHistory(sel, hist.done) }
  4383. hist.lastSelTime = +new Date
  4384. hist.lastSelOrigin = origin
  4385. hist.lastSelOp = opId
  4386. if (options && options.clearRedo !== false)
  4387. { clearSelectionEvents(hist.undone) }
  4388. }
  4389. function pushSelectionToHistory(sel, dest) {
  4390. var top = lst(dest)
  4391. if (!(top && top.ranges && top.equals(sel)))
  4392. { dest.push(sel) }
  4393. }
  4394. // Used to store marked span information in the history.
  4395. function attachLocalSpans(doc, change, from, to) {
  4396. var existing = change["spans_" + doc.id], n = 0
  4397. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4398. if (line.markedSpans)
  4399. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4400. ++n
  4401. })
  4402. }
  4403. // When un/re-doing restores text containing marked spans, those
  4404. // that have been explicitly cleared should not be restored.
  4405. function removeClearedSpans(spans) {
  4406. if (!spans) { return null }
  4407. var out
  4408. for (var i = 0; i < spans.length; ++i) {
  4409. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4410. else if (out) { out.push(spans[i]) }
  4411. }
  4412. return !out ? spans : out.length ? out : null
  4413. }
  4414. // Retrieve and filter the old marked spans stored in a change event.
  4415. function getOldSpans(doc, change) {
  4416. var found = change["spans_" + doc.id]
  4417. if (!found) { return null }
  4418. var nw = []
  4419. for (var i = 0; i < change.text.length; ++i)
  4420. { nw.push(removeClearedSpans(found[i])) }
  4421. return nw
  4422. }
  4423. // Used for un/re-doing changes from the history. Combines the
  4424. // result of computing the existing spans with the set of spans that
  4425. // existed in the history (so that deleting around a span and then
  4426. // undoing brings back the span).
  4427. function mergeOldSpans(doc, change) {
  4428. var old = getOldSpans(doc, change)
  4429. var stretched = stretchSpansOverChange(doc, change)
  4430. if (!old) { return stretched }
  4431. if (!stretched) { return old }
  4432. for (var i = 0; i < old.length; ++i) {
  4433. var oldCur = old[i], stretchCur = stretched[i]
  4434. if (oldCur && stretchCur) {
  4435. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4436. var span = stretchCur[j]
  4437. for (var k = 0; k < oldCur.length; ++k)
  4438. { if (oldCur[k].marker == span.marker) { continue spans } }
  4439. oldCur.push(span)
  4440. }
  4441. } else if (stretchCur) {
  4442. old[i] = stretchCur
  4443. }
  4444. }
  4445. return old
  4446. }
  4447. // Used both to provide a JSON-safe object in .getHistory, and, when
  4448. // detaching a document, to split the history in two
  4449. function copyHistoryArray(events, newGroup, instantiateSel) {
  4450. var copy = []
  4451. for (var i = 0; i < events.length; ++i) {
  4452. var event = events[i]
  4453. if (event.ranges) {
  4454. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4455. continue
  4456. }
  4457. var changes = event.changes, newChanges = []
  4458. copy.push({changes: newChanges})
  4459. for (var j = 0; j < changes.length; ++j) {
  4460. var change = changes[j], m = (void 0)
  4461. newChanges.push({from: change.from, to: change.to, text: change.text})
  4462. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4463. if (indexOf(newGroup, Number(m[1])) > -1) {
  4464. lst(newChanges)[prop] = change[prop]
  4465. delete change[prop]
  4466. }
  4467. } } }
  4468. }
  4469. }
  4470. return copy
  4471. }
  4472. // The 'scroll' parameter given to many of these indicated whether
  4473. // the new cursor position should be scrolled into view after
  4474. // modifying the selection.
  4475. // If shift is held or the extend flag is set, extends a range to
  4476. // include a given position (and optionally a second position).
  4477. // Otherwise, simply returns the range between the given positions.
  4478. // Used for cursor motion and such.
  4479. function extendRange(range, head, other, extend) {
  4480. if (extend) {
  4481. var anchor = range.anchor
  4482. if (other) {
  4483. var posBefore = cmp(head, anchor) < 0
  4484. if (posBefore != (cmp(other, anchor) < 0)) {
  4485. anchor = head
  4486. head = other
  4487. } else if (posBefore != (cmp(head, other) < 0)) {
  4488. head = other
  4489. }
  4490. }
  4491. return new Range(anchor, head)
  4492. } else {
  4493. return new Range(other || head, head)
  4494. }
  4495. }
  4496. // Extend the primary selection range, discard the rest.
  4497. function extendSelection(doc, head, other, options, extend) {
  4498. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend) }
  4499. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)
  4500. }
  4501. // Extend all selections (pos is an array of selections with length
  4502. // equal the number of selections)
  4503. function extendSelections(doc, heads, options) {
  4504. var out = []
  4505. var extend = doc.cm && (doc.cm.display.shift || doc.extend)
  4506. for (var i = 0; i < doc.sel.ranges.length; i++)
  4507. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) }
  4508. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4509. setSelection(doc, newSel, options)
  4510. }
  4511. // Updates a single range in the selection.
  4512. function replaceOneSelection(doc, i, range, options) {
  4513. var ranges = doc.sel.ranges.slice(0)
  4514. ranges[i] = range
  4515. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4516. }
  4517. // Reset the selection to a single range.
  4518. function setSimpleSelection(doc, anchor, head, options) {
  4519. setSelection(doc, simpleSelection(anchor, head), options)
  4520. }
  4521. // Give beforeSelectionChange handlers a change to influence a
  4522. // selection update.
  4523. function filterSelectionChange(doc, sel, options) {
  4524. var obj = {
  4525. ranges: sel.ranges,
  4526. update: function(ranges) {
  4527. var this$1 = this;
  4528. this.ranges = []
  4529. for (var i = 0; i < ranges.length; i++)
  4530. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4531. clipPos(doc, ranges[i].head)) }
  4532. },
  4533. origin: options && options.origin
  4534. }
  4535. signal(doc, "beforeSelectionChange", doc, obj)
  4536. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4537. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4538. else { return sel }
  4539. }
  4540. function setSelectionReplaceHistory(doc, sel, options) {
  4541. var done = doc.history.done, last = lst(done)
  4542. if (last && last.ranges) {
  4543. done[done.length - 1] = sel
  4544. setSelectionNoUndo(doc, sel, options)
  4545. } else {
  4546. setSelection(doc, sel, options)
  4547. }
  4548. }
  4549. // Set a new selection.
  4550. function setSelection(doc, sel, options) {
  4551. setSelectionNoUndo(doc, sel, options)
  4552. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4553. }
  4554. function setSelectionNoUndo(doc, sel, options) {
  4555. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4556. { sel = filterSelectionChange(doc, sel, options) }
  4557. var bias = options && options.bias ||
  4558. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4559. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4560. if (!(options && options.scroll === false) && doc.cm)
  4561. { ensureCursorVisible(doc.cm) }
  4562. }
  4563. function setSelectionInner(doc, sel) {
  4564. if (sel.equals(doc.sel)) { return }
  4565. doc.sel = sel
  4566. if (doc.cm) {
  4567. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4568. signalCursorActivity(doc.cm)
  4569. }
  4570. signalLater(doc, "cursorActivity", doc)
  4571. }
  4572. // Verify that the selection does not partially select any atomic
  4573. // marked ranges.
  4574. function reCheckSelection(doc) {
  4575. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))
  4576. }
  4577. // Return a selection that does not partially select any atomic
  4578. // ranges.
  4579. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4580. var out
  4581. for (var i = 0; i < sel.ranges.length; i++) {
  4582. var range = sel.ranges[i]
  4583. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4584. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4585. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4586. if (out || newAnchor != range.anchor || newHead != range.head) {
  4587. if (!out) { out = sel.ranges.slice(0, i) }
  4588. out[i] = new Range(newAnchor, newHead)
  4589. }
  4590. }
  4591. return out ? normalizeSelection(out, sel.primIndex) : sel
  4592. }
  4593. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4594. var line = getLine(doc, pos.line)
  4595. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4596. var sp = line.markedSpans[i], m = sp.marker
  4597. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4598. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4599. if (mayClear) {
  4600. signal(m, "beforeCursorEnter")
  4601. if (m.explicitlyCleared) {
  4602. if (!line.markedSpans) { break }
  4603. else {--i; continue}
  4604. }
  4605. }
  4606. if (!m.atomic) { continue }
  4607. if (oldPos) {
  4608. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4609. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4610. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4611. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4612. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4613. }
  4614. var far = m.find(dir < 0 ? -1 : 1)
  4615. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4616. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4617. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4618. }
  4619. } }
  4620. return pos
  4621. }
  4622. // Ensure a given position is not inside an atomic range.
  4623. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4624. var dir = bias || 1
  4625. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4626. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4627. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4628. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4629. if (!found) {
  4630. doc.cantEdit = true
  4631. return Pos(doc.first, 0)
  4632. }
  4633. return found
  4634. }
  4635. function movePos(doc, pos, dir, line) {
  4636. if (dir < 0 && pos.ch == 0) {
  4637. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4638. else { return null }
  4639. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4640. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4641. else { return null }
  4642. } else {
  4643. return new Pos(pos.line, pos.ch + dir)
  4644. }
  4645. }
  4646. function selectAll(cm) {
  4647. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4648. }
  4649. // UPDATING
  4650. // Allow "beforeChange" event handlers to influence a change
  4651. function filterChange(doc, change, update) {
  4652. var obj = {
  4653. canceled: false,
  4654. from: change.from,
  4655. to: change.to,
  4656. text: change.text,
  4657. origin: change.origin,
  4658. cancel: function () { return obj.canceled = true; }
  4659. }
  4660. if (update) { obj.update = function (from, to, text, origin) {
  4661. if (from) { obj.from = clipPos(doc, from) }
  4662. if (to) { obj.to = clipPos(doc, to) }
  4663. if (text) { obj.text = text }
  4664. if (origin !== undefined) { obj.origin = origin }
  4665. } }
  4666. signal(doc, "beforeChange", doc, obj)
  4667. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4668. if (obj.canceled) { return null }
  4669. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4670. }
  4671. // Apply a change to a document, and add it to the document's
  4672. // history, and propagating it to all linked documents.
  4673. function makeChange(doc, change, ignoreReadOnly) {
  4674. if (doc.cm) {
  4675. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4676. if (doc.cm.state.suppressEdits) { return }
  4677. }
  4678. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4679. change = filterChange(doc, change, true)
  4680. if (!change) { return }
  4681. }
  4682. // Possibly split or suppress the update based on the presence
  4683. // of read-only spans in its range.
  4684. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4685. if (split) {
  4686. for (var i = split.length - 1; i >= 0; --i)
  4687. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) }
  4688. } else {
  4689. makeChangeInner(doc, change)
  4690. }
  4691. }
  4692. function makeChangeInner(doc, change) {
  4693. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4694. var selAfter = computeSelAfterChange(doc, change)
  4695. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4696. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4697. var rebased = []
  4698. linkedDocs(doc, function (doc, sharedHist) {
  4699. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4700. rebaseHist(doc.history, change)
  4701. rebased.push(doc.history)
  4702. }
  4703. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4704. })
  4705. }
  4706. // Revert a change stored in a document's history.
  4707. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4708. var suppress = doc.cm && doc.cm.state.suppressEdits
  4709. if (suppress && !allowSelectionOnly) { return }
  4710. var hist = doc.history, event, selAfter = doc.sel
  4711. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4712. // Verify that there is a useable event (so that ctrl-z won't
  4713. // needlessly clear selection events)
  4714. var i = 0
  4715. for (; i < source.length; i++) {
  4716. event = source[i]
  4717. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4718. { break }
  4719. }
  4720. if (i == source.length) { return }
  4721. hist.lastOrigin = hist.lastSelOrigin = null
  4722. for (;;) {
  4723. event = source.pop()
  4724. if (event.ranges) {
  4725. pushSelectionToHistory(event, dest)
  4726. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4727. setSelection(doc, event, {clearRedo: false})
  4728. return
  4729. }
  4730. selAfter = event
  4731. } else if (suppress) {
  4732. source.push(event)
  4733. return
  4734. } else { break }
  4735. }
  4736. // Build up a reverse change object to add to the opposite history
  4737. // stack (redo when undoing, and vice versa).
  4738. var antiChanges = []
  4739. pushSelectionToHistory(selAfter, dest)
  4740. dest.push({changes: antiChanges, generation: hist.generation})
  4741. hist.generation = event.generation || ++hist.maxGeneration
  4742. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4743. var loop = function ( i ) {
  4744. var change = event.changes[i]
  4745. change.origin = type
  4746. if (filter && !filterChange(doc, change, false)) {
  4747. source.length = 0
  4748. return {}
  4749. }
  4750. antiChanges.push(historyChangeFromChange(doc, change))
  4751. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4752. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4753. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4754. var rebased = []
  4755. // Propagate to the linked documents
  4756. linkedDocs(doc, function (doc, sharedHist) {
  4757. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4758. rebaseHist(doc.history, change)
  4759. rebased.push(doc.history)
  4760. }
  4761. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4762. })
  4763. };
  4764. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4765. var returned = loop( i$1 );
  4766. if ( returned ) return returned.v;
  4767. }
  4768. }
  4769. // Sub-views need their line numbers shifted when text is added
  4770. // above or below them in the parent document.
  4771. function shiftDoc(doc, distance) {
  4772. if (distance == 0) { return }
  4773. doc.first += distance
  4774. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4775. Pos(range.anchor.line + distance, range.anchor.ch),
  4776. Pos(range.head.line + distance, range.head.ch)
  4777. ); }), doc.sel.primIndex)
  4778. if (doc.cm) {
  4779. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4780. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4781. { regLineChange(doc.cm, l, "gutter") }
  4782. }
  4783. }
  4784. // More lower-level change function, handling only a single document
  4785. // (not linked ones).
  4786. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4787. if (doc.cm && !doc.cm.curOp)
  4788. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4789. if (change.to.line < doc.first) {
  4790. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4791. return
  4792. }
  4793. if (change.from.line > doc.lastLine()) { return }
  4794. // Clip the change to the size of this doc
  4795. if (change.from.line < doc.first) {
  4796. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4797. shiftDoc(doc, shift)
  4798. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4799. text: [lst(change.text)], origin: change.origin}
  4800. }
  4801. var last = doc.lastLine()
  4802. if (change.to.line > last) {
  4803. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4804. text: [change.text[0]], origin: change.origin}
  4805. }
  4806. change.removed = getBetween(doc, change.from, change.to)
  4807. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4808. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4809. else { updateDoc(doc, change, spans) }
  4810. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4811. }
  4812. // Handle the interaction of a change to a document with the editor
  4813. // that this document is part of.
  4814. function makeChangeSingleDocInEditor(cm, change, spans) {
  4815. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4816. var recomputeMaxLength = false, checkWidthStart = from.line
  4817. if (!cm.options.lineWrapping) {
  4818. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4819. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4820. if (line == display.maxLine) {
  4821. recomputeMaxLength = true
  4822. return true
  4823. }
  4824. })
  4825. }
  4826. if (doc.sel.contains(change.from, change.to) > -1)
  4827. { signalCursorActivity(cm) }
  4828. updateDoc(doc, change, spans, estimateHeight(cm))
  4829. if (!cm.options.lineWrapping) {
  4830. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4831. var len = lineLength(line)
  4832. if (len > display.maxLineLength) {
  4833. display.maxLine = line
  4834. display.maxLineLength = len
  4835. display.maxLineChanged = true
  4836. recomputeMaxLength = false
  4837. }
  4838. })
  4839. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4840. }
  4841. retreatFrontier(doc, from.line)
  4842. startWorker(cm, 400)
  4843. var lendiff = change.text.length - (to.line - from.line) - 1
  4844. // Remember that these lines changed, for updating the display
  4845. if (change.full)
  4846. { regChange(cm) }
  4847. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4848. { regLineChange(cm, from.line, "text") }
  4849. else
  4850. { regChange(cm, from.line, to.line + 1, lendiff) }
  4851. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4852. if (changeHandler || changesHandler) {
  4853. var obj = {
  4854. from: from, to: to,
  4855. text: change.text,
  4856. removed: change.removed,
  4857. origin: change.origin
  4858. }
  4859. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4860. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4861. }
  4862. cm.display.selForContextMenu = null
  4863. }
  4864. function replaceRange(doc, code, from, to, origin) {
  4865. if (!to) { to = from }
  4866. if (cmp(to, from) < 0) { var assign;
  4867. (assign = [to, from], from = assign[0], to = assign[1], assign) }
  4868. if (typeof code == "string") { code = doc.splitLines(code) }
  4869. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4870. }
  4871. // Rebasing/resetting history to deal with externally-sourced changes
  4872. function rebaseHistSelSingle(pos, from, to, diff) {
  4873. if (to < pos.line) {
  4874. pos.line += diff
  4875. } else if (from < pos.line) {
  4876. pos.line = from
  4877. pos.ch = 0
  4878. }
  4879. }
  4880. // Tries to rebase an array of history events given a change in the
  4881. // document. If the change touches the same lines as the event, the
  4882. // event, and everything 'behind' it, is discarded. If the change is
  4883. // before the event, the event's positions are updated. Uses a
  4884. // copy-on-write scheme for the positions, to avoid having to
  4885. // reallocate them all on every rebase, but also avoid problems with
  4886. // shared position objects being unsafely updated.
  4887. function rebaseHistArray(array, from, to, diff) {
  4888. for (var i = 0; i < array.length; ++i) {
  4889. var sub = array[i], ok = true
  4890. if (sub.ranges) {
  4891. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4892. for (var j = 0; j < sub.ranges.length; j++) {
  4893. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4894. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4895. }
  4896. continue
  4897. }
  4898. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4899. var cur = sub.changes[j$1]
  4900. if (to < cur.from.line) {
  4901. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4902. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4903. } else if (from <= cur.to.line) {
  4904. ok = false
  4905. break
  4906. }
  4907. }
  4908. if (!ok) {
  4909. array.splice(0, i + 1)
  4910. i = 0
  4911. }
  4912. }
  4913. }
  4914. function rebaseHist(hist, change) {
  4915. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4916. rebaseHistArray(hist.done, from, to, diff)
  4917. rebaseHistArray(hist.undone, from, to, diff)
  4918. }
  4919. // Utility for applying a change to a line by handle or number,
  4920. // returning the number and optionally registering the line as
  4921. // changed.
  4922. function changeLine(doc, handle, changeType, op) {
  4923. var no = handle, line = handle
  4924. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4925. else { no = lineNo(handle) }
  4926. if (no == null) { return null }
  4927. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4928. return line
  4929. }
  4930. // The document is represented as a BTree consisting of leaves, with
  4931. // chunk of lines in them, and branches, with up to ten leaves or
  4932. // other branch nodes below them. The top node is always a branch
  4933. // node, and is the document object itself (meaning it has
  4934. // additional methods and properties).
  4935. //
  4936. // All nodes have parent links. The tree is used both to go from
  4937. // line numbers to line objects, and to go from objects to numbers.
  4938. // It also indexes by height, and is used to convert between height
  4939. // and line object, and to find the total height of the document.
  4940. //
  4941. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4942. function LeafChunk(lines) {
  4943. var this$1 = this;
  4944. this.lines = lines
  4945. this.parent = null
  4946. var height = 0
  4947. for (var i = 0; i < lines.length; ++i) {
  4948. lines[i].parent = this$1
  4949. height += lines[i].height
  4950. }
  4951. this.height = height
  4952. }
  4953. LeafChunk.prototype = {
  4954. chunkSize: function chunkSize() { return this.lines.length },
  4955. // Remove the n lines at offset 'at'.
  4956. removeInner: function removeInner(at, n) {
  4957. var this$1 = this;
  4958. for (var i = at, e = at + n; i < e; ++i) {
  4959. var line = this$1.lines[i]
  4960. this$1.height -= line.height
  4961. cleanUpLine(line)
  4962. signalLater(line, "delete")
  4963. }
  4964. this.lines.splice(at, n)
  4965. },
  4966. // Helper used to collapse a small branch into a single leaf.
  4967. collapse: function collapse(lines) {
  4968. lines.push.apply(lines, this.lines)
  4969. },
  4970. // Insert the given array of lines at offset 'at', count them as
  4971. // having the given height.
  4972. insertInner: function insertInner(at, lines, height) {
  4973. var this$1 = this;
  4974. this.height += height
  4975. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4976. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4977. },
  4978. // Used to iterate over a part of the tree.
  4979. iterN: function iterN(at, n, op) {
  4980. var this$1 = this;
  4981. for (var e = at + n; at < e; ++at)
  4982. { if (op(this$1.lines[at])) { return true } }
  4983. }
  4984. }
  4985. function BranchChunk(children) {
  4986. var this$1 = this;
  4987. this.children = children
  4988. var size = 0, height = 0
  4989. for (var i = 0; i < children.length; ++i) {
  4990. var ch = children[i]
  4991. size += ch.chunkSize(); height += ch.height
  4992. ch.parent = this$1
  4993. }
  4994. this.size = size
  4995. this.height = height
  4996. this.parent = null
  4997. }
  4998. BranchChunk.prototype = {
  4999. chunkSize: function chunkSize() { return this.size },
  5000. removeInner: function removeInner(at, n) {
  5001. var this$1 = this;
  5002. this.size -= n
  5003. for (var i = 0; i < this.children.length; ++i) {
  5004. var child = this$1.children[i], sz = child.chunkSize()
  5005. if (at < sz) {
  5006. var rm = Math.min(n, sz - at), oldHeight = child.height
  5007. child.removeInner(at, rm)
  5008. this$1.height -= oldHeight - child.height
  5009. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  5010. if ((n -= rm) == 0) { break }
  5011. at = 0
  5012. } else { at -= sz }
  5013. }
  5014. // If the result is smaller than 25 lines, ensure that it is a
  5015. // single leaf node.
  5016. if (this.size - n < 25 &&
  5017. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5018. var lines = []
  5019. this.collapse(lines)
  5020. this.children = [new LeafChunk(lines)]
  5021. this.children[0].parent = this
  5022. }
  5023. },
  5024. collapse: function collapse(lines) {
  5025. var this$1 = this;
  5026. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  5027. },
  5028. insertInner: function insertInner(at, lines, height) {
  5029. var this$1 = this;
  5030. this.size += lines.length
  5031. this.height += height
  5032. for (var i = 0; i < this.children.length; ++i) {
  5033. var child = this$1.children[i], sz = child.chunkSize()
  5034. if (at <= sz) {
  5035. child.insertInner(at, lines, height)
  5036. if (child.lines && child.lines.length > 50) {
  5037. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5038. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5039. var remaining = child.lines.length % 25 + 25
  5040. for (var pos = remaining; pos < child.lines.length;) {
  5041. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  5042. child.height -= leaf.height
  5043. this$1.children.splice(++i, 0, leaf)
  5044. leaf.parent = this$1
  5045. }
  5046. child.lines = child.lines.slice(0, remaining)
  5047. this$1.maybeSpill()
  5048. }
  5049. break
  5050. }
  5051. at -= sz
  5052. }
  5053. },
  5054. // When a node has grown, check whether it should be split.
  5055. maybeSpill: function maybeSpill() {
  5056. if (this.children.length <= 10) { return }
  5057. var me = this
  5058. do {
  5059. var spilled = me.children.splice(me.children.length - 5, 5)
  5060. var sibling = new BranchChunk(spilled)
  5061. if (!me.parent) { // Become the parent node
  5062. var copy = new BranchChunk(me.children)
  5063. copy.parent = me
  5064. me.children = [copy, sibling]
  5065. me = copy
  5066. } else {
  5067. me.size -= sibling.size
  5068. me.height -= sibling.height
  5069. var myIndex = indexOf(me.parent.children, me)
  5070. me.parent.children.splice(myIndex + 1, 0, sibling)
  5071. }
  5072. sibling.parent = me.parent
  5073. } while (me.children.length > 10)
  5074. me.parent.maybeSpill()
  5075. },
  5076. iterN: function iterN(at, n, op) {
  5077. var this$1 = this;
  5078. for (var i = 0; i < this.children.length; ++i) {
  5079. var child = this$1.children[i], sz = child.chunkSize()
  5080. if (at < sz) {
  5081. var used = Math.min(n, sz - at)
  5082. if (child.iterN(at, used, op)) { return true }
  5083. if ((n -= used) == 0) { break }
  5084. at = 0
  5085. } else { at -= sz }
  5086. }
  5087. }
  5088. }
  5089. // Line widgets are block elements displayed above or below a line.
  5090. var LineWidget = function(doc, node, options) {
  5091. var this$1 = this;
  5092. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5093. { this$1[opt] = options[opt] } } }
  5094. this.doc = doc
  5095. this.node = node
  5096. };
  5097. LineWidget.prototype.clear = function () {
  5098. var this$1 = this;
  5099. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  5100. if (no == null || !ws) { return }
  5101. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  5102. if (!ws.length) { line.widgets = null }
  5103. var height = widgetHeight(this)
  5104. updateLineHeight(line, Math.max(0, line.height - height))
  5105. if (cm) {
  5106. runInOp(cm, function () {
  5107. adjustScrollWhenAboveVisible(cm, line, -height)
  5108. regLineChange(cm, no, "widget")
  5109. })
  5110. signalLater(cm, "lineWidgetCleared", cm, this, no)
  5111. }
  5112. };
  5113. LineWidget.prototype.changed = function () {
  5114. var this$1 = this;
  5115. var oldH = this.height, cm = this.doc.cm, line = this.line
  5116. this.height = null
  5117. var diff = widgetHeight(this) - oldH
  5118. if (!diff) { return }
  5119. updateLineHeight(line, line.height + diff)
  5120. if (cm) {
  5121. runInOp(cm, function () {
  5122. cm.curOp.forceUpdate = true
  5123. adjustScrollWhenAboveVisible(cm, line, diff)
  5124. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line))
  5125. })
  5126. }
  5127. };
  5128. eventMixin(LineWidget)
  5129. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5130. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5131. { addToScrollTop(cm, diff) }
  5132. }
  5133. function addLineWidget(doc, handle, node, options) {
  5134. var widget = new LineWidget(doc, node, options)
  5135. var cm = doc.cm
  5136. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  5137. changeLine(doc, handle, "widget", function (line) {
  5138. var widgets = line.widgets || (line.widgets = [])
  5139. if (widget.insertAt == null) { widgets.push(widget) }
  5140. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  5141. widget.line = line
  5142. if (cm && !lineIsHidden(doc, line)) {
  5143. var aboveVisible = heightAtLine(line) < doc.scrollTop
  5144. updateLineHeight(line, line.height + widgetHeight(widget))
  5145. if (aboveVisible) { addToScrollTop(cm, widget.height) }
  5146. cm.curOp.forceUpdate = true
  5147. }
  5148. return true
  5149. })
  5150. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) }
  5151. return widget
  5152. }
  5153. // TEXTMARKERS
  5154. // Created with markText and setBookmark methods. A TextMarker is a
  5155. // handle that can be used to clear or find a marked position in the
  5156. // document. Line objects hold arrays (markedSpans) containing
  5157. // {from, to, marker} object pointing to such marker objects, and
  5158. // indicating that such a marker is present on that line. Multiple
  5159. // lines may point to the same marker when it spans across lines.
  5160. // The spans will have null for their from/to properties when the
  5161. // marker continues beyond the start/end of the line. Markers have
  5162. // links back to the lines they currently touch.
  5163. // Collapsed markers have unique ids, in order to be able to order
  5164. // them, which is needed for uniquely determining an outer marker
  5165. // when they overlap (they may nest, but not partially overlap).
  5166. var nextMarkerId = 0
  5167. var TextMarker = function(doc, type) {
  5168. this.lines = []
  5169. this.type = type
  5170. this.doc = doc
  5171. this.id = ++nextMarkerId
  5172. };
  5173. // Clear the marker.
  5174. TextMarker.prototype.clear = function () {
  5175. var this$1 = this;
  5176. if (this.explicitlyCleared) { return }
  5177. var cm = this.doc.cm, withOp = cm && !cm.curOp
  5178. if (withOp) { startOperation(cm) }
  5179. if (hasHandler(this, "clear")) {
  5180. var found = this.find()
  5181. if (found) { signalLater(this, "clear", found.from, found.to) }
  5182. }
  5183. var min = null, max = null
  5184. for (var i = 0; i < this.lines.length; ++i) {
  5185. var line = this$1.lines[i]
  5186. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5187. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  5188. else if (cm) {
  5189. if (span.to != null) { max = lineNo(line) }
  5190. if (span.from != null) { min = lineNo(line) }
  5191. }
  5192. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  5193. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5194. { updateLineHeight(line, textHeight(cm.display)) }
  5195. }
  5196. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5197. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  5198. if (len > cm.display.maxLineLength) {
  5199. cm.display.maxLine = visual
  5200. cm.display.maxLineLength = len
  5201. cm.display.maxLineChanged = true
  5202. }
  5203. } }
  5204. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  5205. this.lines.length = 0
  5206. this.explicitlyCleared = true
  5207. if (this.atomic && this.doc.cantEdit) {
  5208. this.doc.cantEdit = false
  5209. if (cm) { reCheckSelection(cm.doc) }
  5210. }
  5211. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) }
  5212. if (withOp) { endOperation(cm) }
  5213. if (this.parent) { this.parent.clear() }
  5214. };
  5215. // Find the position of the marker in the document. Returns a {from,
  5216. // to} object by default. Side can be passed to get a specific side
  5217. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5218. // Pos objects returned contain a line object, rather than a line
  5219. // number (used to prevent looking up the same line twice).
  5220. TextMarker.prototype.find = function (side, lineObj) {
  5221. var this$1 = this;
  5222. if (side == null && this.type == "bookmark") { side = 1 }
  5223. var from, to
  5224. for (var i = 0; i < this.lines.length; ++i) {
  5225. var line = this$1.lines[i]
  5226. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5227. if (span.from != null) {
  5228. from = Pos(lineObj ? line : lineNo(line), span.from)
  5229. if (side == -1) { return from }
  5230. }
  5231. if (span.to != null) {
  5232. to = Pos(lineObj ? line : lineNo(line), span.to)
  5233. if (side == 1) { return to }
  5234. }
  5235. }
  5236. return from && {from: from, to: to}
  5237. };
  5238. // Signals that the marker's widget changed, and surrounding layout
  5239. // should be recomputed.
  5240. TextMarker.prototype.changed = function () {
  5241. var this$1 = this;
  5242. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5243. if (!pos || !cm) { return }
  5244. runInOp(cm, function () {
  5245. var line = pos.line, lineN = lineNo(pos.line)
  5246. var view = findViewForLine(cm, lineN)
  5247. if (view) {
  5248. clearLineMeasurementCacheFor(view)
  5249. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5250. }
  5251. cm.curOp.updateMaxLine = true
  5252. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5253. var oldHeight = widget.height
  5254. widget.height = null
  5255. var dHeight = widgetHeight(widget) - oldHeight
  5256. if (dHeight)
  5257. { updateLineHeight(line, line.height + dHeight) }
  5258. }
  5259. signalLater(cm, "markerChanged", cm, this$1)
  5260. })
  5261. };
  5262. TextMarker.prototype.attachLine = function (line) {
  5263. if (!this.lines.length && this.doc.cm) {
  5264. var op = this.doc.cm.curOp
  5265. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5266. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5267. }
  5268. this.lines.push(line)
  5269. };
  5270. TextMarker.prototype.detachLine = function (line) {
  5271. this.lines.splice(indexOf(this.lines, line), 1)
  5272. if (!this.lines.length && this.doc.cm) {
  5273. var op = this.doc.cm.curOp
  5274. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5275. }
  5276. };
  5277. eventMixin(TextMarker)
  5278. // Create a marker, wire it up to the right lines, and
  5279. function markText(doc, from, to, options, type) {
  5280. // Shared markers (across linked documents) are handled separately
  5281. // (markTextShared will call out to this again, once per
  5282. // document).
  5283. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5284. // Ensure we are in an operation.
  5285. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5286. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5287. if (options) { copyObj(options, marker, false) }
  5288. // Don't connect empty markers unless clearWhenEmpty is false
  5289. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5290. { return marker }
  5291. if (marker.replacedWith) {
  5292. // Showing up as a widget implies collapsed (widget replaces text)
  5293. marker.collapsed = true
  5294. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget")
  5295. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5296. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5297. }
  5298. if (marker.collapsed) {
  5299. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5300. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5301. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5302. seeCollapsedSpans()
  5303. }
  5304. if (marker.addToHistory)
  5305. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5306. var curLine = from.line, cm = doc.cm, updateMaxLine
  5307. doc.iter(curLine, to.line + 1, function (line) {
  5308. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5309. { updateMaxLine = true }
  5310. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5311. addMarkedSpan(line, new MarkedSpan(marker,
  5312. curLine == from.line ? from.ch : null,
  5313. curLine == to.line ? to.ch : null))
  5314. ++curLine
  5315. })
  5316. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5317. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5318. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5319. }) }
  5320. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5321. if (marker.readOnly) {
  5322. seeReadOnlySpans()
  5323. if (doc.history.done.length || doc.history.undone.length)
  5324. { doc.clearHistory() }
  5325. }
  5326. if (marker.collapsed) {
  5327. marker.id = ++nextMarkerId
  5328. marker.atomic = true
  5329. }
  5330. if (cm) {
  5331. // Sync editor state
  5332. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5333. if (marker.collapsed)
  5334. { regChange(cm, from.line, to.line + 1) }
  5335. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5336. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5337. if (marker.atomic) { reCheckSelection(cm.doc) }
  5338. signalLater(cm, "markerAdded", cm, marker)
  5339. }
  5340. return marker
  5341. }
  5342. // SHARED TEXTMARKERS
  5343. // A shared marker spans multiple linked documents. It is
  5344. // implemented as a meta-marker-object controlling multiple normal
  5345. // markers.
  5346. var SharedTextMarker = function(markers, primary) {
  5347. var this$1 = this;
  5348. this.markers = markers
  5349. this.primary = primary
  5350. for (var i = 0; i < markers.length; ++i)
  5351. { markers[i].parent = this$1 }
  5352. };
  5353. SharedTextMarker.prototype.clear = function () {
  5354. var this$1 = this;
  5355. if (this.explicitlyCleared) { return }
  5356. this.explicitlyCleared = true
  5357. for (var i = 0; i < this.markers.length; ++i)
  5358. { this$1.markers[i].clear() }
  5359. signalLater(this, "clear")
  5360. };
  5361. SharedTextMarker.prototype.find = function (side, lineObj) {
  5362. return this.primary.find(side, lineObj)
  5363. };
  5364. eventMixin(SharedTextMarker)
  5365. function markTextShared(doc, from, to, options, type) {
  5366. options = copyObj(options)
  5367. options.shared = false
  5368. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5369. var widget = options.widgetNode
  5370. linkedDocs(doc, function (doc) {
  5371. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5372. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5373. for (var i = 0; i < doc.linked.length; ++i)
  5374. { if (doc.linked[i].isParent) { return } }
  5375. primary = lst(markers)
  5376. })
  5377. return new SharedTextMarker(markers, primary)
  5378. }
  5379. function findSharedMarkers(doc) {
  5380. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5381. }
  5382. function copySharedMarkers(doc, markers) {
  5383. for (var i = 0; i < markers.length; i++) {
  5384. var marker = markers[i], pos = marker.find()
  5385. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5386. if (cmp(mFrom, mTo)) {
  5387. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5388. marker.markers.push(subMark)
  5389. subMark.parent = marker
  5390. }
  5391. }
  5392. }
  5393. function detachSharedMarkers(markers) {
  5394. var loop = function ( i ) {
  5395. var marker = markers[i], linked = [marker.primary.doc]
  5396. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5397. for (var j = 0; j < marker.markers.length; j++) {
  5398. var subMarker = marker.markers[j]
  5399. if (indexOf(linked, subMarker.doc) == -1) {
  5400. subMarker.parent = null
  5401. marker.markers.splice(j--, 1)
  5402. }
  5403. }
  5404. };
  5405. for (var i = 0; i < markers.length; i++) loop( i );
  5406. }
  5407. var nextDocId = 0
  5408. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5409. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5410. if (firstLine == null) { firstLine = 0 }
  5411. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5412. this.first = firstLine
  5413. this.scrollTop = this.scrollLeft = 0
  5414. this.cantEdit = false
  5415. this.cleanGeneration = 1
  5416. this.modeFrontier = this.highlightFrontier = firstLine
  5417. var start = Pos(firstLine, 0)
  5418. this.sel = simpleSelection(start)
  5419. this.history = new History(null)
  5420. this.id = ++nextDocId
  5421. this.modeOption = mode
  5422. this.lineSep = lineSep
  5423. this.direction = (direction == "rtl") ? "rtl" : "ltr"
  5424. this.extend = false
  5425. if (typeof text == "string") { text = this.splitLines(text) }
  5426. updateDoc(this, {from: start, to: start, text: text})
  5427. setSelection(this, simpleSelection(start), sel_dontScroll)
  5428. }
  5429. Doc.prototype = createObj(BranchChunk.prototype, {
  5430. constructor: Doc,
  5431. // Iterate over the document. Supports two forms -- with only one
  5432. // argument, it calls that for each line in the document. With
  5433. // three, it iterates over the range given by the first two (with
  5434. // the second being non-inclusive).
  5435. iter: function(from, to, op) {
  5436. if (op) { this.iterN(from - this.first, to - from, op) }
  5437. else { this.iterN(this.first, this.first + this.size, from) }
  5438. },
  5439. // Non-public interface for adding and removing lines.
  5440. insert: function(at, lines) {
  5441. var height = 0
  5442. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5443. this.insertInner(at - this.first, lines, height)
  5444. },
  5445. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5446. // From here, the methods are part of the public interface. Most
  5447. // are also available from CodeMirror (editor) instances.
  5448. getValue: function(lineSep) {
  5449. var lines = getLines(this, this.first, this.first + this.size)
  5450. if (lineSep === false) { return lines }
  5451. return lines.join(lineSep || this.lineSeparator())
  5452. },
  5453. setValue: docMethodOp(function(code) {
  5454. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5455. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5456. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5457. if (this.cm) { scrollToCoords(this.cm, 0, 0) }
  5458. setSelection(this, simpleSelection(top), sel_dontScroll)
  5459. }),
  5460. replaceRange: function(code, from, to, origin) {
  5461. from = clipPos(this, from)
  5462. to = to ? clipPos(this, to) : from
  5463. replaceRange(this, code, from, to, origin)
  5464. },
  5465. getRange: function(from, to, lineSep) {
  5466. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5467. if (lineSep === false) { return lines }
  5468. return lines.join(lineSep || this.lineSeparator())
  5469. },
  5470. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5471. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5472. getLineNumber: function(line) {return lineNo(line)},
  5473. getLineHandleVisualStart: function(line) {
  5474. if (typeof line == "number") { line = getLine(this, line) }
  5475. return visualLine(line)
  5476. },
  5477. lineCount: function() {return this.size},
  5478. firstLine: function() {return this.first},
  5479. lastLine: function() {return this.first + this.size - 1},
  5480. clipPos: function(pos) {return clipPos(this, pos)},
  5481. getCursor: function(start) {
  5482. var range = this.sel.primary(), pos
  5483. if (start == null || start == "head") { pos = range.head }
  5484. else if (start == "anchor") { pos = range.anchor }
  5485. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5486. else { pos = range.from() }
  5487. return pos
  5488. },
  5489. listSelections: function() { return this.sel.ranges },
  5490. somethingSelected: function() {return this.sel.somethingSelected()},
  5491. setCursor: docMethodOp(function(line, ch, options) {
  5492. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5493. }),
  5494. setSelection: docMethodOp(function(anchor, head, options) {
  5495. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5496. }),
  5497. extendSelection: docMethodOp(function(head, other, options) {
  5498. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5499. }),
  5500. extendSelections: docMethodOp(function(heads, options) {
  5501. extendSelections(this, clipPosArray(this, heads), options)
  5502. }),
  5503. extendSelectionsBy: docMethodOp(function(f, options) {
  5504. var heads = map(this.sel.ranges, f)
  5505. extendSelections(this, clipPosArray(this, heads), options)
  5506. }),
  5507. setSelections: docMethodOp(function(ranges, primary, options) {
  5508. var this$1 = this;
  5509. if (!ranges.length) { return }
  5510. var out = []
  5511. for (var i = 0; i < ranges.length; i++)
  5512. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5513. clipPos(this$1, ranges[i].head)) }
  5514. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5515. setSelection(this, normalizeSelection(out, primary), options)
  5516. }),
  5517. addSelection: docMethodOp(function(anchor, head, options) {
  5518. var ranges = this.sel.ranges.slice(0)
  5519. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5520. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5521. }),
  5522. getSelection: function(lineSep) {
  5523. var this$1 = this;
  5524. var ranges = this.sel.ranges, lines
  5525. for (var i = 0; i < ranges.length; i++) {
  5526. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5527. lines = lines ? lines.concat(sel) : sel
  5528. }
  5529. if (lineSep === false) { return lines }
  5530. else { return lines.join(lineSep || this.lineSeparator()) }
  5531. },
  5532. getSelections: function(lineSep) {
  5533. var this$1 = this;
  5534. var parts = [], ranges = this.sel.ranges
  5535. for (var i = 0; i < ranges.length; i++) {
  5536. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5537. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5538. parts[i] = sel
  5539. }
  5540. return parts
  5541. },
  5542. replaceSelection: function(code, collapse, origin) {
  5543. var dup = []
  5544. for (var i = 0; i < this.sel.ranges.length; i++)
  5545. { dup[i] = code }
  5546. this.replaceSelections(dup, collapse, origin || "+input")
  5547. },
  5548. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5549. var this$1 = this;
  5550. var changes = [], sel = this.sel
  5551. for (var i = 0; i < sel.ranges.length; i++) {
  5552. var range = sel.ranges[i]
  5553. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5554. }
  5555. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5556. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5557. { makeChange(this$1, changes[i$1]) }
  5558. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5559. else if (this.cm) { ensureCursorVisible(this.cm) }
  5560. }),
  5561. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5562. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5563. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5564. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5565. setExtending: function(val) {this.extend = val},
  5566. getExtending: function() {return this.extend},
  5567. historySize: function() {
  5568. var hist = this.history, done = 0, undone = 0
  5569. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5570. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5571. return {undo: done, redo: undone}
  5572. },
  5573. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5574. markClean: function() {
  5575. this.cleanGeneration = this.changeGeneration(true)
  5576. },
  5577. changeGeneration: function(forceSplit) {
  5578. if (forceSplit)
  5579. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5580. return this.history.generation
  5581. },
  5582. isClean: function (gen) {
  5583. return this.history.generation == (gen || this.cleanGeneration)
  5584. },
  5585. getHistory: function() {
  5586. return {done: copyHistoryArray(this.history.done),
  5587. undone: copyHistoryArray(this.history.undone)}
  5588. },
  5589. setHistory: function(histData) {
  5590. var hist = this.history = new History(this.history.maxGeneration)
  5591. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5592. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5593. },
  5594. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5595. return changeLine(this, line, "gutter", function (line) {
  5596. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5597. markers[gutterID] = value
  5598. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5599. return true
  5600. })
  5601. }),
  5602. clearGutter: docMethodOp(function(gutterID) {
  5603. var this$1 = this;
  5604. this.iter(function (line) {
  5605. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5606. changeLine(this$1, line, "gutter", function () {
  5607. line.gutterMarkers[gutterID] = null
  5608. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5609. return true
  5610. })
  5611. }
  5612. })
  5613. }),
  5614. lineInfo: function(line) {
  5615. var n
  5616. if (typeof line == "number") {
  5617. if (!isLine(this, line)) { return null }
  5618. n = line
  5619. line = getLine(this, line)
  5620. if (!line) { return null }
  5621. } else {
  5622. n = lineNo(line)
  5623. if (n == null) { return null }
  5624. }
  5625. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5626. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5627. widgets: line.widgets}
  5628. },
  5629. addLineClass: docMethodOp(function(handle, where, cls) {
  5630. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5631. var prop = where == "text" ? "textClass"
  5632. : where == "background" ? "bgClass"
  5633. : where == "gutter" ? "gutterClass" : "wrapClass"
  5634. if (!line[prop]) { line[prop] = cls }
  5635. else if (classTest(cls).test(line[prop])) { return false }
  5636. else { line[prop] += " " + cls }
  5637. return true
  5638. })
  5639. }),
  5640. removeLineClass: docMethodOp(function(handle, where, cls) {
  5641. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5642. var prop = where == "text" ? "textClass"
  5643. : where == "background" ? "bgClass"
  5644. : where == "gutter" ? "gutterClass" : "wrapClass"
  5645. var cur = line[prop]
  5646. if (!cur) { return false }
  5647. else if (cls == null) { line[prop] = null }
  5648. else {
  5649. var found = cur.match(classTest(cls))
  5650. if (!found) { return false }
  5651. var end = found.index + found[0].length
  5652. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5653. }
  5654. return true
  5655. })
  5656. }),
  5657. addLineWidget: docMethodOp(function(handle, node, options) {
  5658. return addLineWidget(this, handle, node, options)
  5659. }),
  5660. removeLineWidget: function(widget) { widget.clear() },
  5661. markText: function(from, to, options) {
  5662. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5663. },
  5664. setBookmark: function(pos, options) {
  5665. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5666. insertLeft: options && options.insertLeft,
  5667. clearWhenEmpty: false, shared: options && options.shared,
  5668. handleMouseEvents: options && options.handleMouseEvents}
  5669. pos = clipPos(this, pos)
  5670. return markText(this, pos, pos, realOpts, "bookmark")
  5671. },
  5672. findMarksAt: function(pos) {
  5673. pos = clipPos(this, pos)
  5674. var markers = [], spans = getLine(this, pos.line).markedSpans
  5675. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5676. var span = spans[i]
  5677. if ((span.from == null || span.from <= pos.ch) &&
  5678. (span.to == null || span.to >= pos.ch))
  5679. { markers.push(span.marker.parent || span.marker) }
  5680. } }
  5681. return markers
  5682. },
  5683. findMarks: function(from, to, filter) {
  5684. from = clipPos(this, from); to = clipPos(this, to)
  5685. var found = [], lineNo = from.line
  5686. this.iter(from.line, to.line + 1, function (line) {
  5687. var spans = line.markedSpans
  5688. if (spans) { for (var i = 0; i < spans.length; i++) {
  5689. var span = spans[i]
  5690. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5691. span.from == null && lineNo != from.line ||
  5692. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5693. (!filter || filter(span.marker)))
  5694. { found.push(span.marker.parent || span.marker) }
  5695. } }
  5696. ++lineNo
  5697. })
  5698. return found
  5699. },
  5700. getAllMarks: function() {
  5701. var markers = []
  5702. this.iter(function (line) {
  5703. var sps = line.markedSpans
  5704. if (sps) { for (var i = 0; i < sps.length; ++i)
  5705. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5706. })
  5707. return markers
  5708. },
  5709. posFromIndex: function(off) {
  5710. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5711. this.iter(function (line) {
  5712. var sz = line.text.length + sepSize
  5713. if (sz > off) { ch = off; return true }
  5714. off -= sz
  5715. ++lineNo
  5716. })
  5717. return clipPos(this, Pos(lineNo, ch))
  5718. },
  5719. indexFromPos: function (coords) {
  5720. coords = clipPos(this, coords)
  5721. var index = coords.ch
  5722. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5723. var sepSize = this.lineSeparator().length
  5724. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5725. index += line.text.length + sepSize
  5726. })
  5727. return index
  5728. },
  5729. copy: function(copyHistory) {
  5730. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5731. this.modeOption, this.first, this.lineSep, this.direction)
  5732. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5733. doc.sel = this.sel
  5734. doc.extend = false
  5735. if (copyHistory) {
  5736. doc.history.undoDepth = this.history.undoDepth
  5737. doc.setHistory(this.getHistory())
  5738. }
  5739. return doc
  5740. },
  5741. linkedDoc: function(options) {
  5742. if (!options) { options = {} }
  5743. var from = this.first, to = this.first + this.size
  5744. if (options.from != null && options.from > from) { from = options.from }
  5745. if (options.to != null && options.to < to) { to = options.to }
  5746. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)
  5747. if (options.sharedHist) { copy.history = this.history
  5748. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5749. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5750. copySharedMarkers(copy, findSharedMarkers(this))
  5751. return copy
  5752. },
  5753. unlinkDoc: function(other) {
  5754. var this$1 = this;
  5755. if (other instanceof CodeMirror) { other = other.doc }
  5756. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5757. var link = this$1.linked[i]
  5758. if (link.doc != other) { continue }
  5759. this$1.linked.splice(i, 1)
  5760. other.unlinkDoc(this$1)
  5761. detachSharedMarkers(findSharedMarkers(this$1))
  5762. break
  5763. } }
  5764. // If the histories were shared, split them again
  5765. if (other.history == this.history) {
  5766. var splitIds = [other.id]
  5767. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5768. other.history = new History(null)
  5769. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5770. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5771. }
  5772. },
  5773. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5774. getMode: function() {return this.mode},
  5775. getEditor: function() {return this.cm},
  5776. splitLines: function(str) {
  5777. if (this.lineSep) { return str.split(this.lineSep) }
  5778. return splitLinesAuto(str)
  5779. },
  5780. lineSeparator: function() { return this.lineSep || "\n" },
  5781. setDirection: docMethodOp(function (dir) {
  5782. if (dir != "rtl") { dir = "ltr" }
  5783. if (dir == this.direction) { return }
  5784. this.direction = dir
  5785. this.iter(function (line) { return line.order = null; })
  5786. if (this.cm) { directionChanged(this.cm) }
  5787. })
  5788. })
  5789. // Public alias.
  5790. Doc.prototype.eachLine = Doc.prototype.iter
  5791. // Kludge to work around strange IE behavior where it'll sometimes
  5792. // re-fire a series of drag-related events right after the drop (#1551)
  5793. var lastDrop = 0
  5794. function onDrop(e) {
  5795. var cm = this
  5796. clearDragCursor(cm)
  5797. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5798. { return }
  5799. e_preventDefault(e)
  5800. if (ie) { lastDrop = +new Date }
  5801. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5802. if (!pos || cm.isReadOnly()) { return }
  5803. // Might be a file drop, in which case we simply extract the text
  5804. // and insert it.
  5805. if (files && files.length && window.FileReader && window.File) {
  5806. var n = files.length, text = Array(n), read = 0
  5807. var loadFile = function (file, i) {
  5808. if (cm.options.allowDropFileTypes &&
  5809. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5810. { return }
  5811. var reader = new FileReader
  5812. reader.onload = operation(cm, function () {
  5813. var content = reader.result
  5814. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5815. text[i] = content
  5816. if (++read == n) {
  5817. pos = clipPos(cm.doc, pos)
  5818. var change = {from: pos, to: pos,
  5819. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5820. origin: "paste"}
  5821. makeChange(cm.doc, change)
  5822. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5823. }
  5824. })
  5825. reader.readAsText(file)
  5826. }
  5827. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5828. } else { // Normal drop
  5829. // Don't do a replace if the drop happened inside of the selected text.
  5830. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5831. cm.state.draggingText(e)
  5832. // Ensure the editor is re-focused
  5833. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5834. return
  5835. }
  5836. try {
  5837. var text$1 = e.dataTransfer.getData("Text")
  5838. if (text$1) {
  5839. var selected
  5840. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5841. { selected = cm.listSelections() }
  5842. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5843. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5844. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5845. cm.replaceSelection(text$1, "around", "paste")
  5846. cm.display.input.focus()
  5847. }
  5848. }
  5849. catch(e){}
  5850. }
  5851. }
  5852. function onDragStart(cm, e) {
  5853. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5854. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5855. e.dataTransfer.setData("Text", cm.getSelection())
  5856. e.dataTransfer.effectAllowed = "copyMove"
  5857. // Use dummy image instead of default browsers image.
  5858. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5859. if (e.dataTransfer.setDragImage && !safari) {
  5860. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5861. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5862. if (presto) {
  5863. img.width = img.height = 1
  5864. cm.display.wrapper.appendChild(img)
  5865. // Force a relayout, or Opera won't use our image for some obscure reason
  5866. img._top = img.offsetTop
  5867. }
  5868. e.dataTransfer.setDragImage(img, 0, 0)
  5869. if (presto) { img.parentNode.removeChild(img) }
  5870. }
  5871. }
  5872. function onDragOver(cm, e) {
  5873. var pos = posFromMouse(cm, e)
  5874. if (!pos) { return }
  5875. var frag = document.createDocumentFragment()
  5876. drawSelectionCursor(cm, pos, frag)
  5877. if (!cm.display.dragCursor) {
  5878. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5879. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5880. }
  5881. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5882. }
  5883. function clearDragCursor(cm) {
  5884. if (cm.display.dragCursor) {
  5885. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5886. cm.display.dragCursor = null
  5887. }
  5888. }
  5889. // These must be handled carefully, because naively registering a
  5890. // handler for each editor will cause the editors to never be
  5891. // garbage collected.
  5892. function forEachCodeMirror(f) {
  5893. if (!document.getElementsByClassName) { return }
  5894. var byClass = document.getElementsByClassName("CodeMirror")
  5895. for (var i = 0; i < byClass.length; i++) {
  5896. var cm = byClass[i].CodeMirror
  5897. if (cm) { f(cm) }
  5898. }
  5899. }
  5900. var globalsRegistered = false
  5901. function ensureGlobalHandlers() {
  5902. if (globalsRegistered) { return }
  5903. registerGlobalHandlers()
  5904. globalsRegistered = true
  5905. }
  5906. function registerGlobalHandlers() {
  5907. // When the window resizes, we need to refresh active editors.
  5908. var resizeTimer
  5909. on(window, "resize", function () {
  5910. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5911. resizeTimer = null
  5912. forEachCodeMirror(onResize)
  5913. }, 100) }
  5914. })
  5915. // When the window loses focus, we want to show the editor as blurred
  5916. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5917. }
  5918. // Called when the window resizes
  5919. function onResize(cm) {
  5920. var d = cm.display
  5921. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5922. { return }
  5923. // Might be a text scaling operation, clear size caches.
  5924. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5925. d.scrollbarsClipped = false
  5926. cm.setSize()
  5927. }
  5928. var keyNames = {
  5929. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5930. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5931. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5932. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5933. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
  5934. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5935. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5936. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5937. }
  5938. // Number keys
  5939. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5940. // Alphabetic keys
  5941. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5942. // Function keys
  5943. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5944. var keyMap = {}
  5945. keyMap.basic = {
  5946. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5947. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5948. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5949. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5950. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5951. "Esc": "singleSelection"
  5952. }
  5953. // Note that the save and find-related commands aren't defined by
  5954. // default. User code or addons can define them. Unknown commands
  5955. // are simply ignored.
  5956. keyMap.pcDefault = {
  5957. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5958. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5959. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5960. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5961. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5962. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5963. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5964. fallthrough: "basic"
  5965. }
  5966. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5967. keyMap.emacsy = {
  5968. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5969. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5970. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5971. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5972. "Ctrl-O": "openLine"
  5973. }
  5974. keyMap.macDefault = {
  5975. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5976. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5977. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5978. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5979. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5980. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5981. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5982. fallthrough: ["basic", "emacsy"]
  5983. }
  5984. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5985. // KEYMAP DISPATCH
  5986. function normalizeKeyName(name) {
  5987. var parts = name.split(/-(?!$)/)
  5988. name = parts[parts.length - 1]
  5989. var alt, ctrl, shift, cmd
  5990. for (var i = 0; i < parts.length - 1; i++) {
  5991. var mod = parts[i]
  5992. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5993. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5994. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5995. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5996. else { throw new Error("Unrecognized modifier name: " + mod) }
  5997. }
  5998. if (alt) { name = "Alt-" + name }
  5999. if (ctrl) { name = "Ctrl-" + name }
  6000. if (cmd) { name = "Cmd-" + name }
  6001. if (shift) { name = "Shift-" + name }
  6002. return name
  6003. }
  6004. // This is a kludge to keep keymaps mostly working as raw objects
  6005. // (backwards compatibility) while at the same time support features
  6006. // like normalization and multi-stroke key bindings. It compiles a
  6007. // new normalized keymap, and then updates the old object to reflect
  6008. // this.
  6009. function normalizeKeyMap(keymap) {
  6010. var copy = {}
  6011. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6012. var value = keymap[keyname]
  6013. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6014. if (value == "...") { delete keymap[keyname]; continue }
  6015. var keys = map(keyname.split(" "), normalizeKeyName)
  6016. for (var i = 0; i < keys.length; i++) {
  6017. var val = (void 0), name = (void 0)
  6018. if (i == keys.length - 1) {
  6019. name = keys.join(" ")
  6020. val = value
  6021. } else {
  6022. name = keys.slice(0, i + 1).join(" ")
  6023. val = "..."
  6024. }
  6025. var prev = copy[name]
  6026. if (!prev) { copy[name] = val }
  6027. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6028. }
  6029. delete keymap[keyname]
  6030. } }
  6031. for (var prop in copy) { keymap[prop] = copy[prop] }
  6032. return keymap
  6033. }
  6034. function lookupKey(key, map, handle, context) {
  6035. map = getKeyMap(map)
  6036. var found = map.call ? map.call(key, context) : map[key]
  6037. if (found === false) { return "nothing" }
  6038. if (found === "...") { return "multi" }
  6039. if (found != null && handle(found)) { return "handled" }
  6040. if (map.fallthrough) {
  6041. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6042. { return lookupKey(key, map.fallthrough, handle, context) }
  6043. for (var i = 0; i < map.fallthrough.length; i++) {
  6044. var result = lookupKey(key, map.fallthrough[i], handle, context)
  6045. if (result) { return result }
  6046. }
  6047. }
  6048. }
  6049. // Modifier key presses don't count as 'real' key presses for the
  6050. // purpose of keymap fallthrough.
  6051. function isModifierKey(value) {
  6052. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  6053. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6054. }
  6055. function addModifierNames(name, event, noShift) {
  6056. var base = name
  6057. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  6058. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  6059. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  6060. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  6061. return name
  6062. }
  6063. // Look up the name of a key as indicated by an event object.
  6064. function keyName(event, noShift) {
  6065. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6066. var name = keyNames[event.keyCode]
  6067. if (name == null || event.altGraphKey) { return false }
  6068. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6069. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6070. if (event.keyCode == 3 && event.code) { name = event.code }
  6071. return addModifierNames(name, event, noShift)
  6072. }
  6073. function getKeyMap(val) {
  6074. return typeof val == "string" ? keyMap[val] : val
  6075. }
  6076. // Helper for deleting text near the selection(s), used to implement
  6077. // backspace, delete, and similar functionality.
  6078. function deleteNearSelection(cm, compute) {
  6079. var ranges = cm.doc.sel.ranges, kill = []
  6080. // Build up a set of ranges to kill first, merging overlapping
  6081. // ranges.
  6082. for (var i = 0; i < ranges.length; i++) {
  6083. var toKill = compute(ranges[i])
  6084. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6085. var replaced = kill.pop()
  6086. if (cmp(replaced.from, toKill.from) < 0) {
  6087. toKill.from = replaced.from
  6088. break
  6089. }
  6090. }
  6091. kill.push(toKill)
  6092. }
  6093. // Next, remove those actual ranges.
  6094. runInOp(cm, function () {
  6095. for (var i = kill.length - 1; i >= 0; i--)
  6096. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  6097. ensureCursorVisible(cm)
  6098. })
  6099. }
  6100. function moveCharLogically(line, ch, dir) {
  6101. var target = skipExtendingChars(line.text, ch + dir, dir)
  6102. return target < 0 || target > line.text.length ? null : target
  6103. }
  6104. function moveLogically(line, start, dir) {
  6105. var ch = moveCharLogically(line, start.ch, dir)
  6106. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6107. }
  6108. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6109. if (visually) {
  6110. var order = getOrder(lineObj, cm.doc.direction)
  6111. if (order) {
  6112. var part = dir < 0 ? lst(order) : order[0]
  6113. var moveInStorageOrder = (dir < 0) == (part.level == 1)
  6114. var sticky = moveInStorageOrder ? "after" : "before"
  6115. var ch
  6116. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6117. // it could be that the last bidi part is not on the last visual line,
  6118. // since visual lines contain content order-consecutive chunks.
  6119. // Thus, in rtl, we are looking for the first (content-order) character
  6120. // in the rtl chunk that is on the last line (that is, the same line
  6121. // as the last (content-order) character).
  6122. if (part.level > 0 || cm.doc.direction == "rtl") {
  6123. var prep = prepareMeasureForLine(cm, lineObj)
  6124. ch = dir < 0 ? lineObj.text.length - 1 : 0
  6125. var targetTop = measureCharPrepared(cm, prep, ch).top
  6126. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
  6127. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) }
  6128. } else { ch = dir < 0 ? part.to : part.from }
  6129. return new Pos(lineNo, ch, sticky)
  6130. }
  6131. }
  6132. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6133. }
  6134. function moveVisually(cm, line, start, dir) {
  6135. var bidi = getOrder(line, cm.doc.direction)
  6136. if (!bidi) { return moveLogically(line, start, dir) }
  6137. if (start.ch >= line.text.length) {
  6138. start.ch = line.text.length
  6139. start.sticky = "before"
  6140. } else if (start.ch <= 0) {
  6141. start.ch = 0
  6142. start.sticky = "after"
  6143. }
  6144. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
  6145. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6146. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6147. // nothing interesting happens.
  6148. return moveLogically(line, start, dir)
  6149. }
  6150. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
  6151. var prep
  6152. var getWrappedLineExtent = function (ch) {
  6153. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6154. prep = prep || prepareMeasureForLine(cm, line)
  6155. return wrappedLineExtentChar(cm, line, prep, ch)
  6156. }
  6157. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
  6158. if (cm.doc.direction == "rtl" || part.level == 1) {
  6159. var moveInStorageOrder = (part.level == 1) == (dir < 0)
  6160. var ch = mv(start, moveInStorageOrder ? 1 : -1)
  6161. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6162. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6163. var sticky = moveInStorageOrder ? "before" : "after"
  6164. return new Pos(start.line, ch, sticky)
  6165. }
  6166. }
  6167. // Case 3: Could not move within this bidi part in this visual line, so leave
  6168. // the current bidi part
  6169. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6170. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6171. ? new Pos(start.line, mv(ch, 1), "before")
  6172. : new Pos(start.line, ch, "after"); }
  6173. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6174. var part = bidi[partPos]
  6175. var moveInStorageOrder = (dir > 0) == (part.level != 1)
  6176. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  6177. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6178. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  6179. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6180. }
  6181. }
  6182. // Case 3a: Look for other bidi parts on the same visual line
  6183. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  6184. if (res) { return res }
  6185. // Case 3b: Look for other bidi parts on the next visual line
  6186. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  6187. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6188. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  6189. if (res) { return res }
  6190. }
  6191. // Case 4: Nowhere to move
  6192. return null
  6193. }
  6194. // Commands are parameter-less actions that can be performed on an
  6195. // editor, mostly used for keybindings.
  6196. var commands = {
  6197. selectAll: selectAll,
  6198. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6199. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6200. if (range.empty()) {
  6201. var len = getLine(cm.doc, range.head.line).text.length
  6202. if (range.head.ch == len && range.head.line < cm.lastLine())
  6203. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6204. else
  6205. { return {from: range.head, to: Pos(range.head.line, len)} }
  6206. } else {
  6207. return {from: range.from(), to: range.to()}
  6208. }
  6209. }); },
  6210. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6211. from: Pos(range.from().line, 0),
  6212. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6213. }); }); },
  6214. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6215. from: Pos(range.from().line, 0), to: range.from()
  6216. }); }); },
  6217. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6218. var top = cm.charCoords(range.head, "div").top + 5
  6219. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  6220. return {from: leftPos, to: range.from()}
  6221. }); },
  6222. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6223. var top = cm.charCoords(range.head, "div").top + 5
  6224. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6225. return {from: range.from(), to: rightPos }
  6226. }); },
  6227. undo: function (cm) { return cm.undo(); },
  6228. redo: function (cm) { return cm.redo(); },
  6229. undoSelection: function (cm) { return cm.undoSelection(); },
  6230. redoSelection: function (cm) { return cm.redoSelection(); },
  6231. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6232. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6233. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6234. {origin: "+move", bias: 1}
  6235. ); },
  6236. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6237. {origin: "+move", bias: 1}
  6238. ); },
  6239. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6240. {origin: "+move", bias: -1}
  6241. ); },
  6242. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6243. var top = cm.cursorCoords(range.head, "div").top + 5
  6244. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6245. }, sel_move); },
  6246. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6247. var top = cm.cursorCoords(range.head, "div").top + 5
  6248. return cm.coordsChar({left: 0, top: top}, "div")
  6249. }, sel_move); },
  6250. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6251. var top = cm.cursorCoords(range.head, "div").top + 5
  6252. var pos = cm.coordsChar({left: 0, top: top}, "div")
  6253. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6254. return pos
  6255. }, sel_move); },
  6256. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6257. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6258. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6259. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6260. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6261. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6262. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6263. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6264. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6265. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6266. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6267. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6268. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6269. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6270. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6271. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6272. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6273. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6274. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6275. indentMore: function (cm) { return cm.indentSelection("add"); },
  6276. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6277. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6278. insertSoftTab: function (cm) {
  6279. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  6280. for (var i = 0; i < ranges.length; i++) {
  6281. var pos = ranges[i].from()
  6282. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  6283. spaces.push(spaceStr(tabSize - col % tabSize))
  6284. }
  6285. cm.replaceSelections(spaces)
  6286. },
  6287. defaultTab: function (cm) {
  6288. if (cm.somethingSelected()) { cm.indentSelection("add") }
  6289. else { cm.execCommand("insertTab") }
  6290. },
  6291. // Swap the two chars left and right of each selection's head.
  6292. // Move cursor behind the two swapped characters afterwards.
  6293. //
  6294. // Doesn't consider line feeds a character.
  6295. // Doesn't scan more than one line above to find a character.
  6296. // Doesn't do anything on an empty line.
  6297. // Doesn't do anything with non-empty selections.
  6298. transposeChars: function (cm) { return runInOp(cm, function () {
  6299. var ranges = cm.listSelections(), newSel = []
  6300. for (var i = 0; i < ranges.length; i++) {
  6301. if (!ranges[i].empty()) { continue }
  6302. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  6303. if (line) {
  6304. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  6305. if (cur.ch > 0) {
  6306. cur = new Pos(cur.line, cur.ch + 1)
  6307. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6308. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  6309. } else if (cur.line > cm.doc.first) {
  6310. var prev = getLine(cm.doc, cur.line - 1).text
  6311. if (prev) {
  6312. cur = new Pos(cur.line, 1)
  6313. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6314. prev.charAt(prev.length - 1),
  6315. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  6316. }
  6317. }
  6318. }
  6319. newSel.push(new Range(cur, cur))
  6320. }
  6321. cm.setSelections(newSel)
  6322. }); },
  6323. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6324. var sels = cm.listSelections()
  6325. for (var i = sels.length - 1; i >= 0; i--)
  6326. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  6327. sels = cm.listSelections()
  6328. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6329. { cm.indentLine(sels[i$1].from().line, null, true) }
  6330. ensureCursorVisible(cm)
  6331. }); },
  6332. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6333. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6334. }
  6335. function lineStart(cm, lineN) {
  6336. var line = getLine(cm.doc, lineN)
  6337. var visual = visualLine(line)
  6338. if (visual != line) { lineN = lineNo(visual) }
  6339. return endOfLine(true, cm, visual, lineN, 1)
  6340. }
  6341. function lineEnd(cm, lineN) {
  6342. var line = getLine(cm.doc, lineN)
  6343. var visual = visualLineEnd(line)
  6344. if (visual != line) { lineN = lineNo(visual) }
  6345. return endOfLine(true, cm, line, lineN, -1)
  6346. }
  6347. function lineStartSmart(cm, pos) {
  6348. var start = lineStart(cm, pos.line)
  6349. var line = getLine(cm.doc, start.line)
  6350. var order = getOrder(line, cm.doc.direction)
  6351. if (!order || order[0].level == 0) {
  6352. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6353. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6354. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6355. }
  6356. return start
  6357. }
  6358. // Run a handler that was bound to a key.
  6359. function doHandleBinding(cm, bound, dropShift) {
  6360. if (typeof bound == "string") {
  6361. bound = commands[bound]
  6362. if (!bound) { return false }
  6363. }
  6364. // Ensure previous input has been read, so that the handler sees a
  6365. // consistent view of the document
  6366. cm.display.input.ensurePolled()
  6367. var prevShift = cm.display.shift, done = false
  6368. try {
  6369. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6370. if (dropShift) { cm.display.shift = false }
  6371. done = bound(cm) != Pass
  6372. } finally {
  6373. cm.display.shift = prevShift
  6374. cm.state.suppressEdits = false
  6375. }
  6376. return done
  6377. }
  6378. function lookupKeyForEditor(cm, name, handle) {
  6379. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6380. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6381. if (result) { return result }
  6382. }
  6383. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6384. || lookupKey(name, cm.options.keyMap, handle, cm)
  6385. }
  6386. // Note that, despite the name, this function is also used to check
  6387. // for bound mouse clicks.
  6388. var stopSeq = new Delayed
  6389. function dispatchKey(cm, name, e, handle) {
  6390. var seq = cm.state.keySeq
  6391. if (seq) {
  6392. if (isModifierKey(name)) { return "handled" }
  6393. if (/\'$/.test(name))
  6394. { cm.state.keySeq = null }
  6395. else
  6396. { stopSeq.set(50, function () {
  6397. if (cm.state.keySeq == seq) {
  6398. cm.state.keySeq = null
  6399. cm.display.input.reset()
  6400. }
  6401. }) }
  6402. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6403. }
  6404. return dispatchKeyInner(cm, name, e, handle)
  6405. }
  6406. function dispatchKeyInner(cm, name, e, handle) {
  6407. var result = lookupKeyForEditor(cm, name, handle)
  6408. if (result == "multi")
  6409. { cm.state.keySeq = name }
  6410. if (result == "handled")
  6411. { signalLater(cm, "keyHandled", cm, name, e) }
  6412. if (result == "handled" || result == "multi") {
  6413. e_preventDefault(e)
  6414. restartBlink(cm)
  6415. }
  6416. return !!result
  6417. }
  6418. // Handle a key from the keydown event.
  6419. function handleKeyBinding(cm, e) {
  6420. var name = keyName(e, true)
  6421. if (!name) { return false }
  6422. if (e.shiftKey && !cm.state.keySeq) {
  6423. // First try to resolve full name (including 'Shift-'). Failing
  6424. // that, see if there is a cursor-motion command (starting with
  6425. // 'go') bound to the keyname without 'Shift-'.
  6426. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6427. || dispatchKey(cm, name, e, function (b) {
  6428. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6429. { return doHandleBinding(cm, b) }
  6430. })
  6431. } else {
  6432. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6433. }
  6434. }
  6435. // Handle a key from the keypress event
  6436. function handleCharBinding(cm, e, ch) {
  6437. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6438. }
  6439. var lastStoppedKey = null
  6440. function onKeyDown(e) {
  6441. var cm = this
  6442. cm.curOp.focus = activeElt()
  6443. if (signalDOMEvent(cm, e)) { return }
  6444. // IE does strange things with escape.
  6445. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6446. var code = e.keyCode
  6447. cm.display.shift = code == 16 || e.shiftKey
  6448. var handled = handleKeyBinding(cm, e)
  6449. if (presto) {
  6450. lastStoppedKey = handled ? code : null
  6451. // Opera has no cut event... we try to at least catch the key combo
  6452. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6453. { cm.replaceSelection("", null, "cut") }
  6454. }
  6455. // Turn mouse into crosshair when Alt is held on Mac.
  6456. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6457. { showCrossHair(cm) }
  6458. }
  6459. function showCrossHair(cm) {
  6460. var lineDiv = cm.display.lineDiv
  6461. addClass(lineDiv, "CodeMirror-crosshair")
  6462. function up(e) {
  6463. if (e.keyCode == 18 || !e.altKey) {
  6464. rmClass(lineDiv, "CodeMirror-crosshair")
  6465. off(document, "keyup", up)
  6466. off(document, "mouseover", up)
  6467. }
  6468. }
  6469. on(document, "keyup", up)
  6470. on(document, "mouseover", up)
  6471. }
  6472. function onKeyUp(e) {
  6473. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6474. signalDOMEvent(this, e)
  6475. }
  6476. function onKeyPress(e) {
  6477. var cm = this
  6478. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6479. var keyCode = e.keyCode, charCode = e.charCode
  6480. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6481. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6482. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6483. // Some browsers fire keypress events for backspace
  6484. if (ch == "\x08") { return }
  6485. if (handleCharBinding(cm, e, ch)) { return }
  6486. cm.display.input.onKeyPress(e)
  6487. }
  6488. var DOUBLECLICK_DELAY = 400
  6489. var PastClick = function(time, pos, button) {
  6490. this.time = time
  6491. this.pos = pos
  6492. this.button = button
  6493. };
  6494. PastClick.prototype.compare = function (time, pos, button) {
  6495. return this.time + DOUBLECLICK_DELAY > time &&
  6496. cmp(pos, this.pos) == 0 && button == this.button
  6497. };
  6498. var lastClick;
  6499. var lastDoubleClick;
  6500. function clickRepeat(pos, button) {
  6501. var now = +new Date
  6502. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6503. lastClick = lastDoubleClick = null
  6504. return "triple"
  6505. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6506. lastDoubleClick = new PastClick(now, pos, button)
  6507. lastClick = null
  6508. return "double"
  6509. } else {
  6510. lastClick = new PastClick(now, pos, button)
  6511. lastDoubleClick = null
  6512. return "single"
  6513. }
  6514. }
  6515. // A mouse down can be a single click, double click, triple click,
  6516. // start of selection drag, start of text drag, new cursor
  6517. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6518. // middle-click-paste. Or it might be a click on something we should
  6519. // not interfere with, such as a scrollbar or widget.
  6520. function onMouseDown(e) {
  6521. var cm = this, display = cm.display
  6522. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6523. display.input.ensurePolled()
  6524. display.shift = e.shiftKey
  6525. if (eventInWidget(display, e)) {
  6526. if (!webkit) {
  6527. // Briefly turn off draggability, to allow widgets to do
  6528. // normal dragging things.
  6529. display.scroller.draggable = false
  6530. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6531. }
  6532. return
  6533. }
  6534. if (clickInGutter(cm, e)) { return }
  6535. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"
  6536. window.focus()
  6537. // #3261: make sure, that we're not starting a second selection
  6538. if (button == 1 && cm.state.selectingText)
  6539. { cm.state.selectingText(e) }
  6540. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6541. if (button == 1) {
  6542. if (pos) { leftButtonDown(cm, pos, repeat, e) }
  6543. else if (e_target(e) == display.scroller) { e_preventDefault(e) }
  6544. } else if (button == 2) {
  6545. if (pos) { extendSelection(cm.doc, pos) }
  6546. setTimeout(function () { return display.input.focus(); }, 20)
  6547. } else if (button == 3) {
  6548. if (captureRightClick) { onContextMenu(cm, e) }
  6549. else { delayBlurEvent(cm) }
  6550. }
  6551. }
  6552. function handleMappedButton(cm, button, pos, repeat, event) {
  6553. var name = "Click"
  6554. if (repeat == "double") { name = "Double" + name }
  6555. else if (repeat == "triple") { name = "Triple" + name }
  6556. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name
  6557. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6558. if (typeof bound == "string") { bound = commands[bound] }
  6559. if (!bound) { return false }
  6560. var done = false
  6561. try {
  6562. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6563. done = bound(cm, pos) != Pass
  6564. } finally {
  6565. cm.state.suppressEdits = false
  6566. }
  6567. return done
  6568. })
  6569. }
  6570. function configureMouse(cm, repeat, event) {
  6571. var option = cm.getOption("configureMouse")
  6572. var value = option ? option(cm, repeat, event) : {}
  6573. if (value.unit == null) {
  6574. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  6575. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"
  6576. }
  6577. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey }
  6578. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey }
  6579. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) }
  6580. return value
  6581. }
  6582. function leftButtonDown(cm, pos, repeat, event) {
  6583. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6584. else { cm.curOp.focus = activeElt() }
  6585. var behavior = configureMouse(cm, repeat, event)
  6586. var sel = cm.doc.sel, contained
  6587. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6588. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6589. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6590. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6591. { leftButtonStartDrag(cm, event, pos, behavior) }
  6592. else
  6593. { leftButtonSelect(cm, event, pos, behavior) }
  6594. }
  6595. // Start a text drag. When it ends, see if any dragging actually
  6596. // happen, and treat as a click if it didn't.
  6597. function leftButtonStartDrag(cm, event, pos, behavior) {
  6598. var display = cm.display, moved = false
  6599. var dragEnd = operation(cm, function (e) {
  6600. if (webkit) { display.scroller.draggable = false }
  6601. cm.state.draggingText = false
  6602. off(display.wrapper.ownerDocument, "mouseup", dragEnd)
  6603. off(display.wrapper.ownerDocument, "mousemove", mouseMove)
  6604. off(display.scroller, "dragstart", dragStart)
  6605. off(display.scroller, "drop", dragEnd)
  6606. if (!moved) {
  6607. e_preventDefault(e)
  6608. if (!behavior.addNew)
  6609. { extendSelection(cm.doc, pos, null, null, behavior.extend) }
  6610. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6611. if (webkit || ie && ie_version == 9)
  6612. { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20) }
  6613. else
  6614. { display.input.focus() }
  6615. }
  6616. })
  6617. var mouseMove = function(e2) {
  6618. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  6619. }
  6620. var dragStart = function () { return moved = true; }
  6621. // Let the drag handler handle this.
  6622. if (webkit) { display.scroller.draggable = true }
  6623. cm.state.draggingText = dragEnd
  6624. dragEnd.copy = !behavior.moveOnDrag
  6625. // IE's approach to draggable
  6626. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6627. on(display.wrapper.ownerDocument, "mouseup", dragEnd)
  6628. on(display.wrapper.ownerDocument, "mousemove", mouseMove)
  6629. on(display.scroller, "dragstart", dragStart)
  6630. on(display.scroller, "drop", dragEnd)
  6631. delayBlurEvent(cm)
  6632. setTimeout(function () { return display.input.focus(); }, 20)
  6633. }
  6634. function rangeForUnit(cm, pos, unit) {
  6635. if (unit == "char") { return new Range(pos, pos) }
  6636. if (unit == "word") { return cm.findWordAt(pos) }
  6637. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6638. var result = unit(cm, pos)
  6639. return new Range(result.from, result.to)
  6640. }
  6641. // Normal selection, as opposed to text dragging.
  6642. function leftButtonSelect(cm, event, start, behavior) {
  6643. var display = cm.display, doc = cm.doc
  6644. e_preventDefault(event)
  6645. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6646. if (behavior.addNew && !behavior.extend) {
  6647. ourIndex = doc.sel.contains(start)
  6648. if (ourIndex > -1)
  6649. { ourRange = ranges[ourIndex] }
  6650. else
  6651. { ourRange = new Range(start, start) }
  6652. } else {
  6653. ourRange = doc.sel.primary()
  6654. ourIndex = doc.sel.primIndex
  6655. }
  6656. if (behavior.unit == "rectangle") {
  6657. if (!behavior.addNew) { ourRange = new Range(start, start) }
  6658. start = posFromMouse(cm, event, true, true)
  6659. ourIndex = -1
  6660. } else {
  6661. var range = rangeForUnit(cm, start, behavior.unit)
  6662. if (behavior.extend)
  6663. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) }
  6664. else
  6665. { ourRange = range }
  6666. }
  6667. if (!behavior.addNew) {
  6668. ourIndex = 0
  6669. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6670. startSel = doc.sel
  6671. } else if (ourIndex == -1) {
  6672. ourIndex = ranges.length
  6673. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6674. {scroll: false, origin: "*mouse"})
  6675. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6676. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6677. {scroll: false, origin: "*mouse"})
  6678. startSel = doc.sel
  6679. } else {
  6680. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6681. }
  6682. var lastPos = start
  6683. function extendTo(pos) {
  6684. if (cmp(lastPos, pos) == 0) { return }
  6685. lastPos = pos
  6686. if (behavior.unit == "rectangle") {
  6687. var ranges = [], tabSize = cm.options.tabSize
  6688. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6689. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6690. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6691. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6692. line <= end; line++) {
  6693. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6694. if (left == right)
  6695. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6696. else if (text.length > leftPos)
  6697. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6698. }
  6699. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6700. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6701. {origin: "*mouse", scroll: false})
  6702. cm.scrollIntoView(pos)
  6703. } else {
  6704. var oldRange = ourRange
  6705. var range = rangeForUnit(cm, pos, behavior.unit)
  6706. var anchor = oldRange.anchor, head
  6707. if (cmp(range.anchor, anchor) > 0) {
  6708. head = range.head
  6709. anchor = minPos(oldRange.from(), range.anchor)
  6710. } else {
  6711. head = range.anchor
  6712. anchor = maxPos(oldRange.to(), range.head)
  6713. }
  6714. var ranges$1 = startSel.ranges.slice(0)
  6715. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))
  6716. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6717. }
  6718. }
  6719. var editorSize = display.wrapper.getBoundingClientRect()
  6720. // Used to ensure timeout re-tries don't fire when another extend
  6721. // happened in the meantime (clearTimeout isn't reliable -- at
  6722. // least on Chrome, the timeouts still happen even when cleared,
  6723. // if the clear happens after their scheduled firing time).
  6724. var counter = 0
  6725. function extend(e) {
  6726. var curCount = ++counter
  6727. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle")
  6728. if (!cur) { return }
  6729. if (cmp(cur, lastPos) != 0) {
  6730. cm.curOp.focus = activeElt()
  6731. extendTo(cur)
  6732. var visible = visibleLines(display, doc)
  6733. if (cur.line >= visible.to || cur.line < visible.from)
  6734. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6735. } else {
  6736. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6737. if (outside) { setTimeout(operation(cm, function () {
  6738. if (counter != curCount) { return }
  6739. display.scroller.scrollTop += outside
  6740. extend(e)
  6741. }), 50) }
  6742. }
  6743. }
  6744. function done(e) {
  6745. cm.state.selectingText = false
  6746. counter = Infinity
  6747. e_preventDefault(e)
  6748. display.input.focus()
  6749. off(display.wrapper.ownerDocument, "mousemove", move)
  6750. off(display.wrapper.ownerDocument, "mouseup", up)
  6751. doc.history.lastSelOrigin = null
  6752. }
  6753. var move = operation(cm, function (e) {
  6754. if (!e_button(e)) { done(e) }
  6755. else { extend(e) }
  6756. })
  6757. var up = operation(cm, done)
  6758. cm.state.selectingText = up
  6759. on(display.wrapper.ownerDocument, "mousemove", move)
  6760. on(display.wrapper.ownerDocument, "mouseup", up)
  6761. }
  6762. // Used when mouse-selecting to adjust the anchor to the proper side
  6763. // of a bidi jump depending on the visual position of the head.
  6764. function bidiSimplify(cm, range) {
  6765. var anchor = range.anchor;
  6766. var head = range.head;
  6767. var anchorLine = getLine(cm.doc, anchor.line)
  6768. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6769. var order = getOrder(anchorLine)
  6770. if (!order) { return range }
  6771. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]
  6772. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6773. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)
  6774. if (boundary == 0 || boundary == order.length) { return range }
  6775. // Compute the relative visual position of the head compared to the
  6776. // anchor (<0 is to the left, >0 to the right)
  6777. var leftSide
  6778. if (head.line != anchor.line) {
  6779. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0
  6780. } else {
  6781. var headIndex = getBidiPartAt(order, head.ch, head.sticky)
  6782. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)
  6783. if (headIndex == boundary - 1 || headIndex == boundary)
  6784. { leftSide = dir < 0 }
  6785. else
  6786. { leftSide = dir > 0 }
  6787. }
  6788. var usePart = order[boundary + (leftSide ? -1 : 0)]
  6789. var from = leftSide == (usePart.level == 1)
  6790. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"
  6791. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6792. }
  6793. // Determines whether an event happened in the gutter, and fires the
  6794. // handlers for the corresponding event.
  6795. function gutterEvent(cm, e, type, prevent) {
  6796. var mX, mY
  6797. if (e.touches) {
  6798. mX = e.touches[0].clientX
  6799. mY = e.touches[0].clientY
  6800. } else {
  6801. try { mX = e.clientX; mY = e.clientY }
  6802. catch(e) { return false }
  6803. }
  6804. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6805. if (prevent) { e_preventDefault(e) }
  6806. var display = cm.display
  6807. var lineBox = display.lineDiv.getBoundingClientRect()
  6808. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6809. mY -= lineBox.top - display.viewOffset
  6810. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6811. var g = display.gutters.childNodes[i]
  6812. if (g && g.getBoundingClientRect().right >= mX) {
  6813. var line = lineAtHeight(cm.doc, mY)
  6814. var gutter = cm.options.gutters[i]
  6815. signal(cm, type, cm, line, gutter, e)
  6816. return e_defaultPrevented(e)
  6817. }
  6818. }
  6819. }
  6820. function clickInGutter(cm, e) {
  6821. return gutterEvent(cm, e, "gutterClick", true)
  6822. }
  6823. // CONTEXT MENU HANDLING
  6824. // To make the context menu work, we need to briefly unhide the
  6825. // textarea (making it as unobtrusive as possible) to let the
  6826. // right-click take effect on it.
  6827. function onContextMenu(cm, e) {
  6828. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6829. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6830. cm.display.input.onContextMenu(e)
  6831. }
  6832. function contextMenuInGutter(cm, e) {
  6833. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6834. return gutterEvent(cm, e, "gutterContextMenu", false)
  6835. }
  6836. function themeChanged(cm) {
  6837. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6838. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6839. clearCaches(cm)
  6840. }
  6841. var Init = {toString: function(){return "CodeMirror.Init"}}
  6842. var defaults = {}
  6843. var optionHandlers = {}
  6844. function defineOptions(CodeMirror) {
  6845. var optionHandlers = CodeMirror.optionHandlers
  6846. function option(name, deflt, handle, notOnInit) {
  6847. CodeMirror.defaults[name] = deflt
  6848. if (handle) { optionHandlers[name] =
  6849. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6850. }
  6851. CodeMirror.defineOption = option
  6852. // Passed to option handlers when there is no old value.
  6853. CodeMirror.Init = Init
  6854. // These two are, on init, called from the constructor because they
  6855. // have to be initialized before the editor can start at all.
  6856. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6857. option("mode", null, function (cm, val) {
  6858. cm.doc.modeOption = val
  6859. loadMode(cm)
  6860. }, true)
  6861. option("indentUnit", 2, loadMode, true)
  6862. option("indentWithTabs", false)
  6863. option("smartIndent", true)
  6864. option("tabSize", 4, function (cm) {
  6865. resetModeState(cm)
  6866. clearCaches(cm)
  6867. regChange(cm)
  6868. }, true)
  6869. option("lineSeparator", null, function (cm, val) {
  6870. cm.doc.lineSep = val
  6871. if (!val) { return }
  6872. var newBreaks = [], lineNo = cm.doc.first
  6873. cm.doc.iter(function (line) {
  6874. for (var pos = 0;;) {
  6875. var found = line.text.indexOf(val, pos)
  6876. if (found == -1) { break }
  6877. pos = found + val.length
  6878. newBreaks.push(Pos(lineNo, found))
  6879. }
  6880. lineNo++
  6881. })
  6882. for (var i = newBreaks.length - 1; i >= 0; i--)
  6883. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6884. })
  6885. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6886. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6887. if (old != Init) { cm.refresh() }
  6888. })
  6889. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6890. option("electricChars", true)
  6891. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6892. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6893. }, true)
  6894. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6895. option("rtlMoveVisually", !windows)
  6896. option("wholeLineUpdateBefore", true)
  6897. option("theme", "default", function (cm) {
  6898. themeChanged(cm)
  6899. guttersChanged(cm)
  6900. }, true)
  6901. option("keyMap", "default", function (cm, val, old) {
  6902. var next = getKeyMap(val)
  6903. var prev = old != Init && getKeyMap(old)
  6904. if (prev && prev.detach) { prev.detach(cm, next) }
  6905. if (next.attach) { next.attach(cm, prev || null) }
  6906. })
  6907. option("extraKeys", null)
  6908. option("configureMouse", null)
  6909. option("lineWrapping", false, wrappingChanged, true)
  6910. option("gutters", [], function (cm) {
  6911. setGuttersForLineNumbers(cm.options)
  6912. guttersChanged(cm)
  6913. }, true)
  6914. option("fixedGutter", true, function (cm, val) {
  6915. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6916. cm.refresh()
  6917. }, true)
  6918. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6919. option("scrollbarStyle", "native", function (cm) {
  6920. initScrollbars(cm)
  6921. updateScrollbars(cm)
  6922. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6923. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6924. }, true)
  6925. option("lineNumbers", false, function (cm) {
  6926. setGuttersForLineNumbers(cm.options)
  6927. guttersChanged(cm)
  6928. }, true)
  6929. option("firstLineNumber", 1, guttersChanged, true)
  6930. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6931. option("showCursorWhenSelecting", false, updateSelection, true)
  6932. option("resetSelectionOnContextMenu", true)
  6933. option("lineWiseCopyCut", true)
  6934. option("pasteLinesPerSelection", true)
  6935. option("readOnly", false, function (cm, val) {
  6936. if (val == "nocursor") {
  6937. onBlur(cm)
  6938. cm.display.input.blur()
  6939. }
  6940. cm.display.input.readOnlyChanged(val)
  6941. })
  6942. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6943. option("dragDrop", true, dragDropChanged)
  6944. option("allowDropFileTypes", null)
  6945. option("cursorBlinkRate", 530)
  6946. option("cursorScrollMargin", 0)
  6947. option("cursorHeight", 1, updateSelection, true)
  6948. option("singleCursorHeightPerLine", true, updateSelection, true)
  6949. option("workTime", 100)
  6950. option("workDelay", 100)
  6951. option("flattenSpans", true, resetModeState, true)
  6952. option("addModeClass", false, resetModeState, true)
  6953. option("pollInterval", 100)
  6954. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6955. option("historyEventDelay", 1250)
  6956. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6957. option("maxHighlightLength", 10000, resetModeState, true)
  6958. option("moveInputWithCursor", true, function (cm, val) {
  6959. if (!val) { cm.display.input.resetPosition() }
  6960. })
  6961. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6962. option("autofocus", null)
  6963. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true)
  6964. }
  6965. function guttersChanged(cm) {
  6966. updateGutters(cm)
  6967. regChange(cm)
  6968. alignHorizontally(cm)
  6969. }
  6970. function dragDropChanged(cm, value, old) {
  6971. var wasOn = old && old != Init
  6972. if (!value != !wasOn) {
  6973. var funcs = cm.display.dragFunctions
  6974. var toggle = value ? on : off
  6975. toggle(cm.display.scroller, "dragstart", funcs.start)
  6976. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6977. toggle(cm.display.scroller, "dragover", funcs.over)
  6978. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6979. toggle(cm.display.scroller, "drop", funcs.drop)
  6980. }
  6981. }
  6982. function wrappingChanged(cm) {
  6983. if (cm.options.lineWrapping) {
  6984. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6985. cm.display.sizer.style.minWidth = ""
  6986. cm.display.sizerWidth = null
  6987. } else {
  6988. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6989. findMaxLine(cm)
  6990. }
  6991. estimateLineHeights(cm)
  6992. regChange(cm)
  6993. clearCaches(cm)
  6994. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6995. }
  6996. // A CodeMirror instance represents an editor. This is the object
  6997. // that user code is usually dealing with.
  6998. function CodeMirror(place, options) {
  6999. var this$1 = this;
  7000. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7001. this.options = options = options ? copyObj(options) : {}
  7002. // Determine effective options based on given values and defaults.
  7003. copyObj(defaults, options, false)
  7004. setGuttersForLineNumbers(options)
  7005. var doc = options.value
  7006. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) }
  7007. this.doc = doc
  7008. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  7009. var display = this.display = new Display(place, doc, input)
  7010. display.wrapper.CodeMirror = this
  7011. updateGutters(this)
  7012. themeChanged(this)
  7013. if (options.lineWrapping)
  7014. { this.display.wrapper.className += " CodeMirror-wrap" }
  7015. initScrollbars(this)
  7016. this.state = {
  7017. keyMaps: [], // stores maps added by addKeyMap
  7018. overlays: [], // highlighting overlays, as added by addOverlay
  7019. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7020. overwrite: false,
  7021. delayingBlurEvent: false,
  7022. focused: false,
  7023. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7024. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  7025. selectingText: false,
  7026. draggingText: false,
  7027. highlight: new Delayed(), // stores highlight worker timeout
  7028. keySeq: null, // Unfinished key sequence
  7029. specialChars: null
  7030. }
  7031. if (options.autofocus && !mobile) { display.input.focus() }
  7032. // Override magic textarea content restore that IE sometimes does
  7033. // on our hidden textarea on reload
  7034. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  7035. registerEventHandlers(this)
  7036. ensureGlobalHandlers()
  7037. startOperation(this)
  7038. this.curOp.forceUpdate = true
  7039. attachDoc(this, doc)
  7040. if ((options.autofocus && !mobile) || this.hasFocus())
  7041. { setTimeout(bind(onFocus, this), 20) }
  7042. else
  7043. { onBlur(this) }
  7044. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7045. { optionHandlers[opt](this$1, options[opt], Init) } }
  7046. maybeUpdateLineNumberWidth(this)
  7047. if (options.finishInit) { options.finishInit(this) }
  7048. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  7049. endOperation(this)
  7050. // Suppress optimizelegibility in Webkit, since it breaks text
  7051. // measuring on line wrapping boundaries.
  7052. if (webkit && options.lineWrapping &&
  7053. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7054. { display.lineDiv.style.textRendering = "auto" }
  7055. }
  7056. // The default configuration options.
  7057. CodeMirror.defaults = defaults
  7058. // Functions to run when options are changed.
  7059. CodeMirror.optionHandlers = optionHandlers
  7060. // Attach the necessary event handlers when initializing the editor
  7061. function registerEventHandlers(cm) {
  7062. var d = cm.display
  7063. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  7064. // Older IE's will not fire a second mousedown for a double click
  7065. if (ie && ie_version < 11)
  7066. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7067. if (signalDOMEvent(cm, e)) { return }
  7068. var pos = posFromMouse(cm, e)
  7069. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7070. e_preventDefault(e)
  7071. var word = cm.findWordAt(pos)
  7072. extendSelection(cm.doc, word.anchor, word.head)
  7073. })) }
  7074. else
  7075. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  7076. // Some browsers fire contextmenu *after* opening the menu, at
  7077. // which point we can't mess with it anymore. Context menu is
  7078. // handled in onMouseDown for these browsers.
  7079. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  7080. // Used to suppress mouse event handling when a touch happens
  7081. var touchFinished, prevTouch = {end: 0}
  7082. function finishTouch() {
  7083. if (d.activeTouch) {
  7084. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  7085. prevTouch = d.activeTouch
  7086. prevTouch.end = +new Date
  7087. }
  7088. }
  7089. function isMouseLikeTouchEvent(e) {
  7090. if (e.touches.length != 1) { return false }
  7091. var touch = e.touches[0]
  7092. return touch.radiusX <= 1 && touch.radiusY <= 1
  7093. }
  7094. function farAway(touch, other) {
  7095. if (other.left == null) { return true }
  7096. var dx = other.left - touch.left, dy = other.top - touch.top
  7097. return dx * dx + dy * dy > 20 * 20
  7098. }
  7099. on(d.scroller, "touchstart", function (e) {
  7100. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7101. d.input.ensurePolled()
  7102. clearTimeout(touchFinished)
  7103. var now = +new Date
  7104. d.activeTouch = {start: now, moved: false,
  7105. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  7106. if (e.touches.length == 1) {
  7107. d.activeTouch.left = e.touches[0].pageX
  7108. d.activeTouch.top = e.touches[0].pageY
  7109. }
  7110. }
  7111. })
  7112. on(d.scroller, "touchmove", function () {
  7113. if (d.activeTouch) { d.activeTouch.moved = true }
  7114. })
  7115. on(d.scroller, "touchend", function (e) {
  7116. var touch = d.activeTouch
  7117. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7118. !touch.moved && new Date - touch.start < 300) {
  7119. var pos = cm.coordsChar(d.activeTouch, "page"), range
  7120. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7121. { range = new Range(pos, pos) }
  7122. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7123. { range = cm.findWordAt(pos) }
  7124. else // Triple tap
  7125. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  7126. cm.setSelection(range.anchor, range.head)
  7127. cm.focus()
  7128. e_preventDefault(e)
  7129. }
  7130. finishTouch()
  7131. })
  7132. on(d.scroller, "touchcancel", finishTouch)
  7133. // Sync scrolling between fake scrollbars and real scrollable
  7134. // area, ensure viewport is updated when scrolling.
  7135. on(d.scroller, "scroll", function () {
  7136. if (d.scroller.clientHeight) {
  7137. updateScrollTop(cm, d.scroller.scrollTop)
  7138. setScrollLeft(cm, d.scroller.scrollLeft, true)
  7139. signal(cm, "scroll", cm)
  7140. }
  7141. })
  7142. // Listen to wheel events in order to try and update the viewport on time.
  7143. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  7144. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  7145. // Prevent wrapper from ever scrolling
  7146. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  7147. d.dragFunctions = {
  7148. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  7149. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  7150. start: function (e) { return onDragStart(cm, e); },
  7151. drop: operation(cm, onDrop),
  7152. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  7153. }
  7154. var inp = d.input.getField()
  7155. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  7156. on(inp, "keydown", operation(cm, onKeyDown))
  7157. on(inp, "keypress", operation(cm, onKeyPress))
  7158. on(inp, "focus", function (e) { return onFocus(cm, e); })
  7159. on(inp, "blur", function (e) { return onBlur(cm, e); })
  7160. }
  7161. var initHooks = []
  7162. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  7163. // Indent the given line. The how parameter can be "smart",
  7164. // "add"/null, "subtract", or "prev". When aggressive is false
  7165. // (typically set to true for forced single-line indents), empty
  7166. // lines are not indented, and places where the mode returns Pass
  7167. // are left alone.
  7168. function indentLine(cm, n, how, aggressive) {
  7169. var doc = cm.doc, state
  7170. if (how == null) { how = "add" }
  7171. if (how == "smart") {
  7172. // Fall back to "prev" when the mode doesn't have an indentation
  7173. // method.
  7174. if (!doc.mode.indent) { how = "prev" }
  7175. else { state = getContextBefore(cm, n).state }
  7176. }
  7177. var tabSize = cm.options.tabSize
  7178. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  7179. if (line.stateAfter) { line.stateAfter = null }
  7180. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  7181. if (!aggressive && !/\S/.test(line.text)) {
  7182. indentation = 0
  7183. how = "not"
  7184. } else if (how == "smart") {
  7185. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  7186. if (indentation == Pass || indentation > 150) {
  7187. if (!aggressive) { return }
  7188. how = "prev"
  7189. }
  7190. }
  7191. if (how == "prev") {
  7192. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  7193. else { indentation = 0 }
  7194. } else if (how == "add") {
  7195. indentation = curSpace + cm.options.indentUnit
  7196. } else if (how == "subtract") {
  7197. indentation = curSpace - cm.options.indentUnit
  7198. } else if (typeof how == "number") {
  7199. indentation = curSpace + how
  7200. }
  7201. indentation = Math.max(0, indentation)
  7202. var indentString = "", pos = 0
  7203. if (cm.options.indentWithTabs)
  7204. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  7205. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  7206. if (indentString != curSpaceString) {
  7207. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  7208. line.stateAfter = null
  7209. return true
  7210. } else {
  7211. // Ensure that, if the cursor was in the whitespace at the start
  7212. // of the line, it is moved to the end of that space.
  7213. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7214. var range = doc.sel.ranges[i$1]
  7215. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7216. var pos$1 = Pos(n, curSpaceString.length)
  7217. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  7218. break
  7219. }
  7220. }
  7221. }
  7222. }
  7223. // This will be set to a {lineWise: bool, text: [string]} object, so
  7224. // that, when pasting, we know what kind of selections the copied
  7225. // text was made out of.
  7226. var lastCopied = null
  7227. function setLastCopied(newLastCopied) {
  7228. lastCopied = newLastCopied
  7229. }
  7230. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7231. var doc = cm.doc
  7232. cm.display.shift = false
  7233. if (!sel) { sel = doc.sel }
  7234. var paste = cm.state.pasteIncoming || origin == "paste"
  7235. var textLines = splitLinesAuto(inserted), multiPaste = null
  7236. // When pasting N lines into N selections, insert one line per selection
  7237. if (paste && sel.ranges.length > 1) {
  7238. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7239. if (sel.ranges.length % lastCopied.text.length == 0) {
  7240. multiPaste = []
  7241. for (var i = 0; i < lastCopied.text.length; i++)
  7242. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  7243. }
  7244. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7245. multiPaste = map(textLines, function (l) { return [l]; })
  7246. }
  7247. }
  7248. var updateInput
  7249. // Normal behavior is to insert the new text into every selection
  7250. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7251. var range = sel.ranges[i$1]
  7252. var from = range.from(), to = range.to()
  7253. if (range.empty()) {
  7254. if (deleted && deleted > 0) // Handle deletion
  7255. { from = Pos(from.line, from.ch - deleted) }
  7256. else if (cm.state.overwrite && !paste) // Handle overwrite
  7257. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  7258. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7259. { from = to = Pos(from.line, 0) }
  7260. }
  7261. updateInput = cm.curOp.updateInput
  7262. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7263. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  7264. makeChange(cm.doc, changeEvent)
  7265. signalLater(cm, "inputRead", cm, changeEvent)
  7266. }
  7267. if (inserted && !paste)
  7268. { triggerElectric(cm, inserted) }
  7269. ensureCursorVisible(cm)
  7270. cm.curOp.updateInput = updateInput
  7271. cm.curOp.typing = true
  7272. cm.state.pasteIncoming = cm.state.cutIncoming = false
  7273. }
  7274. function handlePaste(e, cm) {
  7275. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  7276. if (pasted) {
  7277. e.preventDefault()
  7278. if (!cm.isReadOnly() && !cm.options.disableInput)
  7279. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  7280. return true
  7281. }
  7282. }
  7283. function triggerElectric(cm, inserted) {
  7284. // When an 'electric' character is inserted, immediately trigger a reindent
  7285. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7286. var sel = cm.doc.sel
  7287. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7288. var range = sel.ranges[i]
  7289. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7290. var mode = cm.getModeAt(range.head)
  7291. var indented = false
  7292. if (mode.electricChars) {
  7293. for (var j = 0; j < mode.electricChars.length; j++)
  7294. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7295. indented = indentLine(cm, range.head.line, "smart")
  7296. break
  7297. } }
  7298. } else if (mode.electricInput) {
  7299. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7300. { indented = indentLine(cm, range.head.line, "smart") }
  7301. }
  7302. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  7303. }
  7304. }
  7305. function copyableRanges(cm) {
  7306. var text = [], ranges = []
  7307. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7308. var line = cm.doc.sel.ranges[i].head.line
  7309. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  7310. ranges.push(lineRange)
  7311. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  7312. }
  7313. return {text: text, ranges: ranges}
  7314. }
  7315. function disableBrowserMagic(field, spellcheck) {
  7316. field.setAttribute("autocorrect", "off")
  7317. field.setAttribute("autocapitalize", "off")
  7318. field.setAttribute("spellcheck", !!spellcheck)
  7319. }
  7320. function hiddenTextarea() {
  7321. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  7322. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  7323. // The textarea is kept positioned near the cursor to prevent the
  7324. // fact that it'll be scrolled into view on input from scrolling
  7325. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7326. // very slow. So make the area wide instead.
  7327. if (webkit) { te.style.width = "1000px" }
  7328. else { te.setAttribute("wrap", "off") }
  7329. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7330. if (ios) { te.style.border = "1px solid black" }
  7331. disableBrowserMagic(te)
  7332. return div
  7333. }
  7334. // The publicly visible API. Note that methodOp(f) means
  7335. // 'wrap f in an operation, performed on its `this` parameter'.
  7336. // This is not the complete set of editor methods. Most of the
  7337. // methods defined on the Doc type are also injected into
  7338. // CodeMirror.prototype, for backwards compatibility and
  7339. // convenience.
  7340. function addEditorMethods(CodeMirror) {
  7341. var optionHandlers = CodeMirror.optionHandlers
  7342. var helpers = CodeMirror.helpers = {}
  7343. CodeMirror.prototype = {
  7344. constructor: CodeMirror,
  7345. focus: function(){window.focus(); this.display.input.focus()},
  7346. setOption: function(option, value) {
  7347. var options = this.options, old = options[option]
  7348. if (options[option] == value && option != "mode") { return }
  7349. options[option] = value
  7350. if (optionHandlers.hasOwnProperty(option))
  7351. { operation(this, optionHandlers[option])(this, value, old) }
  7352. signal(this, "optionChange", this, option)
  7353. },
  7354. getOption: function(option) {return this.options[option]},
  7355. getDoc: function() {return this.doc},
  7356. addKeyMap: function(map, bottom) {
  7357. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  7358. },
  7359. removeKeyMap: function(map) {
  7360. var maps = this.state.keyMaps
  7361. for (var i = 0; i < maps.length; ++i)
  7362. { if (maps[i] == map || maps[i].name == map) {
  7363. maps.splice(i, 1)
  7364. return true
  7365. } }
  7366. },
  7367. addOverlay: methodOp(function(spec, options) {
  7368. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  7369. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7370. insertSorted(this.state.overlays,
  7371. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7372. priority: (options && options.priority) || 0},
  7373. function (overlay) { return overlay.priority; })
  7374. this.state.modeGen++
  7375. regChange(this)
  7376. }),
  7377. removeOverlay: methodOp(function(spec) {
  7378. var this$1 = this;
  7379. var overlays = this.state.overlays
  7380. for (var i = 0; i < overlays.length; ++i) {
  7381. var cur = overlays[i].modeSpec
  7382. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7383. overlays.splice(i, 1)
  7384. this$1.state.modeGen++
  7385. regChange(this$1)
  7386. return
  7387. }
  7388. }
  7389. }),
  7390. indentLine: methodOp(function(n, dir, aggressive) {
  7391. if (typeof dir != "string" && typeof dir != "number") {
  7392. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  7393. else { dir = dir ? "add" : "subtract" }
  7394. }
  7395. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  7396. }),
  7397. indentSelection: methodOp(function(how) {
  7398. var this$1 = this;
  7399. var ranges = this.doc.sel.ranges, end = -1
  7400. for (var i = 0; i < ranges.length; i++) {
  7401. var range = ranges[i]
  7402. if (!range.empty()) {
  7403. var from = range.from(), to = range.to()
  7404. var start = Math.max(end, from.line)
  7405. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  7406. for (var j = start; j < end; ++j)
  7407. { indentLine(this$1, j, how) }
  7408. var newRanges = this$1.doc.sel.ranges
  7409. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7410. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  7411. } else if (range.head.line > end) {
  7412. indentLine(this$1, range.head.line, how, true)
  7413. end = range.head.line
  7414. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  7415. }
  7416. }
  7417. }),
  7418. // Fetch the parser token for a given character. Useful for hacks
  7419. // that want to inspect the mode state (say, for completion).
  7420. getTokenAt: function(pos, precise) {
  7421. return takeToken(this, pos, precise)
  7422. },
  7423. getLineTokens: function(line, precise) {
  7424. return takeToken(this, Pos(line), precise, true)
  7425. },
  7426. getTokenTypeAt: function(pos) {
  7427. pos = clipPos(this.doc, pos)
  7428. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7429. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7430. var type
  7431. if (ch == 0) { type = styles[2] }
  7432. else { for (;;) {
  7433. var mid = (before + after) >> 1
  7434. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7435. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7436. else { type = styles[mid * 2 + 2]; break }
  7437. } }
  7438. var cut = type ? type.indexOf("overlay ") : -1
  7439. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7440. },
  7441. getModeAt: function(pos) {
  7442. var mode = this.doc.mode
  7443. if (!mode.innerMode) { return mode }
  7444. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7445. },
  7446. getHelper: function(pos, type) {
  7447. return this.getHelpers(pos, type)[0]
  7448. },
  7449. getHelpers: function(pos, type) {
  7450. var this$1 = this;
  7451. var found = []
  7452. if (!helpers.hasOwnProperty(type)) { return found }
  7453. var help = helpers[type], mode = this.getModeAt(pos)
  7454. if (typeof mode[type] == "string") {
  7455. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7456. } else if (mode[type]) {
  7457. for (var i = 0; i < mode[type].length; i++) {
  7458. var val = help[mode[type][i]]
  7459. if (val) { found.push(val) }
  7460. }
  7461. } else if (mode.helperType && help[mode.helperType]) {
  7462. found.push(help[mode.helperType])
  7463. } else if (help[mode.name]) {
  7464. found.push(help[mode.name])
  7465. }
  7466. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7467. var cur = help._global[i$1]
  7468. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7469. { found.push(cur.val) }
  7470. }
  7471. return found
  7472. },
  7473. getStateAfter: function(line, precise) {
  7474. var doc = this.doc
  7475. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7476. return getContextBefore(this, line + 1, precise).state
  7477. },
  7478. cursorCoords: function(start, mode) {
  7479. var pos, range = this.doc.sel.primary()
  7480. if (start == null) { pos = range.head }
  7481. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7482. else { pos = start ? range.from() : range.to() }
  7483. return cursorCoords(this, pos, mode || "page")
  7484. },
  7485. charCoords: function(pos, mode) {
  7486. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7487. },
  7488. coordsChar: function(coords, mode) {
  7489. coords = fromCoordSystem(this, coords, mode || "page")
  7490. return coordsChar(this, coords.left, coords.top)
  7491. },
  7492. lineAtHeight: function(height, mode) {
  7493. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7494. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7495. },
  7496. heightAtLine: function(line, mode, includeWidgets) {
  7497. var end = false, lineObj
  7498. if (typeof line == "number") {
  7499. var last = this.doc.first + this.doc.size - 1
  7500. if (line < this.doc.first) { line = this.doc.first }
  7501. else if (line > last) { line = last; end = true }
  7502. lineObj = getLine(this.doc, line)
  7503. } else {
  7504. lineObj = line
  7505. }
  7506. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7507. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7508. },
  7509. defaultTextHeight: function() { return textHeight(this.display) },
  7510. defaultCharWidth: function() { return charWidth(this.display) },
  7511. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7512. addWidget: function(pos, node, scroll, vert, horiz) {
  7513. var display = this.display
  7514. pos = cursorCoords(this, clipPos(this.doc, pos))
  7515. var top = pos.bottom, left = pos.left
  7516. node.style.position = "absolute"
  7517. node.setAttribute("cm-ignore-events", "true")
  7518. this.display.input.setUneditable(node)
  7519. display.sizer.appendChild(node)
  7520. if (vert == "over") {
  7521. top = pos.top
  7522. } else if (vert == "above" || vert == "near") {
  7523. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7524. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7525. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7526. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7527. { top = pos.top - node.offsetHeight }
  7528. else if (pos.bottom + node.offsetHeight <= vspace)
  7529. { top = pos.bottom }
  7530. if (left + node.offsetWidth > hspace)
  7531. { left = hspace - node.offsetWidth }
  7532. }
  7533. node.style.top = top + "px"
  7534. node.style.left = node.style.right = ""
  7535. if (horiz == "right") {
  7536. left = display.sizer.clientWidth - node.offsetWidth
  7537. node.style.right = "0px"
  7538. } else {
  7539. if (horiz == "left") { left = 0 }
  7540. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7541. node.style.left = left + "px"
  7542. }
  7543. if (scroll)
  7544. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) }
  7545. },
  7546. triggerOnKeyDown: methodOp(onKeyDown),
  7547. triggerOnKeyPress: methodOp(onKeyPress),
  7548. triggerOnKeyUp: onKeyUp,
  7549. triggerOnMouseDown: methodOp(onMouseDown),
  7550. execCommand: function(cmd) {
  7551. if (commands.hasOwnProperty(cmd))
  7552. { return commands[cmd].call(null, this) }
  7553. },
  7554. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7555. findPosH: function(from, amount, unit, visually) {
  7556. var this$1 = this;
  7557. var dir = 1
  7558. if (amount < 0) { dir = -1; amount = -amount }
  7559. var cur = clipPos(this.doc, from)
  7560. for (var i = 0; i < amount; ++i) {
  7561. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7562. if (cur.hitSide) { break }
  7563. }
  7564. return cur
  7565. },
  7566. moveH: methodOp(function(dir, unit) {
  7567. var this$1 = this;
  7568. this.extendSelectionsBy(function (range) {
  7569. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7570. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7571. else
  7572. { return dir < 0 ? range.from() : range.to() }
  7573. }, sel_move)
  7574. }),
  7575. deleteH: methodOp(function(dir, unit) {
  7576. var sel = this.doc.sel, doc = this.doc
  7577. if (sel.somethingSelected())
  7578. { doc.replaceSelection("", null, "+delete") }
  7579. else
  7580. { deleteNearSelection(this, function (range) {
  7581. var other = findPosH(doc, range.head, dir, unit, false)
  7582. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7583. }) }
  7584. }),
  7585. findPosV: function(from, amount, unit, goalColumn) {
  7586. var this$1 = this;
  7587. var dir = 1, x = goalColumn
  7588. if (amount < 0) { dir = -1; amount = -amount }
  7589. var cur = clipPos(this.doc, from)
  7590. for (var i = 0; i < amount; ++i) {
  7591. var coords = cursorCoords(this$1, cur, "div")
  7592. if (x == null) { x = coords.left }
  7593. else { coords.left = x }
  7594. cur = findPosV(this$1, coords, dir, unit)
  7595. if (cur.hitSide) { break }
  7596. }
  7597. return cur
  7598. },
  7599. moveV: methodOp(function(dir, unit) {
  7600. var this$1 = this;
  7601. var doc = this.doc, goals = []
  7602. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7603. doc.extendSelectionsBy(function (range) {
  7604. if (collapse)
  7605. { return dir < 0 ? range.from() : range.to() }
  7606. var headPos = cursorCoords(this$1, range.head, "div")
  7607. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7608. goals.push(headPos.left)
  7609. var pos = findPosV(this$1, headPos, dir, unit)
  7610. if (unit == "page" && range == doc.sel.primary())
  7611. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top) }
  7612. return pos
  7613. }, sel_move)
  7614. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7615. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7616. }),
  7617. // Find the word at the given position (as returned by coordsChar).
  7618. findWordAt: function(pos) {
  7619. var doc = this.doc, line = getLine(doc, pos.line).text
  7620. var start = pos.ch, end = pos.ch
  7621. if (line) {
  7622. var helper = this.getHelper(pos, "wordChars")
  7623. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end }
  7624. var startChar = line.charAt(start)
  7625. var check = isWordChar(startChar, helper)
  7626. ? function (ch) { return isWordChar(ch, helper); }
  7627. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7628. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7629. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7630. while (end < line.length && check(line.charAt(end))) { ++end }
  7631. }
  7632. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7633. },
  7634. toggleOverwrite: function(value) {
  7635. if (value != null && value == this.state.overwrite) { return }
  7636. if (this.state.overwrite = !this.state.overwrite)
  7637. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7638. else
  7639. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7640. signal(this, "overwriteToggle", this, this.state.overwrite)
  7641. },
  7642. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7643. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7644. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }),
  7645. getScrollInfo: function() {
  7646. var scroller = this.display.scroller
  7647. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7648. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7649. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7650. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7651. },
  7652. scrollIntoView: methodOp(function(range, margin) {
  7653. if (range == null) {
  7654. range = {from: this.doc.sel.primary().head, to: null}
  7655. if (margin == null) { margin = this.options.cursorScrollMargin }
  7656. } else if (typeof range == "number") {
  7657. range = {from: Pos(range, 0), to: null}
  7658. } else if (range.from == null) {
  7659. range = {from: range, to: null}
  7660. }
  7661. if (!range.to) { range.to = range.from }
  7662. range.margin = margin || 0
  7663. if (range.from.line != null) {
  7664. scrollToRange(this, range)
  7665. } else {
  7666. scrollToCoordsRange(this, range.from, range.to, range.margin)
  7667. }
  7668. }),
  7669. setSize: methodOp(function(width, height) {
  7670. var this$1 = this;
  7671. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7672. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7673. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7674. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7675. var lineNo = this.display.viewFrom
  7676. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7677. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7678. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7679. ++lineNo
  7680. })
  7681. this.curOp.forceUpdate = true
  7682. signal(this, "refresh", this)
  7683. }),
  7684. operation: function(f){return runInOp(this, f)},
  7685. startOperation: function(){return startOperation(this)},
  7686. endOperation: function(){return endOperation(this)},
  7687. refresh: methodOp(function() {
  7688. var oldHeight = this.display.cachedTextHeight
  7689. regChange(this)
  7690. this.curOp.forceUpdate = true
  7691. clearCaches(this)
  7692. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)
  7693. updateGutterSpace(this)
  7694. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7695. { estimateLineHeights(this) }
  7696. signal(this, "refresh", this)
  7697. }),
  7698. swapDoc: methodOp(function(doc) {
  7699. var old = this.doc
  7700. old.cm = null
  7701. attachDoc(this, doc)
  7702. clearCaches(this)
  7703. this.display.input.reset()
  7704. scrollToCoords(this, doc.scrollLeft, doc.scrollTop)
  7705. this.curOp.forceScroll = true
  7706. signalLater(this, "swapDoc", this, old)
  7707. return old
  7708. }),
  7709. getInputField: function(){return this.display.input.getField()},
  7710. getWrapperElement: function(){return this.display.wrapper},
  7711. getScrollerElement: function(){return this.display.scroller},
  7712. getGutterElement: function(){return this.display.gutters}
  7713. }
  7714. eventMixin(CodeMirror)
  7715. CodeMirror.registerHelper = function(type, name, value) {
  7716. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7717. helpers[type][name] = value
  7718. }
  7719. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7720. CodeMirror.registerHelper(type, name, value)
  7721. helpers[type]._global.push({pred: predicate, val: value})
  7722. }
  7723. }
  7724. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7725. // right), unit can be "char", "column" (like char, but doesn't
  7726. // cross line boundaries), "word" (across next word), or "group" (to
  7727. // the start of next group of word or non-word-non-whitespace
  7728. // chars). The visually param controls whether, in right-to-left
  7729. // text, direction 1 means to move towards the next index in the
  7730. // string, or towards the character to the right of the current
  7731. // position. The resulting position will have a hitSide=true
  7732. // property if it reached the end of the document.
  7733. function findPosH(doc, pos, dir, unit, visually) {
  7734. var oldPos = pos
  7735. var origDir = dir
  7736. var lineObj = getLine(doc, pos.line)
  7737. function findNextLine() {
  7738. var l = pos.line + dir
  7739. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7740. pos = new Pos(l, pos.ch, pos.sticky)
  7741. return lineObj = getLine(doc, l)
  7742. }
  7743. function moveOnce(boundToLine) {
  7744. var next
  7745. if (visually) {
  7746. next = moveVisually(doc.cm, lineObj, pos, dir)
  7747. } else {
  7748. next = moveLogically(lineObj, pos, dir)
  7749. }
  7750. if (next == null) {
  7751. if (!boundToLine && findNextLine())
  7752. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) }
  7753. else
  7754. { return false }
  7755. } else {
  7756. pos = next
  7757. }
  7758. return true
  7759. }
  7760. if (unit == "char") {
  7761. moveOnce()
  7762. } else if (unit == "column") {
  7763. moveOnce(true)
  7764. } else if (unit == "word" || unit == "group") {
  7765. var sawType = null, group = unit == "group"
  7766. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7767. for (var first = true;; first = false) {
  7768. if (dir < 0 && !moveOnce(!first)) { break }
  7769. var cur = lineObj.text.charAt(pos.ch) || "\n"
  7770. var type = isWordChar(cur, helper) ? "w"
  7771. : group && cur == "\n" ? "n"
  7772. : !group || /\s/.test(cur) ? null
  7773. : "p"
  7774. if (group && !first && !type) { type = "s" }
  7775. if (sawType && sawType != type) {
  7776. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"}
  7777. break
  7778. }
  7779. if (type) { sawType = type }
  7780. if (dir > 0 && !moveOnce(!first)) { break }
  7781. }
  7782. }
  7783. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  7784. if (equalCursorPos(oldPos, result)) { result.hitSide = true }
  7785. return result
  7786. }
  7787. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7788. // "page" or "line". The resulting position will have a hitSide=true
  7789. // property if it reached the end of the document.
  7790. function findPosV(cm, pos, dir, unit) {
  7791. var doc = cm.doc, x = pos.left, y
  7792. if (unit == "page") {
  7793. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7794. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7795. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7796. } else if (unit == "line") {
  7797. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7798. }
  7799. var target
  7800. for (;;) {
  7801. target = coordsChar(cm, x, y)
  7802. if (!target.outside) { break }
  7803. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7804. y += dir * 5
  7805. }
  7806. return target
  7807. }
  7808. // CONTENTEDITABLE INPUT STYLE
  7809. var ContentEditableInput = function(cm) {
  7810. this.cm = cm
  7811. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7812. this.polling = new Delayed()
  7813. this.composing = null
  7814. this.gracePeriod = false
  7815. this.readDOMTimeout = null
  7816. };
  7817. ContentEditableInput.prototype.init = function (display) {
  7818. var this$1 = this;
  7819. var input = this, cm = input.cm
  7820. var div = input.div = display.lineDiv
  7821. disableBrowserMagic(div, cm.options.spellcheck)
  7822. on(div, "paste", function (e) {
  7823. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7824. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7825. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) }
  7826. })
  7827. on(div, "compositionstart", function (e) {
  7828. this$1.composing = {data: e.data, done: false}
  7829. })
  7830. on(div, "compositionupdate", function (e) {
  7831. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7832. })
  7833. on(div, "compositionend", function (e) {
  7834. if (this$1.composing) {
  7835. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7836. this$1.composing.done = true
  7837. }
  7838. })
  7839. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7840. on(div, "input", function () {
  7841. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7842. })
  7843. function onCopyCut(e) {
  7844. if (signalDOMEvent(cm, e)) { return }
  7845. if (cm.somethingSelected()) {
  7846. setLastCopied({lineWise: false, text: cm.getSelections()})
  7847. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7848. } else if (!cm.options.lineWiseCopyCut) {
  7849. return
  7850. } else {
  7851. var ranges = copyableRanges(cm)
  7852. setLastCopied({lineWise: true, text: ranges.text})
  7853. if (e.type == "cut") {
  7854. cm.operation(function () {
  7855. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7856. cm.replaceSelection("", null, "cut")
  7857. })
  7858. }
  7859. }
  7860. if (e.clipboardData) {
  7861. e.clipboardData.clearData()
  7862. var content = lastCopied.text.join("\n")
  7863. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7864. e.clipboardData.setData("Text", content)
  7865. if (e.clipboardData.getData("Text") == content) {
  7866. e.preventDefault()
  7867. return
  7868. }
  7869. }
  7870. // Old-fashioned briefly-focus-a-textarea hack
  7871. var kludge = hiddenTextarea(), te = kludge.firstChild
  7872. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7873. te.value = lastCopied.text.join("\n")
  7874. var hadFocus = document.activeElement
  7875. selectInput(te)
  7876. setTimeout(function () {
  7877. cm.display.lineSpace.removeChild(kludge)
  7878. hadFocus.focus()
  7879. if (hadFocus == div) { input.showPrimarySelection() }
  7880. }, 50)
  7881. }
  7882. on(div, "copy", onCopyCut)
  7883. on(div, "cut", onCopyCut)
  7884. };
  7885. ContentEditableInput.prototype.prepareSelection = function () {
  7886. var result = prepareSelection(this.cm, false)
  7887. result.focus = this.cm.state.focused
  7888. return result
  7889. };
  7890. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7891. if (!info || !this.cm.display.view.length) { return }
  7892. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7893. this.showMultipleSelections(info)
  7894. };
  7895. ContentEditableInput.prototype.showPrimarySelection = function () {
  7896. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()
  7897. var from = prim.from(), to = prim.to()
  7898. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7899. sel.removeAllRanges()
  7900. return
  7901. }
  7902. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7903. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  7904. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7905. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7906. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7907. { return }
  7908. var view = cm.display.view
  7909. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7910. {node: view[0].measure.map[2], offset: 0}
  7911. var end = to.line < cm.display.viewTo && posToDOM(cm, to)
  7912. if (!end) {
  7913. var measure = view[view.length - 1].measure
  7914. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7915. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7916. }
  7917. if (!start || !end) {
  7918. sel.removeAllRanges()
  7919. return
  7920. }
  7921. var old = sel.rangeCount && sel.getRangeAt(0), rng
  7922. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7923. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7924. if (rng) {
  7925. if (!gecko && cm.state.focused) {
  7926. sel.collapse(start.node, start.offset)
  7927. if (!rng.collapsed) {
  7928. sel.removeAllRanges()
  7929. sel.addRange(rng)
  7930. }
  7931. } else {
  7932. sel.removeAllRanges()
  7933. sel.addRange(rng)
  7934. }
  7935. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7936. else if (gecko) { this.startGracePeriod() }
  7937. }
  7938. this.rememberSelection()
  7939. };
  7940. ContentEditableInput.prototype.startGracePeriod = function () {
  7941. var this$1 = this;
  7942. clearTimeout(this.gracePeriod)
  7943. this.gracePeriod = setTimeout(function () {
  7944. this$1.gracePeriod = false
  7945. if (this$1.selectionChanged())
  7946. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7947. }, 20)
  7948. };
  7949. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7950. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7951. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7952. };
  7953. ContentEditableInput.prototype.rememberSelection = function () {
  7954. var sel = window.getSelection()
  7955. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7956. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7957. };
  7958. ContentEditableInput.prototype.selectionInEditor = function () {
  7959. var sel = window.getSelection()
  7960. if (!sel.rangeCount) { return false }
  7961. var node = sel.getRangeAt(0).commonAncestorContainer
  7962. return contains(this.div, node)
  7963. };
  7964. ContentEditableInput.prototype.focus = function () {
  7965. if (this.cm.options.readOnly != "nocursor") {
  7966. if (!this.selectionInEditor())
  7967. { this.showSelection(this.prepareSelection(), true) }
  7968. this.div.focus()
  7969. }
  7970. };
  7971. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7972. ContentEditableInput.prototype.getField = function () { return this.div };
  7973. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7974. ContentEditableInput.prototype.receivedFocus = function () {
  7975. var input = this
  7976. if (this.selectionInEditor())
  7977. { this.pollSelection() }
  7978. else
  7979. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7980. function poll() {
  7981. if (input.cm.state.focused) {
  7982. input.pollSelection()
  7983. input.polling.set(input.cm.options.pollInterval, poll)
  7984. }
  7985. }
  7986. this.polling.set(this.cm.options.pollInterval, poll)
  7987. };
  7988. ContentEditableInput.prototype.selectionChanged = function () {
  7989. var sel = window.getSelection()
  7990. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7991. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7992. };
  7993. ContentEditableInput.prototype.pollSelection = function () {
  7994. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  7995. var sel = window.getSelection(), cm = this.cm
  7996. // On Android Chrome (version 56, at least), backspacing into an
  7997. // uneditable block element will put the cursor in that element,
  7998. // and then, because it's not editable, hide the virtual keyboard.
  7999. // Because Android doesn't allow us to actually detect backspace
  8000. // presses in a sane way, this code checks for when that happens
  8001. // and simulates a backspace press in this case.
  8002. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  8003. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs})
  8004. this.blur()
  8005. this.focus()
  8006. return
  8007. }
  8008. if (this.composing) { return }
  8009. this.rememberSelection()
  8010. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  8011. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  8012. if (anchor && head) { runInOp(cm, function () {
  8013. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  8014. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  8015. }) }
  8016. };
  8017. ContentEditableInput.prototype.pollContent = function () {
  8018. if (this.readDOMTimeout != null) {
  8019. clearTimeout(this.readDOMTimeout)
  8020. this.readDOMTimeout = null
  8021. }
  8022. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  8023. var from = sel.from(), to = sel.to()
  8024. if (from.ch == 0 && from.line > cm.firstLine())
  8025. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  8026. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8027. { to = Pos(to.line + 1, 0) }
  8028. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8029. var fromIndex, fromLine, fromNode
  8030. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8031. fromLine = lineNo(display.view[0].line)
  8032. fromNode = display.view[0].node
  8033. } else {
  8034. fromLine = lineNo(display.view[fromIndex].line)
  8035. fromNode = display.view[fromIndex - 1].node.nextSibling
  8036. }
  8037. var toIndex = findViewIndex(cm, to.line)
  8038. var toLine, toNode
  8039. if (toIndex == display.view.length - 1) {
  8040. toLine = display.viewTo - 1
  8041. toNode = display.lineDiv.lastChild
  8042. } else {
  8043. toLine = lineNo(display.view[toIndex + 1].line) - 1
  8044. toNode = display.view[toIndex + 1].node.previousSibling
  8045. }
  8046. if (!fromNode) { return false }
  8047. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  8048. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  8049. while (newText.length > 1 && oldText.length > 1) {
  8050. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  8051. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  8052. else { break }
  8053. }
  8054. var cutFront = 0, cutEnd = 0
  8055. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  8056. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8057. { ++cutFront }
  8058. var newBot = lst(newText), oldBot = lst(oldText)
  8059. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8060. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  8061. while (cutEnd < maxCutEnd &&
  8062. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8063. { ++cutEnd }
  8064. // Try to move start of change to start of selection if ambiguous
  8065. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8066. while (cutFront && cutFront > from.ch &&
  8067. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8068. cutFront--
  8069. cutEnd++
  8070. }
  8071. }
  8072. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  8073. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  8074. var chFrom = Pos(fromLine, cutFront)
  8075. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  8076. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8077. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  8078. return true
  8079. }
  8080. };
  8081. ContentEditableInput.prototype.ensurePolled = function () {
  8082. this.forceCompositionEnd()
  8083. };
  8084. ContentEditableInput.prototype.reset = function () {
  8085. this.forceCompositionEnd()
  8086. };
  8087. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8088. if (!this.composing) { return }
  8089. clearTimeout(this.readDOMTimeout)
  8090. this.composing = null
  8091. this.updateFromDOM()
  8092. this.div.blur()
  8093. this.div.focus()
  8094. };
  8095. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8096. var this$1 = this;
  8097. if (this.readDOMTimeout != null) { return }
  8098. this.readDOMTimeout = setTimeout(function () {
  8099. this$1.readDOMTimeout = null
  8100. if (this$1.composing) {
  8101. if (this$1.composing.done) { this$1.composing = null }
  8102. else { return }
  8103. }
  8104. this$1.updateFromDOM()
  8105. }, 80)
  8106. };
  8107. ContentEditableInput.prototype.updateFromDOM = function () {
  8108. var this$1 = this;
  8109. if (this.cm.isReadOnly() || !this.pollContent())
  8110. { runInOp(this.cm, function () { return regChange(this$1.cm); }) }
  8111. };
  8112. ContentEditableInput.prototype.setUneditable = function (node) {
  8113. node.contentEditable = "false"
  8114. };
  8115. ContentEditableInput.prototype.onKeyPress = function (e) {
  8116. if (e.charCode == 0) { return }
  8117. e.preventDefault()
  8118. if (!this.cm.isReadOnly())
  8119. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  8120. };
  8121. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8122. this.div.contentEditable = String(val != "nocursor")
  8123. };
  8124. ContentEditableInput.prototype.onContextMenu = function () {};
  8125. ContentEditableInput.prototype.resetPosition = function () {};
  8126. ContentEditableInput.prototype.needsContentAttribute = true
  8127. function posToDOM(cm, pos) {
  8128. var view = findViewForLine(cm, pos.line)
  8129. if (!view || view.hidden) { return null }
  8130. var line = getLine(cm.doc, pos.line)
  8131. var info = mapFromLineView(view, line, pos.line)
  8132. var order = getOrder(line, cm.doc.direction), side = "left"
  8133. if (order) {
  8134. var partPos = getBidiPartAt(order, pos.ch)
  8135. side = partPos % 2 ? "right" : "left"
  8136. }
  8137. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  8138. result.offset = result.collapse == "right" ? result.end : result.start
  8139. return result
  8140. }
  8141. function isInGutter(node) {
  8142. for (var scan = node; scan; scan = scan.parentNode)
  8143. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8144. return false
  8145. }
  8146. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8147. function domTextBetween(cm, from, to, fromLine, toLine) {
  8148. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  8149. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8150. function close() {
  8151. if (closing) {
  8152. text += lineSep
  8153. closing = false
  8154. }
  8155. }
  8156. function addText(str) {
  8157. if (str) {
  8158. close()
  8159. text += str
  8160. }
  8161. }
  8162. function walk(node) {
  8163. if (node.nodeType == 1) {
  8164. var cmText = node.getAttribute("cm-text")
  8165. if (cmText != null) {
  8166. addText(cmText || node.textContent.replace(/\u200b/g, ""))
  8167. return
  8168. }
  8169. var markerID = node.getAttribute("cm-marker"), range
  8170. if (markerID) {
  8171. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  8172. if (found.length && (range = found[0].find(0)))
  8173. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) }
  8174. return
  8175. }
  8176. if (node.getAttribute("contenteditable") == "false") { return }
  8177. var isBlock = /^(pre|div|p)$/i.test(node.nodeName)
  8178. if (isBlock) { close() }
  8179. for (var i = 0; i < node.childNodes.length; i++)
  8180. { walk(node.childNodes[i]) }
  8181. if (isBlock) { closing = true }
  8182. } else if (node.nodeType == 3) {
  8183. addText(node.nodeValue)
  8184. }
  8185. }
  8186. for (;;) {
  8187. walk(from)
  8188. if (from == to) { break }
  8189. from = from.nextSibling
  8190. }
  8191. return text
  8192. }
  8193. function domToPos(cm, node, offset) {
  8194. var lineNode
  8195. if (node == cm.display.lineDiv) {
  8196. lineNode = cm.display.lineDiv.childNodes[offset]
  8197. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8198. node = null; offset = 0
  8199. } else {
  8200. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8201. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8202. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8203. }
  8204. }
  8205. for (var i = 0; i < cm.display.view.length; i++) {
  8206. var lineView = cm.display.view[i]
  8207. if (lineView.node == lineNode)
  8208. { return locateNodeInLineView(lineView, node, offset) }
  8209. }
  8210. }
  8211. function locateNodeInLineView(lineView, node, offset) {
  8212. var wrapper = lineView.text.firstChild, bad = false
  8213. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8214. if (node == wrapper) {
  8215. bad = true
  8216. node = wrapper.childNodes[offset]
  8217. offset = 0
  8218. if (!node) {
  8219. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  8220. return badPos(Pos(lineNo(line), line.text.length), bad)
  8221. }
  8222. }
  8223. var textNode = node.nodeType == 3 ? node : null, topNode = node
  8224. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8225. textNode = node.firstChild
  8226. if (offset) { offset = textNode.nodeValue.length }
  8227. }
  8228. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  8229. var measure = lineView.measure, maps = measure.maps
  8230. function find(textNode, topNode, offset) {
  8231. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8232. var map = i < 0 ? measure.map : maps[i]
  8233. for (var j = 0; j < map.length; j += 3) {
  8234. var curNode = map[j + 2]
  8235. if (curNode == textNode || curNode == topNode) {
  8236. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  8237. var ch = map[j] + offset
  8238. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  8239. return Pos(line, ch)
  8240. }
  8241. }
  8242. }
  8243. }
  8244. var found = find(textNode, topNode, offset)
  8245. if (found) { return badPos(found, bad) }
  8246. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8247. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8248. found = find(after, after.firstChild, 0)
  8249. if (found)
  8250. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8251. else
  8252. { dist += after.textContent.length }
  8253. }
  8254. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8255. found = find(before, before.firstChild, -1)
  8256. if (found)
  8257. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8258. else
  8259. { dist$1 += before.textContent.length }
  8260. }
  8261. }
  8262. // TEXTAREA INPUT STYLE
  8263. var TextareaInput = function(cm) {
  8264. this.cm = cm
  8265. // See input.poll and input.reset
  8266. this.prevInput = ""
  8267. // Flag that indicates whether we expect input to appear real soon
  8268. // now (after some event like 'keypress' or 'input') and are
  8269. // polling intensively.
  8270. this.pollingFast = false
  8271. // Self-resetting timeout for the poller
  8272. this.polling = new Delayed()
  8273. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8274. this.hasSelection = false
  8275. this.composing = null
  8276. };
  8277. TextareaInput.prototype.init = function (display) {
  8278. var this$1 = this;
  8279. var input = this, cm = this.cm
  8280. this.createField(display)
  8281. var te = this.textarea
  8282. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild)
  8283. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8284. if (ios) { te.style.width = "0px" }
  8285. on(te, "input", function () {
  8286. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  8287. input.poll()
  8288. })
  8289. on(te, "paste", function (e) {
  8290. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8291. cm.state.pasteIncoming = true
  8292. input.fastPoll()
  8293. })
  8294. function prepareCopyCut(e) {
  8295. if (signalDOMEvent(cm, e)) { return }
  8296. if (cm.somethingSelected()) {
  8297. setLastCopied({lineWise: false, text: cm.getSelections()})
  8298. } else if (!cm.options.lineWiseCopyCut) {
  8299. return
  8300. } else {
  8301. var ranges = copyableRanges(cm)
  8302. setLastCopied({lineWise: true, text: ranges.text})
  8303. if (e.type == "cut") {
  8304. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  8305. } else {
  8306. input.prevInput = ""
  8307. te.value = ranges.text.join("\n")
  8308. selectInput(te)
  8309. }
  8310. }
  8311. if (e.type == "cut") { cm.state.cutIncoming = true }
  8312. }
  8313. on(te, "cut", prepareCopyCut)
  8314. on(te, "copy", prepareCopyCut)
  8315. on(display.scroller, "paste", function (e) {
  8316. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8317. cm.state.pasteIncoming = true
  8318. input.focus()
  8319. })
  8320. // Prevent normal selection in the editor (we handle our own)
  8321. on(display.lineSpace, "selectstart", function (e) {
  8322. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  8323. })
  8324. on(te, "compositionstart", function () {
  8325. var start = cm.getCursor("from")
  8326. if (input.composing) { input.composing.range.clear() }
  8327. input.composing = {
  8328. start: start,
  8329. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8330. }
  8331. })
  8332. on(te, "compositionend", function () {
  8333. if (input.composing) {
  8334. input.poll()
  8335. input.composing.range.clear()
  8336. input.composing = null
  8337. }
  8338. })
  8339. };
  8340. TextareaInput.prototype.createField = function (_display) {
  8341. // Wraps and hides input textarea
  8342. this.wrapper = hiddenTextarea()
  8343. // The semihidden textarea that is focused when the editor is
  8344. // focused, and receives input.
  8345. this.textarea = this.wrapper.firstChild
  8346. };
  8347. TextareaInput.prototype.prepareSelection = function () {
  8348. // Redraw the selection and/or cursor
  8349. var cm = this.cm, display = cm.display, doc = cm.doc
  8350. var result = prepareSelection(cm)
  8351. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8352. if (cm.options.moveInputWithCursor) {
  8353. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  8354. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  8355. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8356. headPos.top + lineOff.top - wrapOff.top))
  8357. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8358. headPos.left + lineOff.left - wrapOff.left))
  8359. }
  8360. return result
  8361. };
  8362. TextareaInput.prototype.showSelection = function (drawn) {
  8363. var cm = this.cm, display = cm.display
  8364. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  8365. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  8366. if (drawn.teTop != null) {
  8367. this.wrapper.style.top = drawn.teTop + "px"
  8368. this.wrapper.style.left = drawn.teLeft + "px"
  8369. }
  8370. };
  8371. // Reset the input to correspond to the selection (or to be empty,
  8372. // when not typing and nothing is selected)
  8373. TextareaInput.prototype.reset = function (typing) {
  8374. if (this.contextMenuPending || this.composing) { return }
  8375. var cm = this.cm
  8376. if (cm.somethingSelected()) {
  8377. this.prevInput = ""
  8378. var content = cm.getSelection()
  8379. this.textarea.value = content
  8380. if (cm.state.focused) { selectInput(this.textarea) }
  8381. if (ie && ie_version >= 9) { this.hasSelection = content }
  8382. } else if (!typing) {
  8383. this.prevInput = this.textarea.value = ""
  8384. if (ie && ie_version >= 9) { this.hasSelection = null }
  8385. }
  8386. };
  8387. TextareaInput.prototype.getField = function () { return this.textarea };
  8388. TextareaInput.prototype.supportsTouch = function () { return false };
  8389. TextareaInput.prototype.focus = function () {
  8390. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8391. try { this.textarea.focus() }
  8392. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8393. }
  8394. };
  8395. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  8396. TextareaInput.prototype.resetPosition = function () {
  8397. this.wrapper.style.top = this.wrapper.style.left = 0
  8398. };
  8399. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  8400. // Poll for input changes, using the normal rate of polling. This
  8401. // runs as long as the editor is focused.
  8402. TextareaInput.prototype.slowPoll = function () {
  8403. var this$1 = this;
  8404. if (this.pollingFast) { return }
  8405. this.polling.set(this.cm.options.pollInterval, function () {
  8406. this$1.poll()
  8407. if (this$1.cm.state.focused) { this$1.slowPoll() }
  8408. })
  8409. };
  8410. // When an event has just come in that is likely to add or change
  8411. // something in the input textarea, we poll faster, to ensure that
  8412. // the change appears on the screen quickly.
  8413. TextareaInput.prototype.fastPoll = function () {
  8414. var missed = false, input = this
  8415. input.pollingFast = true
  8416. function p() {
  8417. var changed = input.poll()
  8418. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  8419. else {input.pollingFast = false; input.slowPoll()}
  8420. }
  8421. input.polling.set(20, p)
  8422. };
  8423. // Read input from the textarea, and update the document to match.
  8424. // When something is selected, it is present in the textarea, and
  8425. // selected (unless it is huge, in which case a placeholder is
  8426. // used). When nothing is selected, the cursor sits after previously
  8427. // seen text (can be empty), which is stored in prevInput (we must
  8428. // not reset the textarea when typing, because that breaks IME).
  8429. TextareaInput.prototype.poll = function () {
  8430. var this$1 = this;
  8431. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  8432. // Since this is called a *lot*, try to bail out as cheaply as
  8433. // possible when it is clear that nothing happened. hasSelection
  8434. // will be the case when there is a lot of text in the textarea,
  8435. // in which case reading its value would be expensive.
  8436. if (this.contextMenuPending || !cm.state.focused ||
  8437. (hasSelection(input) && !prevInput && !this.composing) ||
  8438. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8439. { return false }
  8440. var text = input.value
  8441. // If nothing changed, bail.
  8442. if (text == prevInput && !cm.somethingSelected()) { return false }
  8443. // Work around nonsensical selection resetting in IE9/10, and
  8444. // inexplicable appearance of private area unicode characters on
  8445. // some key combos in Mac (#2689).
  8446. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8447. mac && /[\uf700-\uf7ff]/.test(text)) {
  8448. cm.display.input.reset()
  8449. return false
  8450. }
  8451. if (cm.doc.sel == cm.display.selForContextMenu) {
  8452. var first = text.charCodeAt(0)
  8453. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  8454. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8455. }
  8456. // Find the part of the input that is actually new
  8457. var same = 0, l = Math.min(prevInput.length, text.length)
  8458. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8459. runInOp(cm, function () {
  8460. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8461. null, this$1.composing ? "*compose" : null)
  8462. // Don't leave long text in the textarea, since it makes further polling slow
  8463. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8464. else { this$1.prevInput = text }
  8465. if (this$1.composing) {
  8466. this$1.composing.range.clear()
  8467. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8468. {className: "CodeMirror-composing"})
  8469. }
  8470. })
  8471. return true
  8472. };
  8473. TextareaInput.prototype.ensurePolled = function () {
  8474. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8475. };
  8476. TextareaInput.prototype.onKeyPress = function () {
  8477. if (ie && ie_version >= 9) { this.hasSelection = null }
  8478. this.fastPoll()
  8479. };
  8480. TextareaInput.prototype.onContextMenu = function (e) {
  8481. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8482. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8483. if (!pos || presto) { return } // Opera is difficult.
  8484. // Reset the current text selection only if the click is done outside of the selection
  8485. // and 'resetSelectionOnContextMenu' option is true.
  8486. var reset = cm.options.resetSelectionOnContextMenu
  8487. if (reset && cm.doc.sel.contains(pos) == -1)
  8488. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8489. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8490. input.wrapper.style.cssText = "position: absolute"
  8491. var wrapperBox = input.wrapper.getBoundingClientRect()
  8492. 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);"
  8493. var oldScrollY
  8494. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8495. display.input.focus()
  8496. if (webkit) { window.scrollTo(null, oldScrollY) }
  8497. display.input.reset()
  8498. // Adds "Select all" to context menu in FF
  8499. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8500. input.contextMenuPending = true
  8501. display.selForContextMenu = cm.doc.sel
  8502. clearTimeout(display.detectingSelectAll)
  8503. // Select-all will be greyed out if there's nothing to select, so
  8504. // this adds a zero-width space so that we can later check whether
  8505. // it got selected.
  8506. function prepareSelectAllHack() {
  8507. if (te.selectionStart != null) {
  8508. var selected = cm.somethingSelected()
  8509. var extval = "\u200b" + (selected ? te.value : "")
  8510. te.value = "\u21da" // Used to catch context-menu undo
  8511. te.value = extval
  8512. input.prevInput = selected ? "" : "\u200b"
  8513. te.selectionStart = 1; te.selectionEnd = extval.length
  8514. // Re-set this, in case some other handler touched the
  8515. // selection in the meantime.
  8516. display.selForContextMenu = cm.doc.sel
  8517. }
  8518. }
  8519. function rehide() {
  8520. input.contextMenuPending = false
  8521. input.wrapper.style.cssText = oldWrapperCSS
  8522. te.style.cssText = oldCSS
  8523. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8524. // Try to detect the user choosing select-all
  8525. if (te.selectionStart != null) {
  8526. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8527. var i = 0, poll = function () {
  8528. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8529. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8530. operation(cm, selectAll)(cm)
  8531. } else if (i++ < 10) {
  8532. display.detectingSelectAll = setTimeout(poll, 500)
  8533. } else {
  8534. display.selForContextMenu = null
  8535. display.input.reset()
  8536. }
  8537. }
  8538. display.detectingSelectAll = setTimeout(poll, 200)
  8539. }
  8540. }
  8541. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8542. if (captureRightClick) {
  8543. e_stop(e)
  8544. var mouseup = function () {
  8545. off(window, "mouseup", mouseup)
  8546. setTimeout(rehide, 20)
  8547. }
  8548. on(window, "mouseup", mouseup)
  8549. } else {
  8550. setTimeout(rehide, 50)
  8551. }
  8552. };
  8553. TextareaInput.prototype.readOnlyChanged = function (val) {
  8554. if (!val) { this.reset() }
  8555. this.textarea.disabled = val == "nocursor"
  8556. };
  8557. TextareaInput.prototype.setUneditable = function () {};
  8558. TextareaInput.prototype.needsContentAttribute = false
  8559. function fromTextArea(textarea, options) {
  8560. options = options ? copyObj(options) : {}
  8561. options.value = textarea.value
  8562. if (!options.tabindex && textarea.tabIndex)
  8563. { options.tabindex = textarea.tabIndex }
  8564. if (!options.placeholder && textarea.placeholder)
  8565. { options.placeholder = textarea.placeholder }
  8566. // Set autofocus to true if this textarea is focused, or if it has
  8567. // autofocus and no other element is focused.
  8568. if (options.autofocus == null) {
  8569. var hasFocus = activeElt()
  8570. options.autofocus = hasFocus == textarea ||
  8571. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8572. }
  8573. function save() {textarea.value = cm.getValue()}
  8574. var realSubmit
  8575. if (textarea.form) {
  8576. on(textarea.form, "submit", save)
  8577. // Deplorable hack to make the submit method do the right thing.
  8578. if (!options.leaveSubmitMethodAlone) {
  8579. var form = textarea.form
  8580. realSubmit = form.submit
  8581. try {
  8582. var wrappedSubmit = form.submit = function () {
  8583. save()
  8584. form.submit = realSubmit
  8585. form.submit()
  8586. form.submit = wrappedSubmit
  8587. }
  8588. } catch(e) {}
  8589. }
  8590. }
  8591. options.finishInit = function (cm) {
  8592. cm.save = save
  8593. cm.getTextArea = function () { return textarea; }
  8594. cm.toTextArea = function () {
  8595. cm.toTextArea = isNaN // Prevent this from being ran twice
  8596. save()
  8597. textarea.parentNode.removeChild(cm.getWrapperElement())
  8598. textarea.style.display = ""
  8599. if (textarea.form) {
  8600. off(textarea.form, "submit", save)
  8601. if (typeof textarea.form.submit == "function")
  8602. { textarea.form.submit = realSubmit }
  8603. }
  8604. }
  8605. }
  8606. textarea.style.display = "none"
  8607. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8608. options)
  8609. return cm
  8610. }
  8611. function addLegacyProps(CodeMirror) {
  8612. CodeMirror.off = off
  8613. CodeMirror.on = on
  8614. CodeMirror.wheelEventPixels = wheelEventPixels
  8615. CodeMirror.Doc = Doc
  8616. CodeMirror.splitLines = splitLinesAuto
  8617. CodeMirror.countColumn = countColumn
  8618. CodeMirror.findColumn = findColumn
  8619. CodeMirror.isWordChar = isWordCharBasic
  8620. CodeMirror.Pass = Pass
  8621. CodeMirror.signal = signal
  8622. CodeMirror.Line = Line
  8623. CodeMirror.changeEnd = changeEnd
  8624. CodeMirror.scrollbarModel = scrollbarModel
  8625. CodeMirror.Pos = Pos
  8626. CodeMirror.cmpPos = cmp
  8627. CodeMirror.modes = modes
  8628. CodeMirror.mimeModes = mimeModes
  8629. CodeMirror.resolveMode = resolveMode
  8630. CodeMirror.getMode = getMode
  8631. CodeMirror.modeExtensions = modeExtensions
  8632. CodeMirror.extendMode = extendMode
  8633. CodeMirror.copyState = copyState
  8634. CodeMirror.startState = startState
  8635. CodeMirror.innerMode = innerMode
  8636. CodeMirror.commands = commands
  8637. CodeMirror.keyMap = keyMap
  8638. CodeMirror.keyName = keyName
  8639. CodeMirror.isModifierKey = isModifierKey
  8640. CodeMirror.lookupKey = lookupKey
  8641. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8642. CodeMirror.StringStream = StringStream
  8643. CodeMirror.SharedTextMarker = SharedTextMarker
  8644. CodeMirror.TextMarker = TextMarker
  8645. CodeMirror.LineWidget = LineWidget
  8646. CodeMirror.e_preventDefault = e_preventDefault
  8647. CodeMirror.e_stopPropagation = e_stopPropagation
  8648. CodeMirror.e_stop = e_stop
  8649. CodeMirror.addClass = addClass
  8650. CodeMirror.contains = contains
  8651. CodeMirror.rmClass = rmClass
  8652. CodeMirror.keyNames = keyNames
  8653. }
  8654. // EDITOR CONSTRUCTOR
  8655. defineOptions(CodeMirror)
  8656. addEditorMethods(CodeMirror)
  8657. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8658. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8659. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8660. { CodeMirror.prototype[prop] = (function(method) {
  8661. return function() {return method.apply(this.doc, arguments)}
  8662. })(Doc.prototype[prop]) } }
  8663. eventMixin(Doc)
  8664. // INPUT HANDLING
  8665. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8666. // MODE DEFINITION AND QUERYING
  8667. // Extra arguments are stored as the mode's dependencies, which is
  8668. // used by (legacy) mechanisms like loadmode.js to automatically
  8669. // load a mode. (Preferred mechanism is the require/define calls.)
  8670. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8671. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8672. defineMode.apply(this, arguments)
  8673. }
  8674. CodeMirror.defineMIME = defineMIME
  8675. // Minimal default mode.
  8676. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8677. CodeMirror.defineMIME("text/plain", "null")
  8678. // EXTENSIONS
  8679. CodeMirror.defineExtension = function (name, func) {
  8680. CodeMirror.prototype[name] = func
  8681. }
  8682. CodeMirror.defineDocExtension = function (name, func) {
  8683. Doc.prototype[name] = func
  8684. }
  8685. CodeMirror.fromTextArea = fromTextArea
  8686. addLegacyProps(CodeMirror)
  8687. CodeMirror.version = "5.36.1"
  8688. return CodeMirror;
  8689. })));