codemirror.js 352 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479
  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` satisfies `pred`.
  247. function findFirst(pred, from, to) {
  248. for (;;) {
  249. if (Math.abs(from - to) <= 1) { return pred(from) ? from : to }
  250. var mid = Math.floor((from + to) / 2)
  251. if (pred(mid)) { to = mid }
  252. else { from = mid }
  253. }
  254. }
  255. // The display handles the DOM integration, both for input reading
  256. // and content drawing. It holds references to DOM nodes and
  257. // display-related state.
  258. function Display(place, doc, input) {
  259. var d = this
  260. this.input = input
  261. // Covers bottom-right square when both scrollbars are present.
  262. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  263. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  264. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  265. // and h scrollbar is present.
  266. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  267. d.gutterFiller.setAttribute("cm-not-content", "true")
  268. // Will contain the actual code, positioned to cover the viewport.
  269. d.lineDiv = eltP("div", null, "CodeMirror-code")
  270. // Elements are added to these to represent selection and cursors.
  271. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  272. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  273. // A visibility: hidden element used to find the size of things.
  274. d.measure = elt("div", null, "CodeMirror-measure")
  275. // When lines outside of the viewport are measured, they are drawn in this.
  276. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  277. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  278. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  279. null, "position: relative; outline: none")
  280. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines")
  281. // Moved around its parent to cover visible view.
  282. d.mover = elt("div", [lines], null, "position: relative")
  283. // Set to the height of the document, allowing scrolling.
  284. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  285. d.sizerWidth = null
  286. // Behavior of elts with overflow: auto and padding is
  287. // inconsistent across browsers. This is used to ensure the
  288. // scrollable area is big enough.
  289. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  290. // Will contain the gutters, if any.
  291. d.gutters = elt("div", null, "CodeMirror-gutters")
  292. d.lineGutter = null
  293. // Actual scrollable element.
  294. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  295. d.scroller.setAttribute("tabIndex", "-1")
  296. // The element in which the editor lives.
  297. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  298. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  299. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  300. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  301. if (place) {
  302. if (place.appendChild) { place.appendChild(d.wrapper) }
  303. else { place(d.wrapper) }
  304. }
  305. // Current rendered range (may be bigger than the view window).
  306. d.viewFrom = d.viewTo = doc.first
  307. d.reportedViewFrom = d.reportedViewTo = doc.first
  308. // Information about the rendered lines.
  309. d.view = []
  310. d.renderedView = null
  311. // Holds info about a single rendered line when it was rendered
  312. // for measurement, while not in view.
  313. d.externalMeasured = null
  314. // Empty space (in pixels) above the view
  315. d.viewOffset = 0
  316. d.lastWrapHeight = d.lastWrapWidth = 0
  317. d.updateLineNumbers = null
  318. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  319. d.scrollbarsClipped = false
  320. // Used to only resize the line number gutter when necessary (when
  321. // the amount of lines crosses a boundary that makes its width change)
  322. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  323. // Set to true when a non-horizontal-scrolling line widget is
  324. // added. As an optimization, line widget aligning is skipped when
  325. // this is false.
  326. d.alignWidgets = false
  327. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  328. // Tracks the maximum line length so that the horizontal scrollbar
  329. // can be kept static when scrolling.
  330. d.maxLine = null
  331. d.maxLineLength = 0
  332. d.maxLineChanged = false
  333. // Used for measuring wheel scrolling granularity
  334. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  335. // True when shift is held down.
  336. d.shift = false
  337. // Used to track whether anything happened since the context menu
  338. // was opened.
  339. d.selForContextMenu = null
  340. d.activeTouch = null
  341. input.init(d)
  342. }
  343. // Find the line object corresponding to the given line number.
  344. function getLine(doc, n) {
  345. n -= doc.first
  346. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  347. var chunk = doc
  348. while (!chunk.lines) {
  349. for (var i = 0;; ++i) {
  350. var child = chunk.children[i], sz = child.chunkSize()
  351. if (n < sz) { chunk = child; break }
  352. n -= sz
  353. }
  354. }
  355. return chunk.lines[n]
  356. }
  357. // Get the part of a document between two positions, as an array of
  358. // strings.
  359. function getBetween(doc, start, end) {
  360. var out = [], n = start.line
  361. doc.iter(start.line, end.line + 1, function (line) {
  362. var text = line.text
  363. if (n == end.line) { text = text.slice(0, end.ch) }
  364. if (n == start.line) { text = text.slice(start.ch) }
  365. out.push(text)
  366. ++n
  367. })
  368. return out
  369. }
  370. // Get the lines between from and to, as array of strings.
  371. function getLines(doc, from, to) {
  372. var out = []
  373. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  374. return out
  375. }
  376. // Update the height of a line, propagating the height change
  377. // upwards to parent nodes.
  378. function updateLineHeight(line, height) {
  379. var diff = height - line.height
  380. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  381. }
  382. // Given a line object, find its line number by walking up through
  383. // its parent links.
  384. function lineNo(line) {
  385. if (line.parent == null) { return null }
  386. var cur = line.parent, no = indexOf(cur.lines, line)
  387. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  388. for (var i = 0;; ++i) {
  389. if (chunk.children[i] == cur) { break }
  390. no += chunk.children[i].chunkSize()
  391. }
  392. }
  393. return no + cur.first
  394. }
  395. // Find the line at the given vertical position, using the height
  396. // information in the document tree.
  397. function lineAtHeight(chunk, h) {
  398. var n = chunk.first
  399. outer: do {
  400. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  401. var child = chunk.children[i$1], ch = child.height
  402. if (h < ch) { chunk = child; continue outer }
  403. h -= ch
  404. n += child.chunkSize()
  405. }
  406. return n
  407. } while (!chunk.lines)
  408. var i = 0
  409. for (; i < chunk.lines.length; ++i) {
  410. var line = chunk.lines[i], lh = line.height
  411. if (h < lh) { break }
  412. h -= lh
  413. }
  414. return n + i
  415. }
  416. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  417. function lineNumberFor(options, i) {
  418. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  419. }
  420. // A Pos instance represents a position within the text.
  421. function Pos(line, ch, sticky) {
  422. if ( sticky === void 0 ) sticky = null;
  423. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  424. this.line = line
  425. this.ch = ch
  426. this.sticky = sticky
  427. }
  428. // Compare two positions, return 0 if they are the same, a negative
  429. // number when a is less, and a positive number otherwise.
  430. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  431. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  432. function copyPos(x) {return Pos(x.line, x.ch)}
  433. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  434. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  435. // Most of the external API clips given positions to make sure they
  436. // actually exist within the document.
  437. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  438. function clipPos(doc, pos) {
  439. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  440. var last = doc.first + doc.size - 1
  441. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  442. return clipToLen(pos, getLine(doc, pos.line).text.length)
  443. }
  444. function clipToLen(pos, linelen) {
  445. var ch = pos.ch
  446. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  447. else if (ch < 0) { return Pos(pos.line, 0) }
  448. else { return pos }
  449. }
  450. function clipPosArray(doc, array) {
  451. var out = []
  452. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  453. return out
  454. }
  455. // Optimize some code when these features are not used.
  456. var sawReadOnlySpans = false;
  457. var sawCollapsedSpans = false;
  458. function seeReadOnlySpans() {
  459. sawReadOnlySpans = true
  460. }
  461. function seeCollapsedSpans() {
  462. sawCollapsedSpans = true
  463. }
  464. // TEXTMARKER SPANS
  465. function MarkedSpan(marker, from, to) {
  466. this.marker = marker
  467. this.from = from; this.to = to
  468. }
  469. // Search an array of spans for a span matching the given marker.
  470. function getMarkedSpanFor(spans, marker) {
  471. if (spans) { for (var i = 0; i < spans.length; ++i) {
  472. var span = spans[i]
  473. if (span.marker == marker) { return span }
  474. } }
  475. }
  476. // Remove a span from an array, returning undefined if no spans are
  477. // left (we don't store arrays for lines without spans).
  478. function removeMarkedSpan(spans, span) {
  479. var r
  480. for (var i = 0; i < spans.length; ++i)
  481. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  482. return r
  483. }
  484. // Add a span to a line.
  485. function addMarkedSpan(line, span) {
  486. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  487. span.marker.attachLine(line)
  488. }
  489. // Used for the algorithm that adjusts markers for a change in the
  490. // document. These functions cut an array of spans at a given
  491. // character position, returning an array of remaining chunks (or
  492. // undefined if nothing remains).
  493. function markedSpansBefore(old, startCh, isInsert) {
  494. var nw
  495. if (old) { for (var i = 0; i < old.length; ++i) {
  496. var span = old[i], marker = span.marker
  497. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  498. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  499. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  500. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  501. }
  502. } }
  503. return nw
  504. }
  505. function markedSpansAfter(old, endCh, isInsert) {
  506. var nw
  507. if (old) { for (var i = 0; i < old.length; ++i) {
  508. var span = old[i], marker = span.marker
  509. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  510. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  511. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  512. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  513. span.to == null ? null : span.to - endCh))
  514. }
  515. } }
  516. return nw
  517. }
  518. // Given a change object, compute the new set of marker spans that
  519. // cover the line in which the change took place. Removes spans
  520. // entirely within the change, reconnects spans belonging to the
  521. // same marker that appear on both sides of the change, and cuts off
  522. // spans partially within the change. Returns an array of span
  523. // arrays with one element for each line in (after) the change.
  524. function stretchSpansOverChange(doc, change) {
  525. if (change.full) { return null }
  526. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  527. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  528. if (!oldFirst && !oldLast) { return null }
  529. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  530. // Get the spans that 'stick out' on both sides
  531. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  532. var last = markedSpansAfter(oldLast, endCh, isInsert)
  533. // Next, merge those two ends
  534. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  535. if (first) {
  536. // Fix up .to properties of first
  537. for (var i = 0; i < first.length; ++i) {
  538. var span = first[i]
  539. if (span.to == null) {
  540. var found = getMarkedSpanFor(last, span.marker)
  541. if (!found) { span.to = startCh }
  542. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  543. }
  544. }
  545. }
  546. if (last) {
  547. // Fix up .from in last (or move them into first in case of sameLine)
  548. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  549. var span$1 = last[i$1]
  550. if (span$1.to != null) { span$1.to += offset }
  551. if (span$1.from == null) {
  552. var found$1 = getMarkedSpanFor(first, span$1.marker)
  553. if (!found$1) {
  554. span$1.from = offset
  555. if (sameLine) { (first || (first = [])).push(span$1) }
  556. }
  557. } else {
  558. span$1.from += offset
  559. if (sameLine) { (first || (first = [])).push(span$1) }
  560. }
  561. }
  562. }
  563. // Make sure we didn't create any zero-length spans
  564. if (first) { first = clearEmptySpans(first) }
  565. if (last && last != first) { last = clearEmptySpans(last) }
  566. var newMarkers = [first]
  567. if (!sameLine) {
  568. // Fill gap with whole-line-spans
  569. var gap = change.text.length - 2, gapMarkers
  570. if (gap > 0 && first)
  571. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  572. { if (first[i$2].to == null)
  573. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  574. for (var i$3 = 0; i$3 < gap; ++i$3)
  575. { newMarkers.push(gapMarkers) }
  576. newMarkers.push(last)
  577. }
  578. return newMarkers
  579. }
  580. // Remove spans that are empty and don't have a clearWhenEmpty
  581. // option of false.
  582. function clearEmptySpans(spans) {
  583. for (var i = 0; i < spans.length; ++i) {
  584. var span = spans[i]
  585. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  586. { spans.splice(i--, 1) }
  587. }
  588. if (!spans.length) { return null }
  589. return spans
  590. }
  591. // Used to 'clip' out readOnly ranges when making a change.
  592. function removeReadOnlyRanges(doc, from, to) {
  593. var markers = null
  594. doc.iter(from.line, to.line + 1, function (line) {
  595. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  596. var mark = line.markedSpans[i].marker
  597. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  598. { (markers || (markers = [])).push(mark) }
  599. } }
  600. })
  601. if (!markers) { return null }
  602. var parts = [{from: from, to: to}]
  603. for (var i = 0; i < markers.length; ++i) {
  604. var mk = markers[i], m = mk.find(0)
  605. for (var j = 0; j < parts.length; ++j) {
  606. var p = parts[j]
  607. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  608. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  609. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  610. { newParts.push({from: p.from, to: m.from}) }
  611. if (dto > 0 || !mk.inclusiveRight && !dto)
  612. { newParts.push({from: m.to, to: p.to}) }
  613. parts.splice.apply(parts, newParts)
  614. j += newParts.length - 3
  615. }
  616. }
  617. return parts
  618. }
  619. // Connect or disconnect spans from a line.
  620. function detachMarkedSpans(line) {
  621. var spans = line.markedSpans
  622. if (!spans) { return }
  623. for (var i = 0; i < spans.length; ++i)
  624. { spans[i].marker.detachLine(line) }
  625. line.markedSpans = null
  626. }
  627. function attachMarkedSpans(line, spans) {
  628. if (!spans) { return }
  629. for (var i = 0; i < spans.length; ++i)
  630. { spans[i].marker.attachLine(line) }
  631. line.markedSpans = spans
  632. }
  633. // Helpers used when computing which overlapping collapsed span
  634. // counts as the larger one.
  635. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  636. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  637. // Returns a number indicating which of two overlapping collapsed
  638. // spans is larger (and thus includes the other). Falls back to
  639. // comparing ids when the spans cover exactly the same range.
  640. function compareCollapsedMarkers(a, b) {
  641. var lenDiff = a.lines.length - b.lines.length
  642. if (lenDiff != 0) { return lenDiff }
  643. var aPos = a.find(), bPos = b.find()
  644. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  645. if (fromCmp) { return -fromCmp }
  646. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  647. if (toCmp) { return toCmp }
  648. return b.id - a.id
  649. }
  650. // Find out whether a line ends or starts in a collapsed span. If
  651. // so, return the marker for that span.
  652. function collapsedSpanAtSide(line, start) {
  653. var sps = sawCollapsedSpans && line.markedSpans, found
  654. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  655. sp = sps[i]
  656. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  657. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  658. { found = sp.marker }
  659. } }
  660. return found
  661. }
  662. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  663. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  664. // Test whether there exists a collapsed span that partially
  665. // overlaps (covers the start or end, but not both) of a new span.
  666. // Such overlap is not allowed.
  667. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  668. var line = getLine(doc, lineNo)
  669. var sps = sawCollapsedSpans && line.markedSpans
  670. if (sps) { for (var i = 0; i < sps.length; ++i) {
  671. var sp = sps[i]
  672. if (!sp.marker.collapsed) { continue }
  673. var found = sp.marker.find(0)
  674. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  675. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  676. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  677. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  678. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  679. { return true }
  680. } }
  681. }
  682. // A visual line is a line as drawn on the screen. Folding, for
  683. // example, can cause multiple logical lines to appear on the same
  684. // visual line. This finds the start of the visual line that the
  685. // given line is part of (usually that is the line itself).
  686. function visualLine(line) {
  687. var merged
  688. while (merged = collapsedSpanAtStart(line))
  689. { line = merged.find(-1, true).line }
  690. return line
  691. }
  692. function visualLineEnd(line) {
  693. var merged
  694. while (merged = collapsedSpanAtEnd(line))
  695. { line = merged.find(1, true).line }
  696. return line
  697. }
  698. // Returns an array of logical lines that continue the visual line
  699. // started by the argument, or undefined if there are no such lines.
  700. function visualLineContinued(line) {
  701. var merged, lines
  702. while (merged = collapsedSpanAtEnd(line)) {
  703. line = merged.find(1, true).line
  704. ;(lines || (lines = [])).push(line)
  705. }
  706. return lines
  707. }
  708. // Get the line number of the start of the visual line that the
  709. // given line number is part of.
  710. function visualLineNo(doc, lineN) {
  711. var line = getLine(doc, lineN), vis = visualLine(line)
  712. if (line == vis) { return lineN }
  713. return lineNo(vis)
  714. }
  715. // Get the line number of the start of the next visual line after
  716. // the given line.
  717. function visualLineEndNo(doc, lineN) {
  718. if (lineN > doc.lastLine()) { return lineN }
  719. var line = getLine(doc, lineN), merged
  720. if (!lineIsHidden(doc, line)) { return lineN }
  721. while (merged = collapsedSpanAtEnd(line))
  722. { line = merged.find(1, true).line }
  723. return lineNo(line) + 1
  724. }
  725. // Compute whether a line is hidden. Lines count as hidden when they
  726. // are part of a visual line that starts with another line, or when
  727. // they are entirely covered by collapsed, non-widget span.
  728. function lineIsHidden(doc, line) {
  729. var sps = sawCollapsedSpans && line.markedSpans
  730. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  731. sp = sps[i]
  732. if (!sp.marker.collapsed) { continue }
  733. if (sp.from == null) { return true }
  734. if (sp.marker.widgetNode) { continue }
  735. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  736. { return true }
  737. } }
  738. }
  739. function lineIsHiddenInner(doc, line, span) {
  740. if (span.to == null) {
  741. var end = span.marker.find(1, true)
  742. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  743. }
  744. if (span.marker.inclusiveRight && span.to == line.text.length)
  745. { return true }
  746. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  747. sp = line.markedSpans[i]
  748. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  749. (sp.to == null || sp.to != span.from) &&
  750. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  751. lineIsHiddenInner(doc, line, sp)) { return true }
  752. }
  753. }
  754. // Find the height above the given line.
  755. function heightAtLine(lineObj) {
  756. lineObj = visualLine(lineObj)
  757. var h = 0, chunk = lineObj.parent
  758. for (var i = 0; i < chunk.lines.length; ++i) {
  759. var line = chunk.lines[i]
  760. if (line == lineObj) { break }
  761. else { h += line.height }
  762. }
  763. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  764. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  765. var cur = p.children[i$1]
  766. if (cur == chunk) { break }
  767. else { h += cur.height }
  768. }
  769. }
  770. return h
  771. }
  772. // Compute the character length of a line, taking into account
  773. // collapsed ranges (see markText) that might hide parts, and join
  774. // other lines onto it.
  775. function lineLength(line) {
  776. if (line.height == 0) { return 0 }
  777. var len = line.text.length, merged, cur = line
  778. while (merged = collapsedSpanAtStart(cur)) {
  779. var found = merged.find(0, true)
  780. cur = found.from.line
  781. len += found.from.ch - found.to.ch
  782. }
  783. cur = line
  784. while (merged = collapsedSpanAtEnd(cur)) {
  785. var found$1 = merged.find(0, true)
  786. len -= cur.text.length - found$1.from.ch
  787. cur = found$1.to.line
  788. len += cur.text.length - found$1.to.ch
  789. }
  790. return len
  791. }
  792. // Find the longest line in the document.
  793. function findMaxLine(cm) {
  794. var d = cm.display, doc = cm.doc
  795. d.maxLine = getLine(doc, doc.first)
  796. d.maxLineLength = lineLength(d.maxLine)
  797. d.maxLineChanged = true
  798. doc.iter(function (line) {
  799. var len = lineLength(line)
  800. if (len > d.maxLineLength) {
  801. d.maxLineLength = len
  802. d.maxLine = line
  803. }
  804. })
  805. }
  806. // BIDI HELPERS
  807. function iterateBidiSections(order, from, to, f) {
  808. if (!order) { return f(from, to, "ltr") }
  809. var found = false
  810. for (var i = 0; i < order.length; ++i) {
  811. var part = order[i]
  812. if (part.from < to && part.to > from || from == to && part.to == from) {
  813. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr")
  814. found = true
  815. }
  816. }
  817. if (!found) { f(from, to, "ltr") }
  818. }
  819. var bidiOther = null
  820. function getBidiPartAt(order, ch, sticky) {
  821. var found
  822. bidiOther = null
  823. for (var i = 0; i < order.length; ++i) {
  824. var cur = order[i]
  825. if (cur.from < ch && cur.to > ch) { return i }
  826. if (cur.to == ch) {
  827. if (cur.from != cur.to && sticky == "before") { found = i }
  828. else { bidiOther = i }
  829. }
  830. if (cur.from == ch) {
  831. if (cur.from != cur.to && sticky != "before") { found = i }
  832. else { bidiOther = i }
  833. }
  834. }
  835. return found != null ? found : bidiOther
  836. }
  837. // Bidirectional ordering algorithm
  838. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  839. // that this (partially) implements.
  840. // One-char codes used for character types:
  841. // L (L): Left-to-Right
  842. // R (R): Right-to-Left
  843. // r (AL): Right-to-Left Arabic
  844. // 1 (EN): European Number
  845. // + (ES): European Number Separator
  846. // % (ET): European Number Terminator
  847. // n (AN): Arabic Number
  848. // , (CS): Common Number Separator
  849. // m (NSM): Non-Spacing Mark
  850. // b (BN): Boundary Neutral
  851. // s (B): Paragraph Separator
  852. // t (S): Segment Separator
  853. // w (WS): Whitespace
  854. // N (ON): Other Neutrals
  855. // Returns null if characters are ordered as they appear
  856. // (left-to-right), or an array of sections ({from, to, level}
  857. // objects) in the order in which they occur visually.
  858. var bidiOrdering = (function() {
  859. // Character types for codepoints 0 to 0xff
  860. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  861. // Character types for codepoints 0x600 to 0x6f9
  862. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  863. function charType(code) {
  864. if (code <= 0xf7) { return lowTypes.charAt(code) }
  865. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  866. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  867. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  868. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  869. else if (code == 0x200c) { return "b" }
  870. else { return "L" }
  871. }
  872. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  873. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  874. function BidiSpan(level, from, to) {
  875. this.level = level
  876. this.from = from; this.to = to
  877. }
  878. return function(str, direction) {
  879. var outerType = direction == "ltr" ? "L" : "R"
  880. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  881. var len = str.length, types = []
  882. for (var i = 0; i < len; ++i)
  883. { types.push(charType(str.charCodeAt(i))) }
  884. // W1. Examine each non-spacing mark (NSM) in the level run, and
  885. // change the type of the NSM to the type of the previous
  886. // character. If the NSM is at the start of the level run, it will
  887. // get the type of sor.
  888. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  889. var type = types[i$1]
  890. if (type == "m") { types[i$1] = prev }
  891. else { prev = type }
  892. }
  893. // W2. Search backwards from each instance of a European number
  894. // until the first strong type (R, L, AL, or sor) is found. If an
  895. // AL is found, change the type of the European number to Arabic
  896. // number.
  897. // W3. Change all ALs to R.
  898. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  899. var type$1 = types[i$2]
  900. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  901. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  902. }
  903. // W4. A single European separator between two European numbers
  904. // changes to a European number. A single common separator between
  905. // two numbers of the same type changes to that type.
  906. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  907. var type$2 = types[i$3]
  908. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  909. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  910. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  911. prev$1 = type$2
  912. }
  913. // W5. A sequence of European terminators adjacent to European
  914. // numbers changes to all European numbers.
  915. // W6. Otherwise, separators and terminators change to Other
  916. // Neutral.
  917. for (var i$4 = 0; i$4 < len; ++i$4) {
  918. var type$3 = types[i$4]
  919. if (type$3 == ",") { types[i$4] = "N" }
  920. else if (type$3 == "%") {
  921. var end = (void 0)
  922. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  923. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  924. for (var j = i$4; j < end; ++j) { types[j] = replace }
  925. i$4 = end - 1
  926. }
  927. }
  928. // W7. Search backwards from each instance of a European number
  929. // until the first strong type (R, L, or sor) is found. If an L is
  930. // found, then change the type of the European number to L.
  931. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  932. var type$4 = types[i$5]
  933. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  934. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  935. }
  936. // N1. A sequence of neutrals takes the direction of the
  937. // surrounding strong text if the text on both sides has the same
  938. // direction. European and Arabic numbers act as if they were R in
  939. // terms of their influence on neutrals. Start-of-level-run (sor)
  940. // and end-of-level-run (eor) are used at level run boundaries.
  941. // N2. Any remaining neutrals take the embedding direction.
  942. for (var i$6 = 0; i$6 < len; ++i$6) {
  943. if (isNeutral.test(types[i$6])) {
  944. var end$1 = (void 0)
  945. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  946. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  947. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  948. var replace$1 = before == after ? (before ? "L" : "R") : outerType
  949. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  950. i$6 = end$1 - 1
  951. }
  952. }
  953. // Here we depart from the documented algorithm, in order to avoid
  954. // building up an actual levels array. Since there are only three
  955. // levels (0, 1, 2) in an implementation that doesn't take
  956. // explicit embedding into account, we can build up the order on
  957. // the fly, without following the level-based algorithm.
  958. var order = [], m
  959. for (var i$7 = 0; i$7 < len;) {
  960. if (countsAsLeft.test(types[i$7])) {
  961. var start = i$7
  962. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  963. order.push(new BidiSpan(0, start, i$7))
  964. } else {
  965. var pos = i$7, at = order.length
  966. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  967. for (var j$2 = pos; j$2 < i$7;) {
  968. if (countsAsNum.test(types[j$2])) {
  969. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  970. var nstart = j$2
  971. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  972. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  973. pos = j$2
  974. } else { ++j$2 }
  975. }
  976. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  977. }
  978. }
  979. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  980. order[0].from = m[0].length
  981. order.unshift(new BidiSpan(0, 0, m[0].length))
  982. }
  983. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  984. lst(order).to -= m[0].length
  985. order.push(new BidiSpan(0, len - m[0].length, len))
  986. }
  987. return direction == "rtl" ? order.reverse() : order
  988. }
  989. })()
  990. // Get the bidi ordering for the given line (and cache it). Returns
  991. // false for lines that are fully left-to-right, and an array of
  992. // BidiSpan objects otherwise.
  993. function getOrder(line, direction) {
  994. var order = line.order
  995. if (order == null) { order = line.order = bidiOrdering(line.text, direction) }
  996. return order
  997. }
  998. function moveCharLogically(line, ch, dir) {
  999. var target = skipExtendingChars(line.text, ch + dir, dir)
  1000. return target < 0 || target > line.text.length ? null : target
  1001. }
  1002. function moveLogically(line, start, dir) {
  1003. var ch = moveCharLogically(line, start.ch, dir)
  1004. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  1005. }
  1006. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  1007. if (visually) {
  1008. var order = getOrder(lineObj, cm.doc.direction)
  1009. if (order) {
  1010. var part = dir < 0 ? lst(order) : order[0]
  1011. var moveInStorageOrder = (dir < 0) == (part.level == 1)
  1012. var sticky = moveInStorageOrder ? "after" : "before"
  1013. var ch
  1014. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  1015. // it could be that the last bidi part is not on the last visual line,
  1016. // since visual lines contain content order-consecutive chunks.
  1017. // Thus, in rtl, we are looking for the first (content-order) character
  1018. // in the rtl chunk that is on the last line (that is, the same line
  1019. // as the last (content-order) character).
  1020. if (part.level > 0) {
  1021. var prep = prepareMeasureForLine(cm, lineObj)
  1022. ch = dir < 0 ? lineObj.text.length - 1 : 0
  1023. var targetTop = measureCharPrepared(cm, prep, ch).top
  1024. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
  1025. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) }
  1026. } else { ch = dir < 0 ? part.to : part.from }
  1027. return new Pos(lineNo, ch, sticky)
  1028. }
  1029. }
  1030. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  1031. }
  1032. function moveVisually(cm, line, start, dir) {
  1033. var bidi = getOrder(line, cm.doc.direction)
  1034. if (!bidi) { return moveLogically(line, start, dir) }
  1035. if (start.ch >= line.text.length) {
  1036. start.ch = line.text.length
  1037. start.sticky = "before"
  1038. } else if (start.ch <= 0) {
  1039. start.ch = 0
  1040. start.sticky = "after"
  1041. }
  1042. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
  1043. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  1044. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  1045. // nothing interesting happens.
  1046. return moveLogically(line, start, dir)
  1047. }
  1048. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
  1049. var prep
  1050. var getWrappedLineExtent = function (ch) {
  1051. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  1052. prep = prep || prepareMeasureForLine(cm, line)
  1053. return wrappedLineExtentChar(cm, line, prep, ch)
  1054. }
  1055. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
  1056. if (cm.doc.direction == "rtl" || part.level == 1) {
  1057. var moveInStorageOrder = (part.level == 1) == (dir < 0)
  1058. var ch = mv(start, moveInStorageOrder ? 1 : -1)
  1059. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  1060. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  1061. var sticky = moveInStorageOrder ? "before" : "after"
  1062. return new Pos(start.line, ch, sticky)
  1063. }
  1064. }
  1065. // Case 3: Could not move within this bidi part in this visual line, so leave
  1066. // the current bidi part
  1067. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  1068. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  1069. ? new Pos(start.line, mv(ch, 1), "before")
  1070. : new Pos(start.line, ch, "after"); }
  1071. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  1072. var part = bidi[partPos]
  1073. var moveInStorageOrder = (dir > 0) == (part.level != 1)
  1074. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  1075. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  1076. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  1077. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  1078. }
  1079. }
  1080. // Case 3a: Look for other bidi parts on the same visual line
  1081. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  1082. if (res) { return res }
  1083. // Case 3b: Look for other bidi parts on the next visual line
  1084. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  1085. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  1086. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  1087. if (res) { return res }
  1088. }
  1089. // Case 4: Nowhere to move
  1090. return null
  1091. }
  1092. // EVENT HANDLING
  1093. // Lightweight event framework. on/off also work on DOM nodes,
  1094. // registering native DOM handlers.
  1095. var noHandlers = []
  1096. var on = function(emitter, type, f) {
  1097. if (emitter.addEventListener) {
  1098. emitter.addEventListener(type, f, false)
  1099. } else if (emitter.attachEvent) {
  1100. emitter.attachEvent("on" + type, f)
  1101. } else {
  1102. var map = emitter._handlers || (emitter._handlers = {})
  1103. map[type] = (map[type] || noHandlers).concat(f)
  1104. }
  1105. }
  1106. function getHandlers(emitter, type) {
  1107. return emitter._handlers && emitter._handlers[type] || noHandlers
  1108. }
  1109. function off(emitter, type, f) {
  1110. if (emitter.removeEventListener) {
  1111. emitter.removeEventListener(type, f, false)
  1112. } else if (emitter.detachEvent) {
  1113. emitter.detachEvent("on" + type, f)
  1114. } else {
  1115. var map = emitter._handlers, arr = map && map[type]
  1116. if (arr) {
  1117. var index = indexOf(arr, f)
  1118. if (index > -1)
  1119. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1120. }
  1121. }
  1122. }
  1123. function signal(emitter, type /*, values...*/) {
  1124. var handlers = getHandlers(emitter, type)
  1125. if (!handlers.length) { return }
  1126. var args = Array.prototype.slice.call(arguments, 2)
  1127. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1128. }
  1129. // The DOM events that CodeMirror handles can be overridden by
  1130. // registering a (non-DOM) handler on the editor for the event name,
  1131. // and preventDefault-ing the event in that handler.
  1132. function signalDOMEvent(cm, e, override) {
  1133. if (typeof e == "string")
  1134. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1135. signal(cm, override || e.type, cm, e)
  1136. return e_defaultPrevented(e) || e.codemirrorIgnore
  1137. }
  1138. function signalCursorActivity(cm) {
  1139. var arr = cm._handlers && cm._handlers.cursorActivity
  1140. if (!arr) { return }
  1141. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1142. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1143. { set.push(arr[i]) } }
  1144. }
  1145. function hasHandler(emitter, type) {
  1146. return getHandlers(emitter, type).length > 0
  1147. }
  1148. // Add on and off methods to a constructor's prototype, to make
  1149. // registering events on such objects more convenient.
  1150. function eventMixin(ctor) {
  1151. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1152. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1153. }
  1154. // Due to the fact that we still support jurassic IE versions, some
  1155. // compatibility wrappers are needed.
  1156. function e_preventDefault(e) {
  1157. if (e.preventDefault) { e.preventDefault() }
  1158. else { e.returnValue = false }
  1159. }
  1160. function e_stopPropagation(e) {
  1161. if (e.stopPropagation) { e.stopPropagation() }
  1162. else { e.cancelBubble = true }
  1163. }
  1164. function e_defaultPrevented(e) {
  1165. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1166. }
  1167. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1168. function e_target(e) {return e.target || e.srcElement}
  1169. function e_button(e) {
  1170. var b = e.which
  1171. if (b == null) {
  1172. if (e.button & 1) { b = 1 }
  1173. else if (e.button & 2) { b = 3 }
  1174. else if (e.button & 4) { b = 2 }
  1175. }
  1176. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1177. return b
  1178. }
  1179. // Detect drag-and-drop
  1180. var dragAndDrop = function() {
  1181. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1182. // couldn't get it to work yet.
  1183. if (ie && ie_version < 9) { return false }
  1184. var div = elt('div')
  1185. return "draggable" in div || "dragDrop" in div
  1186. }()
  1187. var zwspSupported
  1188. function zeroWidthElement(measure) {
  1189. if (zwspSupported == null) {
  1190. var test = elt("span", "\u200b")
  1191. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1192. if (measure.firstChild.offsetHeight != 0)
  1193. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1194. }
  1195. var node = zwspSupported ? elt("span", "\u200b") :
  1196. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1197. node.setAttribute("cm-text", "")
  1198. return node
  1199. }
  1200. // Feature-detect IE's crummy client rect reporting for bidi text
  1201. var badBidiRects
  1202. function hasBadBidiRects(measure) {
  1203. if (badBidiRects != null) { return badBidiRects }
  1204. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1205. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1206. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1207. removeChildren(measure)
  1208. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1209. return badBidiRects = (r1.right - r0.right < 3)
  1210. }
  1211. // See if "".split is the broken IE version, if so, provide an
  1212. // alternative way to split lines.
  1213. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1214. var pos = 0, result = [], l = string.length
  1215. while (pos <= l) {
  1216. var nl = string.indexOf("\n", pos)
  1217. if (nl == -1) { nl = string.length }
  1218. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1219. var rt = line.indexOf("\r")
  1220. if (rt != -1) {
  1221. result.push(line.slice(0, rt))
  1222. pos += rt + 1
  1223. } else {
  1224. result.push(line)
  1225. pos = nl + 1
  1226. }
  1227. }
  1228. return result
  1229. } : function (string) { return string.split(/\r\n?|\n/); }
  1230. var hasSelection = window.getSelection ? function (te) {
  1231. try { return te.selectionStart != te.selectionEnd }
  1232. catch(e) { return false }
  1233. } : function (te) {
  1234. var range
  1235. try {range = te.ownerDocument.selection.createRange()}
  1236. catch(e) {}
  1237. if (!range || range.parentElement() != te) { return false }
  1238. return range.compareEndPoints("StartToEnd", range) != 0
  1239. }
  1240. var hasCopyEvent = (function () {
  1241. var e = elt("div")
  1242. if ("oncopy" in e) { return true }
  1243. e.setAttribute("oncopy", "return;")
  1244. return typeof e.oncopy == "function"
  1245. })()
  1246. var badZoomedRects = null
  1247. function hasBadZoomedRects(measure) {
  1248. if (badZoomedRects != null) { return badZoomedRects }
  1249. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1250. var normal = node.getBoundingClientRect()
  1251. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1252. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1253. }
  1254. var modes = {};
  1255. var mimeModes = {};
  1256. // Extra arguments are stored as the mode's dependencies, which is
  1257. // used by (legacy) mechanisms like loadmode.js to automatically
  1258. // load a mode. (Preferred mechanism is the require/define calls.)
  1259. function defineMode(name, mode) {
  1260. if (arguments.length > 2)
  1261. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1262. modes[name] = mode
  1263. }
  1264. function defineMIME(mime, spec) {
  1265. mimeModes[mime] = spec
  1266. }
  1267. // Given a MIME type, a {name, ...options} config object, or a name
  1268. // string, return a mode config object.
  1269. function resolveMode(spec) {
  1270. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1271. spec = mimeModes[spec]
  1272. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1273. var found = mimeModes[spec.name]
  1274. if (typeof found == "string") { found = {name: found} }
  1275. spec = createObj(found, spec)
  1276. spec.name = found.name
  1277. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1278. return resolveMode("application/xml")
  1279. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1280. return resolveMode("application/json")
  1281. }
  1282. if (typeof spec == "string") { return {name: spec} }
  1283. else { return spec || {name: "null"} }
  1284. }
  1285. // Given a mode spec (anything that resolveMode accepts), find and
  1286. // initialize an actual mode object.
  1287. function getMode(options, spec) {
  1288. spec = resolveMode(spec)
  1289. var mfactory = modes[spec.name]
  1290. if (!mfactory) { return getMode(options, "text/plain") }
  1291. var modeObj = mfactory(options, spec)
  1292. if (modeExtensions.hasOwnProperty(spec.name)) {
  1293. var exts = modeExtensions[spec.name]
  1294. for (var prop in exts) {
  1295. if (!exts.hasOwnProperty(prop)) { continue }
  1296. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1297. modeObj[prop] = exts[prop]
  1298. }
  1299. }
  1300. modeObj.name = spec.name
  1301. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1302. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1303. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1304. return modeObj
  1305. }
  1306. // This can be used to attach properties to mode objects from
  1307. // outside the actual mode definition.
  1308. var modeExtensions = {}
  1309. function extendMode(mode, properties) {
  1310. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1311. copyObj(properties, exts)
  1312. }
  1313. function copyState(mode, state) {
  1314. if (state === true) { return state }
  1315. if (mode.copyState) { return mode.copyState(state) }
  1316. var nstate = {}
  1317. for (var n in state) {
  1318. var val = state[n]
  1319. if (val instanceof Array) { val = val.concat([]) }
  1320. nstate[n] = val
  1321. }
  1322. return nstate
  1323. }
  1324. // Given a mode and a state (for that mode), find the inner mode and
  1325. // state at the position that the state refers to.
  1326. function innerMode(mode, state) {
  1327. var info
  1328. while (mode.innerMode) {
  1329. info = mode.innerMode(state)
  1330. if (!info || info.mode == mode) { break }
  1331. state = info.state
  1332. mode = info.mode
  1333. }
  1334. return info || {mode: mode, state: state}
  1335. }
  1336. function startState(mode, a1, a2) {
  1337. return mode.startState ? mode.startState(a1, a2) : true
  1338. }
  1339. // STRING STREAM
  1340. // Fed to the mode parsers, provides helper functions to make
  1341. // parsers more succinct.
  1342. var StringStream = function(string, tabSize, lineOracle) {
  1343. this.pos = this.start = 0
  1344. this.string = string
  1345. this.tabSize = tabSize || 8
  1346. this.lastColumnPos = this.lastColumnValue = 0
  1347. this.lineStart = 0
  1348. this.lineOracle = lineOracle
  1349. };
  1350. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1351. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1352. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1353. StringStream.prototype.next = function () {
  1354. if (this.pos < this.string.length)
  1355. { return this.string.charAt(this.pos++) }
  1356. };
  1357. StringStream.prototype.eat = function (match) {
  1358. var ch = this.string.charAt(this.pos)
  1359. var ok
  1360. if (typeof match == "string") { ok = ch == match }
  1361. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1362. if (ok) {++this.pos; return ch}
  1363. };
  1364. StringStream.prototype.eatWhile = function (match) {
  1365. var start = this.pos
  1366. while (this.eat(match)){}
  1367. return this.pos > start
  1368. };
  1369. StringStream.prototype.eatSpace = function () {
  1370. var this$1 = this;
  1371. var start = this.pos
  1372. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1373. return this.pos > start
  1374. };
  1375. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
  1376. StringStream.prototype.skipTo = function (ch) {
  1377. var found = this.string.indexOf(ch, this.pos)
  1378. if (found > -1) {this.pos = found; return true}
  1379. };
  1380. StringStream.prototype.backUp = function (n) {this.pos -= n};
  1381. StringStream.prototype.column = function () {
  1382. if (this.lastColumnPos < this.start) {
  1383. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1384. this.lastColumnPos = this.start
  1385. }
  1386. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1387. };
  1388. StringStream.prototype.indentation = function () {
  1389. return countColumn(this.string, null, this.tabSize) -
  1390. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1391. };
  1392. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1393. if (typeof pattern == "string") {
  1394. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1395. var substr = this.string.substr(this.pos, pattern.length)
  1396. if (cased(substr) == cased(pattern)) {
  1397. if (consume !== false) { this.pos += pattern.length }
  1398. return true
  1399. }
  1400. } else {
  1401. var match = this.string.slice(this.pos).match(pattern)
  1402. if (match && match.index > 0) { return null }
  1403. if (match && consume !== false) { this.pos += match[0].length }
  1404. return match
  1405. }
  1406. };
  1407. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1408. StringStream.prototype.hideFirstChars = function (n, inner) {
  1409. this.lineStart += n
  1410. try { return inner() }
  1411. finally { this.lineStart -= n }
  1412. };
  1413. StringStream.prototype.lookAhead = function (n) {
  1414. var oracle = this.lineOracle
  1415. return oracle && oracle.lookAhead(n)
  1416. };
  1417. var SavedContext = function(state, lookAhead) {
  1418. this.state = state
  1419. this.lookAhead = lookAhead
  1420. };
  1421. var Context = function(doc, state, line, lookAhead) {
  1422. this.state = state
  1423. this.doc = doc
  1424. this.line = line
  1425. this.maxLookAhead = lookAhead || 0
  1426. };
  1427. Context.prototype.lookAhead = function (n) {
  1428. var line = this.doc.getLine(this.line + n)
  1429. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n }
  1430. return line
  1431. };
  1432. Context.prototype.nextLine = function () {
  1433. this.line++
  1434. if (this.maxLookAhead > 0) { this.maxLookAhead-- }
  1435. };
  1436. Context.fromSaved = function (doc, saved, line) {
  1437. if (saved instanceof SavedContext)
  1438. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1439. else
  1440. { return new Context(doc, copyState(doc.mode, saved), line) }
  1441. };
  1442. Context.prototype.save = function (copy) {
  1443. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
  1444. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1445. };
  1446. // Compute a style array (an array starting with a mode generation
  1447. // -- for invalidation -- followed by pairs of end positions and
  1448. // style strings), which is used to highlight the tokens on the
  1449. // line.
  1450. function highlightLine(cm, line, context, forceToEnd) {
  1451. // A styles array always starts with a number identifying the
  1452. // mode/overlays that it is based on (for easy invalidation).
  1453. var st = [cm.state.modeGen], lineClasses = {}
  1454. // Compute the base array of styles
  1455. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1456. lineClasses, forceToEnd)
  1457. var state = context.state
  1458. // Run overlays, adjust style array.
  1459. var loop = function ( o ) {
  1460. var overlay = cm.state.overlays[o], i = 1, at = 0
  1461. context.state = true
  1462. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1463. var start = i
  1464. // Ensure there's a token end at the current position, and that i points at it
  1465. while (at < end) {
  1466. var i_end = st[i]
  1467. if (i_end > end)
  1468. { st.splice(i, 1, end, st[i+1], i_end) }
  1469. i += 2
  1470. at = Math.min(end, i_end)
  1471. }
  1472. if (!style) { return }
  1473. if (overlay.opaque) {
  1474. st.splice(start, i - start, end, "overlay " + style)
  1475. i = start + 2
  1476. } else {
  1477. for (; start < i; start += 2) {
  1478. var cur = st[start+1]
  1479. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1480. }
  1481. }
  1482. }, lineClasses)
  1483. };
  1484. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1485. context.state = state
  1486. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1487. }
  1488. function getLineStyles(cm, line, updateFrontier) {
  1489. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1490. var context = getContextBefore(cm, lineNo(line))
  1491. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
  1492. var result = highlightLine(cm, line, context)
  1493. if (resetState) { context.state = resetState }
  1494. line.stateAfter = context.save(!resetState)
  1495. line.styles = result.styles
  1496. if (result.classes) { line.styleClasses = result.classes }
  1497. else if (line.styleClasses) { line.styleClasses = null }
  1498. if (updateFrontier === cm.doc.highlightFrontier)
  1499. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) }
  1500. }
  1501. return line.styles
  1502. }
  1503. function getContextBefore(cm, n, precise) {
  1504. var doc = cm.doc, display = cm.display
  1505. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1506. var start = findStartLine(cm, n, precise)
  1507. var saved = start > doc.first && getLine(doc, start - 1).stateAfter
  1508. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
  1509. doc.iter(start, n, function (line) {
  1510. processLine(cm, line.text, context)
  1511. var pos = context.line
  1512. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null
  1513. context.nextLine()
  1514. })
  1515. if (precise) { doc.modeFrontier = context.line }
  1516. return context
  1517. }
  1518. // Lightweight form of highlight -- proceed over this line and
  1519. // update state, but don't save a style array. Used for lines that
  1520. // aren't currently visible.
  1521. function processLine(cm, text, context, startAt) {
  1522. var mode = cm.doc.mode
  1523. var stream = new StringStream(text, cm.options.tabSize, context)
  1524. stream.start = stream.pos = startAt || 0
  1525. if (text == "") { callBlankLine(mode, context.state) }
  1526. while (!stream.eol()) {
  1527. readToken(mode, stream, context.state)
  1528. stream.start = stream.pos
  1529. }
  1530. }
  1531. function callBlankLine(mode, state) {
  1532. if (mode.blankLine) { return mode.blankLine(state) }
  1533. if (!mode.innerMode) { return }
  1534. var inner = innerMode(mode, state)
  1535. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1536. }
  1537. function readToken(mode, stream, state, inner) {
  1538. for (var i = 0; i < 10; i++) {
  1539. if (inner) { inner[0] = innerMode(mode, state).mode }
  1540. var style = mode.token(stream, state)
  1541. if (stream.pos > stream.start) { return style }
  1542. }
  1543. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1544. }
  1545. var Token = function(stream, type, state) {
  1546. this.start = stream.start; this.end = stream.pos
  1547. this.string = stream.current()
  1548. this.type = type || null
  1549. this.state = state
  1550. };
  1551. // Utility for getTokenAt and getLineTokens
  1552. function takeToken(cm, pos, precise, asArray) {
  1553. var doc = cm.doc, mode = doc.mode, style
  1554. pos = clipPos(doc, pos)
  1555. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)
  1556. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens
  1557. if (asArray) { tokens = [] }
  1558. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1559. stream.start = stream.pos
  1560. style = readToken(mode, stream, context.state)
  1561. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) }
  1562. }
  1563. return asArray ? tokens : new Token(stream, style, context.state)
  1564. }
  1565. function extractLineClasses(type, output) {
  1566. if (type) { for (;;) {
  1567. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1568. if (!lineClass) { break }
  1569. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1570. var prop = lineClass[1] ? "bgClass" : "textClass"
  1571. if (output[prop] == null)
  1572. { output[prop] = lineClass[2] }
  1573. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1574. { output[prop] += " " + lineClass[2] }
  1575. } }
  1576. return type
  1577. }
  1578. // Run the given mode's parser over a line, calling f for each token.
  1579. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1580. var flattenSpans = mode.flattenSpans
  1581. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1582. var curStart = 0, curStyle = null
  1583. var stream = new StringStream(text, cm.options.tabSize, context), style
  1584. var inner = cm.options.addModeClass && [null]
  1585. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) }
  1586. while (!stream.eol()) {
  1587. if (stream.pos > cm.options.maxHighlightLength) {
  1588. flattenSpans = false
  1589. if (forceToEnd) { processLine(cm, text, context, stream.pos) }
  1590. stream.pos = text.length
  1591. style = null
  1592. } else {
  1593. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
  1594. }
  1595. if (inner) {
  1596. var mName = inner[0].name
  1597. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1598. }
  1599. if (!flattenSpans || curStyle != style) {
  1600. while (curStart < stream.start) {
  1601. curStart = Math.min(stream.start, curStart + 5000)
  1602. f(curStart, curStyle)
  1603. }
  1604. curStyle = style
  1605. }
  1606. stream.start = stream.pos
  1607. }
  1608. while (curStart < stream.pos) {
  1609. // Webkit seems to refuse to render text nodes longer than 57444
  1610. // characters, and returns inaccurate measurements in nodes
  1611. // starting around 5000 chars.
  1612. var pos = Math.min(stream.pos, curStart + 5000)
  1613. f(pos, curStyle)
  1614. curStart = pos
  1615. }
  1616. }
  1617. // Finds the line to start with when starting a parse. Tries to
  1618. // find a line with a stateAfter, so that it can start with a
  1619. // valid state. If that fails, it returns the line with the
  1620. // smallest indentation, which tends to need the least context to
  1621. // parse correctly.
  1622. function findStartLine(cm, n, precise) {
  1623. var minindent, minline, doc = cm.doc
  1624. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1625. for (var search = n; search > lim; --search) {
  1626. if (search <= doc.first) { return doc.first }
  1627. var line = getLine(doc, search - 1), after = line.stateAfter
  1628. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1629. { return search }
  1630. var indented = countColumn(line.text, null, cm.options.tabSize)
  1631. if (minline == null || minindent > indented) {
  1632. minline = search - 1
  1633. minindent = indented
  1634. }
  1635. }
  1636. return minline
  1637. }
  1638. function retreatFrontier(doc, n) {
  1639. doc.modeFrontier = Math.min(doc.modeFrontier, n)
  1640. if (doc.highlightFrontier < n - 10) { return }
  1641. var start = doc.first
  1642. for (var line = n - 1; line > start; line--) {
  1643. var saved = getLine(doc, line).stateAfter
  1644. // change is on 3
  1645. // state on line 1 looked ahead 2 -- so saw 3
  1646. // test 1 + 2 < 3 should cover this
  1647. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1648. start = line + 1
  1649. break
  1650. }
  1651. }
  1652. doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
  1653. }
  1654. // LINE DATA STRUCTURE
  1655. // Line objects. These hold state related to a line, including
  1656. // highlighting info (the styles array).
  1657. var Line = function(text, markedSpans, estimateHeight) {
  1658. this.text = text
  1659. attachMarkedSpans(this, markedSpans)
  1660. this.height = estimateHeight ? estimateHeight(this) : 1
  1661. };
  1662. Line.prototype.lineNo = function () { return lineNo(this) };
  1663. eventMixin(Line)
  1664. // Change the content (text, markers) of a line. Automatically
  1665. // invalidates cached information and tries to re-estimate the
  1666. // line's height.
  1667. function updateLine(line, text, markedSpans, estimateHeight) {
  1668. line.text = text
  1669. if (line.stateAfter) { line.stateAfter = null }
  1670. if (line.styles) { line.styles = null }
  1671. if (line.order != null) { line.order = null }
  1672. detachMarkedSpans(line)
  1673. attachMarkedSpans(line, markedSpans)
  1674. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1675. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1676. }
  1677. // Detach a line from the document tree and its markers.
  1678. function cleanUpLine(line) {
  1679. line.parent = null
  1680. detachMarkedSpans(line)
  1681. }
  1682. // Convert a style as returned by a mode (either null, or a string
  1683. // containing one or more styles) to a CSS style. This is cached,
  1684. // and also looks for line-wide styles.
  1685. var styleToClassCache = {};
  1686. var styleToClassCacheWithMode = {};
  1687. function interpretTokenStyle(style, options) {
  1688. if (!style || /^\s*$/.test(style)) { return null }
  1689. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1690. return cache[style] ||
  1691. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1692. }
  1693. // Render the DOM representation of the text of a line. Also builds
  1694. // up a 'line map', which points at the DOM nodes that represent
  1695. // specific stretches of text, and is used by the measuring code.
  1696. // The returned object contains the DOM node, this map, and
  1697. // information about line-wide styles that were set by the mode.
  1698. function buildLineContent(cm, lineView) {
  1699. // The padding-right forces the element to have a 'border', which
  1700. // is needed on Webkit to be able to get line-level bounding
  1701. // rectangles for it (in measureChar).
  1702. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null)
  1703. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1704. col: 0, pos: 0, cm: cm,
  1705. trailingSpace: false,
  1706. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1707. lineView.measure = {}
  1708. // Iterate over the logical lines that make up this visual line.
  1709. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1710. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1711. builder.pos = 0
  1712. builder.addToken = buildToken
  1713. // Optionally wire in some hacks into the token-rendering
  1714. // algorithm, to deal with browser quirks.
  1715. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1716. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1717. builder.map = []
  1718. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1719. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1720. if (line.styleClasses) {
  1721. if (line.styleClasses.bgClass)
  1722. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1723. if (line.styleClasses.textClass)
  1724. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1725. }
  1726. // Ensure at least a single node is present, for measuring.
  1727. if (builder.map.length == 0)
  1728. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1729. // Store the map and a cache object for the current logical line
  1730. if (i == 0) {
  1731. lineView.measure.map = builder.map
  1732. lineView.measure.cache = {}
  1733. } else {
  1734. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1735. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1736. }
  1737. }
  1738. // See issue #2901
  1739. if (webkit) {
  1740. var last = builder.content.lastChild
  1741. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1742. { builder.content.className = "cm-tab-wrap-hack" }
  1743. }
  1744. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1745. if (builder.pre.className)
  1746. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1747. return builder
  1748. }
  1749. function defaultSpecialCharPlaceholder(ch) {
  1750. var token = elt("span", "\u2022", "cm-invalidchar")
  1751. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1752. token.setAttribute("aria-label", token.title)
  1753. return token
  1754. }
  1755. // Build up the DOM representation for a single token, and add it to
  1756. // the line map. Takes care to render special characters separately.
  1757. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1758. if (!text) { return }
  1759. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1760. var special = builder.cm.state.specialChars, mustWrap = false
  1761. var content
  1762. if (!special.test(text)) {
  1763. builder.col += text.length
  1764. content = document.createTextNode(displayText)
  1765. builder.map.push(builder.pos, builder.pos + text.length, content)
  1766. if (ie && ie_version < 9) { mustWrap = true }
  1767. builder.pos += text.length
  1768. } else {
  1769. content = document.createDocumentFragment()
  1770. var pos = 0
  1771. while (true) {
  1772. special.lastIndex = pos
  1773. var m = special.exec(text)
  1774. var skipped = m ? m.index - pos : text.length - pos
  1775. if (skipped) {
  1776. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1777. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1778. else { content.appendChild(txt) }
  1779. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1780. builder.col += skipped
  1781. builder.pos += skipped
  1782. }
  1783. if (!m) { break }
  1784. pos += skipped + 1
  1785. var txt$1 = (void 0)
  1786. if (m[0] == "\t") {
  1787. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1788. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1789. txt$1.setAttribute("role", "presentation")
  1790. txt$1.setAttribute("cm-text", "\t")
  1791. builder.col += tabWidth
  1792. } else if (m[0] == "\r" || m[0] == "\n") {
  1793. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1794. txt$1.setAttribute("cm-text", m[0])
  1795. builder.col += 1
  1796. } else {
  1797. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1798. txt$1.setAttribute("cm-text", m[0])
  1799. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1800. else { content.appendChild(txt$1) }
  1801. builder.col += 1
  1802. }
  1803. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1804. builder.pos++
  1805. }
  1806. }
  1807. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1808. if (style || startStyle || endStyle || mustWrap || css) {
  1809. var fullStyle = style || ""
  1810. if (startStyle) { fullStyle += startStyle }
  1811. if (endStyle) { fullStyle += endStyle }
  1812. var token = elt("span", [content], fullStyle, css)
  1813. if (title) { token.title = title }
  1814. return builder.content.appendChild(token)
  1815. }
  1816. builder.content.appendChild(content)
  1817. }
  1818. function splitSpaces(text, trailingBefore) {
  1819. if (text.length > 1 && !/ /.test(text)) { return text }
  1820. var spaceBefore = trailingBefore, result = ""
  1821. for (var i = 0; i < text.length; i++) {
  1822. var ch = text.charAt(i)
  1823. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1824. { ch = "\u00a0" }
  1825. result += ch
  1826. spaceBefore = ch == " "
  1827. }
  1828. return result
  1829. }
  1830. // Work around nonsense dimensions being reported for stretches of
  1831. // right-to-left text.
  1832. function buildTokenBadBidi(inner, order) {
  1833. return function (builder, text, style, startStyle, endStyle, title, css) {
  1834. style = style ? style + " cm-force-border" : "cm-force-border"
  1835. var start = builder.pos, end = start + text.length
  1836. for (;;) {
  1837. // Find the part that overlaps with the start of this text
  1838. var part = (void 0)
  1839. for (var i = 0; i < order.length; i++) {
  1840. part = order[i]
  1841. if (part.to > start && part.from <= start) { break }
  1842. }
  1843. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1844. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1845. startStyle = null
  1846. text = text.slice(part.to - start)
  1847. start = part.to
  1848. }
  1849. }
  1850. }
  1851. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1852. var widget = !ignoreWidget && marker.widgetNode
  1853. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1854. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1855. if (!widget)
  1856. { widget = builder.content.appendChild(document.createElement("span")) }
  1857. widget.setAttribute("cm-marker", marker.id)
  1858. }
  1859. if (widget) {
  1860. builder.cm.display.input.setUneditable(widget)
  1861. builder.content.appendChild(widget)
  1862. }
  1863. builder.pos += size
  1864. builder.trailingSpace = false
  1865. }
  1866. // Outputs a number of spans to make up a line, taking highlighting
  1867. // and marked text into account.
  1868. function insertLineContent(line, builder, styles) {
  1869. var spans = line.markedSpans, allText = line.text, at = 0
  1870. if (!spans) {
  1871. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1872. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1873. return
  1874. }
  1875. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1876. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1877. for (;;) {
  1878. if (nextChange == pos) { // Update current marker set
  1879. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1880. collapsed = null; nextChange = Infinity
  1881. var foundBookmarks = [], endStyles = (void 0)
  1882. for (var j = 0; j < spans.length; ++j) {
  1883. var sp = spans[j], m = sp.marker
  1884. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1885. foundBookmarks.push(m)
  1886. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1887. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1888. nextChange = sp.to
  1889. spanEndStyle = ""
  1890. }
  1891. if (m.className) { spanStyle += " " + m.className }
  1892. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1893. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1894. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1895. if (m.title && !title) { title = m.title }
  1896. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1897. { collapsed = sp }
  1898. } else if (sp.from > pos && nextChange > sp.from) {
  1899. nextChange = sp.from
  1900. }
  1901. }
  1902. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1903. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1904. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1905. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1906. if (collapsed && (collapsed.from || 0) == pos) {
  1907. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1908. collapsed.marker, collapsed.from == null)
  1909. if (collapsed.to == null) { return }
  1910. if (collapsed.to == pos) { collapsed = false }
  1911. }
  1912. }
  1913. if (pos >= len) { break }
  1914. var upto = Math.min(len, nextChange)
  1915. while (true) {
  1916. if (text) {
  1917. var end = pos + text.length
  1918. if (!collapsed) {
  1919. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1920. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1921. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1922. }
  1923. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1924. pos = end
  1925. spanStartStyle = ""
  1926. }
  1927. text = allText.slice(at, at = styles[i++])
  1928. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1929. }
  1930. }
  1931. }
  1932. // These objects are used to represent the visible (currently drawn)
  1933. // part of the document. A LineView may correspond to multiple
  1934. // logical lines, if those are connected by collapsed ranges.
  1935. function LineView(doc, line, lineN) {
  1936. // The starting line
  1937. this.line = line
  1938. // Continuing lines, if any
  1939. this.rest = visualLineContinued(line)
  1940. // Number of logical lines in this visual line
  1941. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1942. this.node = this.text = null
  1943. this.hidden = lineIsHidden(doc, line)
  1944. }
  1945. // Create a range of LineView objects for the given lines.
  1946. function buildViewArray(cm, from, to) {
  1947. var array = [], nextPos
  1948. for (var pos = from; pos < to; pos = nextPos) {
  1949. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1950. nextPos = pos + view.size
  1951. array.push(view)
  1952. }
  1953. return array
  1954. }
  1955. var operationGroup = null
  1956. function pushOperation(op) {
  1957. if (operationGroup) {
  1958. operationGroup.ops.push(op)
  1959. } else {
  1960. op.ownsGroup = operationGroup = {
  1961. ops: [op],
  1962. delayedCallbacks: []
  1963. }
  1964. }
  1965. }
  1966. function fireCallbacksForOps(group) {
  1967. // Calls delayed callbacks and cursorActivity handlers until no
  1968. // new ones appear
  1969. var callbacks = group.delayedCallbacks, i = 0
  1970. do {
  1971. for (; i < callbacks.length; i++)
  1972. { callbacks[i].call(null) }
  1973. for (var j = 0; j < group.ops.length; j++) {
  1974. var op = group.ops[j]
  1975. if (op.cursorActivityHandlers)
  1976. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1977. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1978. }
  1979. } while (i < callbacks.length)
  1980. }
  1981. function finishOperation(op, endCb) {
  1982. var group = op.ownsGroup
  1983. if (!group) { return }
  1984. try { fireCallbacksForOps(group) }
  1985. finally {
  1986. operationGroup = null
  1987. endCb(group)
  1988. }
  1989. }
  1990. var orphanDelayedCallbacks = null
  1991. // Often, we want to signal events at a point where we are in the
  1992. // middle of some work, but don't want the handler to start calling
  1993. // other methods on the editor, which might be in an inconsistent
  1994. // state or simply not expect any other events to happen.
  1995. // signalLater looks whether there are any handlers, and schedules
  1996. // them to be executed when the last operation ends, or, if no
  1997. // operation is active, when a timeout fires.
  1998. function signalLater(emitter, type /*, values...*/) {
  1999. var arr = getHandlers(emitter, type)
  2000. if (!arr.length) { return }
  2001. var args = Array.prototype.slice.call(arguments, 2), list
  2002. if (operationGroup) {
  2003. list = operationGroup.delayedCallbacks
  2004. } else if (orphanDelayedCallbacks) {
  2005. list = orphanDelayedCallbacks
  2006. } else {
  2007. list = orphanDelayedCallbacks = []
  2008. setTimeout(fireOrphanDelayed, 0)
  2009. }
  2010. var loop = function ( i ) {
  2011. list.push(function () { return arr[i].apply(null, args); })
  2012. };
  2013. for (var i = 0; i < arr.length; ++i)
  2014. loop( i );
  2015. }
  2016. function fireOrphanDelayed() {
  2017. var delayed = orphanDelayedCallbacks
  2018. orphanDelayedCallbacks = null
  2019. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  2020. }
  2021. // When an aspect of a line changes, a string is added to
  2022. // lineView.changes. This updates the relevant part of the line's
  2023. // DOM structure.
  2024. function updateLineForChanges(cm, lineView, lineN, dims) {
  2025. for (var j = 0; j < lineView.changes.length; j++) {
  2026. var type = lineView.changes[j]
  2027. if (type == "text") { updateLineText(cm, lineView) }
  2028. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  2029. else if (type == "class") { updateLineClasses(cm, lineView) }
  2030. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  2031. }
  2032. lineView.changes = null
  2033. }
  2034. // Lines with gutter elements, widgets or a background class need to
  2035. // be wrapped, and have the extra elements added to the wrapper div
  2036. function ensureLineWrapped(lineView) {
  2037. if (lineView.node == lineView.text) {
  2038. lineView.node = elt("div", null, null, "position: relative")
  2039. if (lineView.text.parentNode)
  2040. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  2041. lineView.node.appendChild(lineView.text)
  2042. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  2043. }
  2044. return lineView.node
  2045. }
  2046. function updateLineBackground(cm, lineView) {
  2047. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  2048. if (cls) { cls += " CodeMirror-linebackground" }
  2049. if (lineView.background) {
  2050. if (cls) { lineView.background.className = cls }
  2051. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  2052. } else if (cls) {
  2053. var wrap = ensureLineWrapped(lineView)
  2054. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  2055. cm.display.input.setUneditable(lineView.background)
  2056. }
  2057. }
  2058. // Wrapper around buildLineContent which will reuse the structure
  2059. // in display.externalMeasured when possible.
  2060. function getLineContent(cm, lineView) {
  2061. var ext = cm.display.externalMeasured
  2062. if (ext && ext.line == lineView.line) {
  2063. cm.display.externalMeasured = null
  2064. lineView.measure = ext.measure
  2065. return ext.built
  2066. }
  2067. return buildLineContent(cm, lineView)
  2068. }
  2069. // Redraw the line's text. Interacts with the background and text
  2070. // classes because the mode may output tokens that influence these
  2071. // classes.
  2072. function updateLineText(cm, lineView) {
  2073. var cls = lineView.text.className
  2074. var built = getLineContent(cm, lineView)
  2075. if (lineView.text == lineView.node) { lineView.node = built.pre }
  2076. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2077. lineView.text = built.pre
  2078. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2079. lineView.bgClass = built.bgClass
  2080. lineView.textClass = built.textClass
  2081. updateLineClasses(cm, lineView)
  2082. } else if (cls) {
  2083. lineView.text.className = cls
  2084. }
  2085. }
  2086. function updateLineClasses(cm, lineView) {
  2087. updateLineBackground(cm, lineView)
  2088. if (lineView.line.wrapClass)
  2089. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  2090. else if (lineView.node != lineView.text)
  2091. { lineView.node.className = "" }
  2092. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  2093. lineView.text.className = textClass || ""
  2094. }
  2095. function updateLineGutter(cm, lineView, lineN, dims) {
  2096. if (lineView.gutter) {
  2097. lineView.node.removeChild(lineView.gutter)
  2098. lineView.gutter = null
  2099. }
  2100. if (lineView.gutterBackground) {
  2101. lineView.node.removeChild(lineView.gutterBackground)
  2102. lineView.gutterBackground = null
  2103. }
  2104. if (lineView.line.gutterClass) {
  2105. var wrap = ensureLineWrapped(lineView)
  2106. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2107. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  2108. cm.display.input.setUneditable(lineView.gutterBackground)
  2109. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2110. }
  2111. var markers = lineView.line.gutterMarkers
  2112. if (cm.options.lineNumbers || markers) {
  2113. var wrap$1 = ensureLineWrapped(lineView)
  2114. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  2115. cm.display.input.setUneditable(gutterWrap)
  2116. wrap$1.insertBefore(gutterWrap, lineView.text)
  2117. if (lineView.line.gutterClass)
  2118. { gutterWrap.className += " " + lineView.line.gutterClass }
  2119. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2120. { lineView.lineNumber = gutterWrap.appendChild(
  2121. elt("div", lineNumberFor(cm.options, lineN),
  2122. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2123. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2124. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2125. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2126. if (found)
  2127. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2128. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2129. } }
  2130. }
  2131. }
  2132. function updateLineWidgets(cm, lineView, dims) {
  2133. if (lineView.alignable) { lineView.alignable = null }
  2134. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2135. next = node.nextSibling
  2136. if (node.className == "CodeMirror-linewidget")
  2137. { lineView.node.removeChild(node) }
  2138. }
  2139. insertLineWidgets(cm, lineView, dims)
  2140. }
  2141. // Build a line's DOM representation from scratch
  2142. function buildLineElement(cm, lineView, lineN, dims) {
  2143. var built = getLineContent(cm, lineView)
  2144. lineView.text = lineView.node = built.pre
  2145. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2146. if (built.textClass) { lineView.textClass = built.textClass }
  2147. updateLineClasses(cm, lineView)
  2148. updateLineGutter(cm, lineView, lineN, dims)
  2149. insertLineWidgets(cm, lineView, dims)
  2150. return lineView.node
  2151. }
  2152. // A lineView may contain multiple logical lines (when merged by
  2153. // collapsed spans). The widgets for all of them need to be drawn.
  2154. function insertLineWidgets(cm, lineView, dims) {
  2155. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2156. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2157. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2158. }
  2159. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2160. if (!line.widgets) { return }
  2161. var wrap = ensureLineWrapped(lineView)
  2162. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2163. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2164. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2165. positionLineWidget(widget, node, lineView, dims)
  2166. cm.display.input.setUneditable(node)
  2167. if (allowAbove && widget.above)
  2168. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2169. else
  2170. { wrap.appendChild(node) }
  2171. signalLater(widget, "redraw")
  2172. }
  2173. }
  2174. function positionLineWidget(widget, node, lineView, dims) {
  2175. if (widget.noHScroll) {
  2176. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2177. var width = dims.wrapperWidth
  2178. node.style.left = dims.fixedPos + "px"
  2179. if (!widget.coverGutter) {
  2180. width -= dims.gutterTotalWidth
  2181. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2182. }
  2183. node.style.width = width + "px"
  2184. }
  2185. if (widget.coverGutter) {
  2186. node.style.zIndex = 5
  2187. node.style.position = "relative"
  2188. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2189. }
  2190. }
  2191. function widgetHeight(widget) {
  2192. if (widget.height != null) { return widget.height }
  2193. var cm = widget.doc.cm
  2194. if (!cm) { return 0 }
  2195. if (!contains(document.body, widget.node)) {
  2196. var parentStyle = "position: relative;"
  2197. if (widget.coverGutter)
  2198. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2199. if (widget.noHScroll)
  2200. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2201. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2202. }
  2203. return widget.height = widget.node.parentNode.offsetHeight
  2204. }
  2205. // Return true when the given mouse event happened in a widget
  2206. function eventInWidget(display, e) {
  2207. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2208. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2209. (n.parentNode == display.sizer && n != display.mover))
  2210. { return true }
  2211. }
  2212. }
  2213. // POSITION MEASUREMENT
  2214. function paddingTop(display) {return display.lineSpace.offsetTop}
  2215. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2216. function paddingH(display) {
  2217. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2218. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2219. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2220. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2221. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2222. return data
  2223. }
  2224. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2225. function displayWidth(cm) {
  2226. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2227. }
  2228. function displayHeight(cm) {
  2229. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2230. }
  2231. // Ensure the lineView.wrapping.heights array is populated. This is
  2232. // an array of bottom offsets for the lines that make up a drawn
  2233. // line. When lineWrapping is on, there might be more than one
  2234. // height.
  2235. function ensureLineHeights(cm, lineView, rect) {
  2236. var wrapping = cm.options.lineWrapping
  2237. var curWidth = wrapping && displayWidth(cm)
  2238. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2239. var heights = lineView.measure.heights = []
  2240. if (wrapping) {
  2241. lineView.measure.width = curWidth
  2242. var rects = lineView.text.firstChild.getClientRects()
  2243. for (var i = 0; i < rects.length - 1; i++) {
  2244. var cur = rects[i], next = rects[i + 1]
  2245. if (Math.abs(cur.bottom - next.bottom) > 2)
  2246. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2247. }
  2248. }
  2249. heights.push(rect.bottom - rect.top)
  2250. }
  2251. }
  2252. // Find a line map (mapping character offsets to text nodes) and a
  2253. // measurement cache for the given line number. (A line view might
  2254. // contain multiple lines when collapsed ranges are present.)
  2255. function mapFromLineView(lineView, line, lineN) {
  2256. if (lineView.line == line)
  2257. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2258. for (var i = 0; i < lineView.rest.length; i++)
  2259. { if (lineView.rest[i] == line)
  2260. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2261. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2262. { if (lineNo(lineView.rest[i$1]) > lineN)
  2263. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2264. }
  2265. // Render a line into the hidden node display.externalMeasured. Used
  2266. // when measurement is needed for a line that's not in the viewport.
  2267. function updateExternalMeasurement(cm, line) {
  2268. line = visualLine(line)
  2269. var lineN = lineNo(line)
  2270. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2271. view.lineN = lineN
  2272. var built = view.built = buildLineContent(cm, view)
  2273. view.text = built.pre
  2274. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2275. return view
  2276. }
  2277. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2278. // for a given character.
  2279. function measureChar(cm, line, ch, bias) {
  2280. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2281. }
  2282. // Find a line view that corresponds to the given line number.
  2283. function findViewForLine(cm, lineN) {
  2284. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2285. { return cm.display.view[findViewIndex(cm, lineN)] }
  2286. var ext = cm.display.externalMeasured
  2287. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2288. { return ext }
  2289. }
  2290. // Measurement can be split in two steps, the set-up work that
  2291. // applies to the whole line, and the measurement of the actual
  2292. // character. Functions like coordsChar, that need to do a lot of
  2293. // measurements in a row, can thus ensure that the set-up work is
  2294. // only done once.
  2295. function prepareMeasureForLine(cm, line) {
  2296. var lineN = lineNo(line)
  2297. var view = findViewForLine(cm, lineN)
  2298. if (view && !view.text) {
  2299. view = null
  2300. } else if (view && view.changes) {
  2301. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2302. cm.curOp.forceUpdate = true
  2303. }
  2304. if (!view)
  2305. { view = updateExternalMeasurement(cm, line) }
  2306. var info = mapFromLineView(view, line, lineN)
  2307. return {
  2308. line: line, view: view, rect: null,
  2309. map: info.map, cache: info.cache, before: info.before,
  2310. hasHeights: false
  2311. }
  2312. }
  2313. // Given a prepared measurement object, measures the position of an
  2314. // actual character (or fetches it from the cache).
  2315. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2316. if (prepared.before) { ch = -1 }
  2317. var key = ch + (bias || ""), found
  2318. if (prepared.cache.hasOwnProperty(key)) {
  2319. found = prepared.cache[key]
  2320. } else {
  2321. if (!prepared.rect)
  2322. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2323. if (!prepared.hasHeights) {
  2324. ensureLineHeights(cm, prepared.view, prepared.rect)
  2325. prepared.hasHeights = true
  2326. }
  2327. found = measureCharInner(cm, prepared, ch, bias)
  2328. if (!found.bogus) { prepared.cache[key] = found }
  2329. }
  2330. return {left: found.left, right: found.right,
  2331. top: varHeight ? found.rtop : found.top,
  2332. bottom: varHeight ? found.rbottom : found.bottom}
  2333. }
  2334. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2335. function nodeAndOffsetInLineMap(map, ch, bias) {
  2336. var node, start, end, collapse, mStart, mEnd
  2337. // First, search the line map for the text node corresponding to,
  2338. // or closest to, the target character.
  2339. for (var i = 0; i < map.length; i += 3) {
  2340. mStart = map[i]
  2341. mEnd = map[i + 1]
  2342. if (ch < mStart) {
  2343. start = 0; end = 1
  2344. collapse = "left"
  2345. } else if (ch < mEnd) {
  2346. start = ch - mStart
  2347. end = start + 1
  2348. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2349. end = mEnd - mStart
  2350. start = end - 1
  2351. if (ch >= mEnd) { collapse = "right" }
  2352. }
  2353. if (start != null) {
  2354. node = map[i + 2]
  2355. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2356. { collapse = bias }
  2357. if (bias == "left" && start == 0)
  2358. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2359. node = map[(i -= 3) + 2]
  2360. collapse = "left"
  2361. } }
  2362. if (bias == "right" && start == mEnd - mStart)
  2363. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2364. node = map[(i += 3) + 2]
  2365. collapse = "right"
  2366. } }
  2367. break
  2368. }
  2369. }
  2370. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2371. }
  2372. function getUsefulRect(rects, bias) {
  2373. var rect = nullRect
  2374. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2375. if ((rect = rects[i]).left != rect.right) { break }
  2376. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2377. if ((rect = rects[i$1]).left != rect.right) { break }
  2378. } }
  2379. return rect
  2380. }
  2381. function measureCharInner(cm, prepared, ch, bias) {
  2382. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2383. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2384. var rect
  2385. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2386. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2387. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2388. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2389. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2390. { rect = node.parentNode.getBoundingClientRect() }
  2391. else
  2392. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2393. if (rect.left || rect.right || start == 0) { break }
  2394. end = start
  2395. start = start - 1
  2396. collapse = "right"
  2397. }
  2398. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2399. } else { // If it is a widget, simply get the box for the whole widget.
  2400. if (start > 0) { collapse = bias = "right" }
  2401. var rects
  2402. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2403. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2404. else
  2405. { rect = node.getBoundingClientRect() }
  2406. }
  2407. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2408. var rSpan = node.parentNode.getClientRects()[0]
  2409. if (rSpan)
  2410. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2411. else
  2412. { rect = nullRect }
  2413. }
  2414. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2415. var mid = (rtop + rbot) / 2
  2416. var heights = prepared.view.measure.heights
  2417. var i = 0
  2418. for (; i < heights.length - 1; i++)
  2419. { if (mid < heights[i]) { break } }
  2420. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2421. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2422. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2423. top: top, bottom: bot}
  2424. if (!rect.left && !rect.right) { result.bogus = true }
  2425. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2426. return result
  2427. }
  2428. // Work around problem with bounding client rects on ranges being
  2429. // returned incorrectly when zoomed on IE10 and below.
  2430. function maybeUpdateRectForZooming(measure, rect) {
  2431. if (!window.screen || screen.logicalXDPI == null ||
  2432. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2433. { return rect }
  2434. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2435. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2436. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2437. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2438. }
  2439. function clearLineMeasurementCacheFor(lineView) {
  2440. if (lineView.measure) {
  2441. lineView.measure.cache = {}
  2442. lineView.measure.heights = null
  2443. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2444. { lineView.measure.caches[i] = {} } }
  2445. }
  2446. }
  2447. function clearLineMeasurementCache(cm) {
  2448. cm.display.externalMeasure = null
  2449. removeChildren(cm.display.lineMeasure)
  2450. for (var i = 0; i < cm.display.view.length; i++)
  2451. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2452. }
  2453. function clearCaches(cm) {
  2454. clearLineMeasurementCache(cm)
  2455. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2456. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2457. cm.display.lineNumChars = null
  2458. }
  2459. function pageScrollX() {
  2460. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2461. // which causes page_Offset and bounding client rects to use
  2462. // different reference viewports and invalidate our calculations.
  2463. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2464. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2465. }
  2466. function pageScrollY() {
  2467. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2468. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2469. }
  2470. // Converts a {top, bottom, left, right} box from line-local
  2471. // coordinates into another coordinate system. Context may be one of
  2472. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2473. // or "page".
  2474. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2475. if (!includeWidgets && lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) {
  2476. var size = widgetHeight(lineObj.widgets[i])
  2477. rect.top += size; rect.bottom += size
  2478. } } }
  2479. if (context == "line") { return rect }
  2480. if (!context) { context = "local" }
  2481. var yOff = heightAtLine(lineObj)
  2482. if (context == "local") { yOff += paddingTop(cm.display) }
  2483. else { yOff -= cm.display.viewOffset }
  2484. if (context == "page" || context == "window") {
  2485. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2486. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2487. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2488. rect.left += xOff; rect.right += xOff
  2489. }
  2490. rect.top += yOff; rect.bottom += yOff
  2491. return rect
  2492. }
  2493. // Coverts a box from "div" coords to another coordinate system.
  2494. // Context may be "window", "page", "div", or "local"./null.
  2495. function fromCoordSystem(cm, coords, context) {
  2496. if (context == "div") { return coords }
  2497. var left = coords.left, top = coords.top
  2498. // First move into "page" coordinate system
  2499. if (context == "page") {
  2500. left -= pageScrollX()
  2501. top -= pageScrollY()
  2502. } else if (context == "local" || !context) {
  2503. var localBox = cm.display.sizer.getBoundingClientRect()
  2504. left += localBox.left
  2505. top += localBox.top
  2506. }
  2507. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2508. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2509. }
  2510. function charCoords(cm, pos, context, lineObj, bias) {
  2511. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2512. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2513. }
  2514. // Returns a box for a given cursor position, which may have an
  2515. // 'other' property containing the position of the secondary cursor
  2516. // on a bidi boundary.
  2517. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2518. // and after `char - 1` in writing order of `char - 1`
  2519. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2520. // and before `char` in writing order of `char`
  2521. // Examples (upper-case letters are RTL, lower-case are LTR):
  2522. // Pos(0, 1, ...)
  2523. // before after
  2524. // ab a|b a|b
  2525. // aB a|B aB|
  2526. // Ab |Ab A|b
  2527. // AB B|A B|A
  2528. // Every position after the last character on a line is considered to stick
  2529. // to the last character on the line.
  2530. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2531. lineObj = lineObj || getLine(cm.doc, pos.line)
  2532. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2533. function get(ch, right) {
  2534. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2535. if (right) { m.left = m.right; } else { m.right = m.left }
  2536. return intoCoordSystem(cm, lineObj, m, context)
  2537. }
  2538. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
  2539. if (ch >= lineObj.text.length) {
  2540. ch = lineObj.text.length
  2541. sticky = "before"
  2542. } else if (ch <= 0) {
  2543. ch = 0
  2544. sticky = "after"
  2545. }
  2546. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2547. function getBidi(ch, partPos, invert) {
  2548. var part = order[partPos], right = (part.level % 2) != 0
  2549. return get(invert ? ch - 1 : ch, right != invert)
  2550. }
  2551. var partPos = getBidiPartAt(order, ch, sticky)
  2552. var other = bidiOther
  2553. var val = getBidi(ch, partPos, sticky == "before")
  2554. if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
  2555. return val
  2556. }
  2557. // Used to cheaply estimate the coordinates for a position. Used for
  2558. // intermediate scroll updates.
  2559. function estimateCoords(cm, pos) {
  2560. var left = 0
  2561. pos = clipPos(cm.doc, pos)
  2562. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2563. var lineObj = getLine(cm.doc, pos.line)
  2564. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2565. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2566. }
  2567. // Positions returned by coordsChar contain some extra information.
  2568. // xRel is the relative x position of the input coordinates compared
  2569. // to the found position (so xRel > 0 means the coordinates are to
  2570. // the right of the character position, for example). When outside
  2571. // is true, that means the coordinates lie outside the line's
  2572. // vertical range.
  2573. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2574. var pos = Pos(line, ch, sticky)
  2575. pos.xRel = xRel
  2576. if (outside) { pos.outside = true }
  2577. return pos
  2578. }
  2579. // Compute the character position closest to the given coordinates.
  2580. // Input must be lineSpace-local ("div" coordinate system).
  2581. function coordsChar(cm, x, y) {
  2582. var doc = cm.doc
  2583. y += cm.display.viewOffset
  2584. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2585. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2586. if (lineN > last)
  2587. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2588. if (x < 0) { x = 0 }
  2589. var lineObj = getLine(doc, lineN)
  2590. for (;;) {
  2591. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2592. var merged = collapsedSpanAtEnd(lineObj)
  2593. var mergedPos = merged && merged.find(0, true)
  2594. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2595. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2596. else
  2597. { return found }
  2598. }
  2599. }
  2600. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2601. var measure = function (ch) { return intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line"); }
  2602. var end = lineObj.text.length
  2603. var begin = findFirst(function (ch) { return measure(ch - 1).bottom <= y; }, end, 0)
  2604. end = findFirst(function (ch) { return measure(ch).top > y; }, begin, end)
  2605. return {begin: begin, end: end}
  2606. }
  2607. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2608. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  2609. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2610. }
  2611. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2612. y -= heightAtLine(lineObj)
  2613. var begin = 0, end = lineObj.text.length
  2614. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2615. var pos
  2616. var order = getOrder(lineObj, cm.doc.direction)
  2617. if (order) {
  2618. if (cm.options.lineWrapping) {
  2619. ;var assign;
  2620. ((assign = wrappedLineExtent(cm, lineObj, preparedMeasure, y), begin = assign.begin, end = assign.end, assign))
  2621. }
  2622. pos = new Pos(lineNo, Math.floor(begin + (end - begin) / 2))
  2623. var beginLeft = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left
  2624. var dir = beginLeft < x ? 1 : -1
  2625. var prevDiff, diff = beginLeft - x, prevPos
  2626. var steps = Math.ceil((end - begin) / 4)
  2627. outer: do {
  2628. prevDiff = diff
  2629. prevPos = pos
  2630. var i = 0
  2631. for (; i < steps; ++i) {
  2632. var prevPos$1 = pos
  2633. pos = moveVisually(cm, lineObj, pos, dir)
  2634. if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) {
  2635. pos = prevPos$1
  2636. break outer
  2637. }
  2638. }
  2639. diff = cursorCoords(cm, pos, "line", lineObj, preparedMeasure).left - x
  2640. if (steps > 1) {
  2641. var diff_change_per_step = Math.abs(diff - prevDiff) / steps
  2642. steps = Math.min(steps, Math.ceil(Math.abs(diff) / diff_change_per_step))
  2643. dir = diff < 0 ? 1 : -1
  2644. }
  2645. } while (diff != 0 && (steps > 1 || ((dir < 0) != (diff < 0) && (Math.abs(diff) <= Math.abs(prevDiff)))))
  2646. if (Math.abs(diff) > Math.abs(prevDiff)) {
  2647. if ((diff < 0) == (prevDiff < 0)) { throw new Error("Broke out of infinite loop in coordsCharInner") }
  2648. pos = prevPos
  2649. }
  2650. } else {
  2651. var ch = findFirst(function (ch) {
  2652. var box = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line")
  2653. if (box.top > y) {
  2654. // For the cursor stickiness
  2655. end = Math.min(ch, end)
  2656. return true
  2657. }
  2658. else if (box.bottom <= y) { return false }
  2659. else if (box.left > x) { return true }
  2660. else if (box.right < x) { return false }
  2661. else { return (x - box.left < box.right - x) }
  2662. }, begin, end)
  2663. ch = skipExtendingChars(lineObj.text, ch, 1)
  2664. pos = new Pos(lineNo, ch, ch == end ? "before" : "after")
  2665. }
  2666. var coords = cursorCoords(cm, pos, "line", lineObj, preparedMeasure)
  2667. if (y < coords.top || coords.bottom < y) { pos.outside = true }
  2668. pos.xRel = x < coords.left ? -1 : (x > coords.right ? 1 : 0)
  2669. return pos
  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. var doc = cm.doc, result = {}
  2783. var curFragment = result.cursors = document.createDocumentFragment()
  2784. var selFragment = result.selection = document.createDocumentFragment()
  2785. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2786. if (primary === false && i == doc.sel.primIndex) { continue }
  2787. var range = doc.sel.ranges[i]
  2788. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2789. var collapsed = range.empty()
  2790. if (collapsed || cm.options.showCursorWhenSelecting)
  2791. { drawSelectionCursor(cm, range.head, curFragment) }
  2792. if (!collapsed)
  2793. { drawSelectionRange(cm, range, selFragment) }
  2794. }
  2795. return result
  2796. }
  2797. // Draws a cursor for the given range
  2798. function drawSelectionCursor(cm, head, output) {
  2799. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2800. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2801. cursor.style.left = pos.left + "px"
  2802. cursor.style.top = pos.top + "px"
  2803. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2804. if (pos.other) {
  2805. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2806. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2807. otherCursor.style.display = ""
  2808. otherCursor.style.left = pos.other.left + "px"
  2809. otherCursor.style.top = pos.other.top + "px"
  2810. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2811. }
  2812. }
  2813. // Draws the given range as a highlighted selection
  2814. function drawSelectionRange(cm, range, output) {
  2815. var display = cm.display, doc = cm.doc
  2816. var fragment = document.createDocumentFragment()
  2817. var padding = paddingH(cm.display), leftSide = padding.left
  2818. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2819. function add(left, top, width, bottom) {
  2820. if (top < 0) { top = 0 }
  2821. top = Math.round(top)
  2822. bottom = Math.round(bottom)
  2823. 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")))
  2824. }
  2825. function drawForLine(line, fromArg, toArg) {
  2826. var lineObj = getLine(doc, line)
  2827. var lineLen = lineObj.text.length
  2828. var start, end
  2829. function coords(ch, bias) {
  2830. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2831. }
  2832. iterateBidiSections(getOrder(lineObj, doc.direction), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) {
  2833. var leftPos = coords(from, "left"), rightPos, left, right
  2834. if (from == to) {
  2835. rightPos = leftPos
  2836. left = right = leftPos.left
  2837. } else {
  2838. rightPos = coords(to - 1, "right")
  2839. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp }
  2840. left = leftPos.left
  2841. right = rightPos.right
  2842. }
  2843. if (fromArg == null && from == 0) { left = leftSide }
  2844. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2845. add(left, leftPos.top, null, leftPos.bottom)
  2846. left = leftSide
  2847. if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) }
  2848. }
  2849. if (toArg == null && to == lineLen) { right = rightSide }
  2850. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2851. { start = leftPos }
  2852. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2853. { end = rightPos }
  2854. if (left < leftSide + 1) { left = leftSide }
  2855. add(left, rightPos.top, right - left, rightPos.bottom)
  2856. })
  2857. return {start: start, end: end}
  2858. }
  2859. var sFrom = range.from(), sTo = range.to()
  2860. if (sFrom.line == sTo.line) {
  2861. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2862. } else {
  2863. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2864. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2865. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2866. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2867. if (singleVLine) {
  2868. if (leftEnd.top < rightStart.top - 2) {
  2869. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2870. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2871. } else {
  2872. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2873. }
  2874. }
  2875. if (leftEnd.bottom < rightStart.top)
  2876. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2877. }
  2878. output.appendChild(fragment)
  2879. }
  2880. // Cursor-blinking
  2881. function restartBlink(cm) {
  2882. if (!cm.state.focused) { return }
  2883. var display = cm.display
  2884. clearInterval(display.blinker)
  2885. var on = true
  2886. display.cursorDiv.style.visibility = ""
  2887. if (cm.options.cursorBlinkRate > 0)
  2888. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2889. cm.options.cursorBlinkRate) }
  2890. else if (cm.options.cursorBlinkRate < 0)
  2891. { display.cursorDiv.style.visibility = "hidden" }
  2892. }
  2893. function ensureFocus(cm) {
  2894. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2895. }
  2896. function delayBlurEvent(cm) {
  2897. cm.state.delayingBlurEvent = true
  2898. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2899. cm.state.delayingBlurEvent = false
  2900. onBlur(cm)
  2901. } }, 100)
  2902. }
  2903. function onFocus(cm, e) {
  2904. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2905. if (cm.options.readOnly == "nocursor") { return }
  2906. if (!cm.state.focused) {
  2907. signal(cm, "focus", cm, e)
  2908. cm.state.focused = true
  2909. addClass(cm.display.wrapper, "CodeMirror-focused")
  2910. // This test prevents this from firing when a context
  2911. // menu is closed (since the input reset would kill the
  2912. // select-all detection hack)
  2913. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2914. cm.display.input.reset()
  2915. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2916. }
  2917. cm.display.input.receivedFocus()
  2918. }
  2919. restartBlink(cm)
  2920. }
  2921. function onBlur(cm, e) {
  2922. if (cm.state.delayingBlurEvent) { return }
  2923. if (cm.state.focused) {
  2924. signal(cm, "blur", cm, e)
  2925. cm.state.focused = false
  2926. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2927. }
  2928. clearInterval(cm.display.blinker)
  2929. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2930. }
  2931. // Read the actual heights of the rendered lines, and update their
  2932. // stored heights to match.
  2933. function updateHeightsInViewport(cm) {
  2934. var display = cm.display
  2935. var prevBottom = display.lineDiv.offsetTop
  2936. for (var i = 0; i < display.view.length; i++) {
  2937. var cur = display.view[i], height = (void 0)
  2938. if (cur.hidden) { continue }
  2939. if (ie && ie_version < 8) {
  2940. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2941. height = bot - prevBottom
  2942. prevBottom = bot
  2943. } else {
  2944. var box = cur.node.getBoundingClientRect()
  2945. height = box.bottom - box.top
  2946. }
  2947. var diff = cur.line.height - height
  2948. if (height < 2) { height = textHeight(display) }
  2949. if (diff > .005 || diff < -.005) {
  2950. updateLineHeight(cur.line, height)
  2951. updateWidgetHeight(cur.line)
  2952. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2953. { updateWidgetHeight(cur.rest[j]) } }
  2954. }
  2955. }
  2956. }
  2957. // Read and store the height of line widgets associated with the
  2958. // given line.
  2959. function updateWidgetHeight(line) {
  2960. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i)
  2961. { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } }
  2962. }
  2963. // Compute the lines that are visible in a given viewport (defaults
  2964. // the the current scroll position). viewport may contain top,
  2965. // height, and ensure (see op.scrollToPos) properties.
  2966. function visibleLines(display, doc, viewport) {
  2967. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2968. top = Math.floor(top - paddingTop(display))
  2969. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2970. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2971. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2972. // forces those lines into the viewport (if possible).
  2973. if (viewport && viewport.ensure) {
  2974. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2975. if (ensureFrom < from) {
  2976. from = ensureFrom
  2977. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2978. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2979. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  2980. to = ensureTo
  2981. }
  2982. }
  2983. return {from: from, to: Math.max(to, from + 1)}
  2984. }
  2985. // Re-align line numbers and gutter marks to compensate for
  2986. // horizontal scrolling.
  2987. function alignHorizontally(cm) {
  2988. var display = cm.display, view = display.view
  2989. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  2990. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  2991. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  2992. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  2993. if (cm.options.fixedGutter) {
  2994. if (view[i].gutter)
  2995. { view[i].gutter.style.left = left }
  2996. if (view[i].gutterBackground)
  2997. { view[i].gutterBackground.style.left = left }
  2998. }
  2999. var align = view[i].alignable
  3000. if (align) { for (var j = 0; j < align.length; j++)
  3001. { align[j].style.left = left } }
  3002. } }
  3003. if (cm.options.fixedGutter)
  3004. { display.gutters.style.left = (comp + gutterW) + "px" }
  3005. }
  3006. // Used to ensure that the line number gutter is still the right
  3007. // size for the current document size. Returns true when an update
  3008. // is needed.
  3009. function maybeUpdateLineNumberWidth(cm) {
  3010. if (!cm.options.lineNumbers) { return false }
  3011. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  3012. if (last.length != display.lineNumChars) {
  3013. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3014. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  3015. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  3016. display.lineGutter.style.width = ""
  3017. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  3018. display.lineNumWidth = display.lineNumInnerWidth + padding
  3019. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  3020. display.lineGutter.style.width = display.lineNumWidth + "px"
  3021. updateGutterSpace(cm)
  3022. return true
  3023. }
  3024. return false
  3025. }
  3026. // SCROLLING THINGS INTO VIEW
  3027. // If an editor sits on the top or bottom of the window, partially
  3028. // scrolled out of view, this ensures that the cursor is visible.
  3029. function maybeScrollWindow(cm, rect) {
  3030. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3031. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3032. if (rect.top + box.top < 0) { doScroll = true }
  3033. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3034. if (doScroll != null && !phantom) {
  3035. 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;"))
  3036. cm.display.lineSpace.appendChild(scrollNode)
  3037. scrollNode.scrollIntoView(doScroll)
  3038. cm.display.lineSpace.removeChild(scrollNode)
  3039. }
  3040. }
  3041. // Scroll a given position into view (immediately), verifying that
  3042. // it actually became visible (as line heights are accurately
  3043. // measured, the position of something may 'drift' during drawing).
  3044. function scrollPosIntoView(cm, pos, end, margin) {
  3045. if (margin == null) { margin = 0 }
  3046. var rect
  3047. if (!cm.options.lineWrapping && pos == end) {
  3048. // Set pos and end to the cursor positions around the character pos sticks to
  3049. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3050. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3051. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos
  3052. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos
  3053. }
  3054. for (var limit = 0; limit < 5; limit++) {
  3055. var changed = false
  3056. var coords = cursorCoords(cm, pos)
  3057. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3058. rect = {left: Math.min(coords.left, endCoords.left),
  3059. top: Math.min(coords.top, endCoords.top) - margin,
  3060. right: Math.max(coords.left, endCoords.left),
  3061. bottom: Math.max(coords.bottom, endCoords.bottom) + margin}
  3062. var scrollPos = calculateScrollPos(cm, rect)
  3063. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3064. if (scrollPos.scrollTop != null) {
  3065. updateScrollTop(cm, scrollPos.scrollTop)
  3066. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3067. }
  3068. if (scrollPos.scrollLeft != null) {
  3069. setScrollLeft(cm, scrollPos.scrollLeft)
  3070. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3071. }
  3072. if (!changed) { break }
  3073. }
  3074. return rect
  3075. }
  3076. // Scroll a given set of coordinates into view (immediately).
  3077. function scrollIntoView(cm, rect) {
  3078. var scrollPos = calculateScrollPos(cm, rect)
  3079. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) }
  3080. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3081. }
  3082. // Calculate a new scroll position needed to scroll the given
  3083. // rectangle into view. Returns an object with scrollTop and
  3084. // scrollLeft properties. When these are undefined, the
  3085. // vertical/horizontal position does not need to be adjusted.
  3086. function calculateScrollPos(cm, rect) {
  3087. var display = cm.display, snapMargin = textHeight(cm.display)
  3088. if (rect.top < 0) { rect.top = 0 }
  3089. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3090. var screen = displayHeight(cm), result = {}
  3091. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen }
  3092. var docBottom = cm.doc.height + paddingVert(display)
  3093. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin
  3094. if (rect.top < screentop) {
  3095. result.scrollTop = atTop ? 0 : rect.top
  3096. } else if (rect.bottom > screentop + screen) {
  3097. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
  3098. if (newTop != screentop) { result.scrollTop = newTop }
  3099. }
  3100. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3101. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3102. var tooWide = rect.right - rect.left > screenw
  3103. if (tooWide) { rect.right = rect.left + screenw }
  3104. if (rect.left < 10)
  3105. { result.scrollLeft = 0 }
  3106. else if (rect.left < screenleft)
  3107. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) }
  3108. else if (rect.right > screenw + screenleft - 3)
  3109. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw }
  3110. return result
  3111. }
  3112. // Store a relative adjustment to the scroll position in the current
  3113. // operation (to be applied when the operation finishes).
  3114. function addToScrollTop(cm, top) {
  3115. if (top == null) { return }
  3116. resolveScrollToPos(cm)
  3117. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
  3118. }
  3119. // Make sure that at the end of the operation the current cursor is
  3120. // shown.
  3121. function ensureCursorVisible(cm) {
  3122. resolveScrollToPos(cm)
  3123. var cur = cm.getCursor()
  3124. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}
  3125. }
  3126. function scrollToCoords(cm, x, y) {
  3127. if (x != null || y != null) { resolveScrollToPos(cm) }
  3128. if (x != null) { cm.curOp.scrollLeft = x }
  3129. if (y != null) { cm.curOp.scrollTop = y }
  3130. }
  3131. function scrollToRange(cm, range) {
  3132. resolveScrollToPos(cm)
  3133. cm.curOp.scrollToPos = range
  3134. }
  3135. // When an operation has its scrollToPos property set, and another
  3136. // scroll action is applied before the end of the operation, this
  3137. // 'simulates' scrolling that position into view in a cheap way, so
  3138. // that the effect of intermediate scroll commands is not ignored.
  3139. function resolveScrollToPos(cm) {
  3140. var range = cm.curOp.scrollToPos
  3141. if (range) {
  3142. cm.curOp.scrollToPos = null
  3143. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3144. scrollToCoordsRange(cm, from, to, range.margin)
  3145. }
  3146. }
  3147. function scrollToCoordsRange(cm, from, to, margin) {
  3148. var sPos = calculateScrollPos(cm, {
  3149. left: Math.min(from.left, to.left),
  3150. top: Math.min(from.top, to.top) - margin,
  3151. right: Math.max(from.right, to.right),
  3152. bottom: Math.max(from.bottom, to.bottom) + margin
  3153. })
  3154. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
  3155. }
  3156. // Sync the scrollable area and scrollbars, ensure the viewport
  3157. // covers the visible area.
  3158. function updateScrollTop(cm, val) {
  3159. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3160. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  3161. setScrollTop(cm, val, true)
  3162. if (gecko) { updateDisplaySimple(cm) }
  3163. startWorker(cm, 100)
  3164. }
  3165. function setScrollTop(cm, val, forceScroll) {
  3166. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)
  3167. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3168. cm.doc.scrollTop = val
  3169. cm.display.scrollbars.setScrollTop(val)
  3170. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  3171. }
  3172. // Sync scroller and scrollbar, ensure the gutter elements are
  3173. // aligned.
  3174. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3175. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  3176. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3177. cm.doc.scrollLeft = val
  3178. alignHorizontally(cm)
  3179. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  3180. cm.display.scrollbars.setScrollLeft(val)
  3181. }
  3182. // SCROLLBARS
  3183. // Prepare DOM reads needed to update the scrollbars. Done in one
  3184. // shot to minimize update/measure roundtrips.
  3185. function measureForScrollbars(cm) {
  3186. var d = cm.display, gutterW = d.gutters.offsetWidth
  3187. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  3188. return {
  3189. clientHeight: d.scroller.clientHeight,
  3190. viewHeight: d.wrapper.clientHeight,
  3191. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3192. viewWidth: d.wrapper.clientWidth,
  3193. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3194. docHeight: docH,
  3195. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3196. nativeBarWidth: d.nativeBarWidth,
  3197. gutterWidth: gutterW
  3198. }
  3199. }
  3200. var NativeScrollbars = function(place, scroll, cm) {
  3201. this.cm = cm
  3202. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3203. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3204. place(vert); place(horiz)
  3205. on(vert, "scroll", function () {
  3206. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3207. })
  3208. on(horiz, "scroll", function () {
  3209. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3210. })
  3211. this.checkedZeroWidth = false
  3212. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3213. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3214. };
  3215. NativeScrollbars.prototype.update = function (measure) {
  3216. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3217. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3218. var sWidth = measure.nativeBarWidth
  3219. if (needsV) {
  3220. this.vert.style.display = "block"
  3221. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3222. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3223. // A bug in IE8 can cause this value to be negative, so guard it.
  3224. this.vert.firstChild.style.height =
  3225. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3226. } else {
  3227. this.vert.style.display = ""
  3228. this.vert.firstChild.style.height = "0"
  3229. }
  3230. if (needsH) {
  3231. this.horiz.style.display = "block"
  3232. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3233. this.horiz.style.left = measure.barLeft + "px"
  3234. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3235. this.horiz.firstChild.style.width =
  3236. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3237. } else {
  3238. this.horiz.style.display = ""
  3239. this.horiz.firstChild.style.width = "0"
  3240. }
  3241. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3242. if (sWidth == 0) { this.zeroWidthHack() }
  3243. this.checkedZeroWidth = true
  3244. }
  3245. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3246. };
  3247. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3248. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3249. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") }
  3250. };
  3251. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3252. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3253. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") }
  3254. };
  3255. NativeScrollbars.prototype.zeroWidthHack = function () {
  3256. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3257. this.horiz.style.height = this.vert.style.width = w
  3258. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3259. this.disableHoriz = new Delayed
  3260. this.disableVert = new Delayed
  3261. };
  3262. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3263. bar.style.pointerEvents = "auto"
  3264. function maybeDisable() {
  3265. // To find out whether the scrollbar is still visible, we
  3266. // check whether the element under the pixel in the bottom
  3267. // right corner of the scrollbar box is the scrollbar box
  3268. // itself (when the bar is still visible) or its filler child
  3269. // (when the bar is hidden). If it is still visible, we keep
  3270. // it enabled, if it's hidden, we disable pointer events.
  3271. var box = bar.getBoundingClientRect()
  3272. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3273. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
  3274. if (elt != bar) { bar.style.pointerEvents = "none" }
  3275. else { delay.set(1000, maybeDisable) }
  3276. }
  3277. delay.set(1000, maybeDisable)
  3278. };
  3279. NativeScrollbars.prototype.clear = function () {
  3280. var parent = this.horiz.parentNode
  3281. parent.removeChild(this.horiz)
  3282. parent.removeChild(this.vert)
  3283. };
  3284. var NullScrollbars = function () {};
  3285. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3286. NullScrollbars.prototype.setScrollLeft = function () {};
  3287. NullScrollbars.prototype.setScrollTop = function () {};
  3288. NullScrollbars.prototype.clear = function () {};
  3289. function updateScrollbars(cm, measure) {
  3290. if (!measure) { measure = measureForScrollbars(cm) }
  3291. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3292. updateScrollbarsInner(cm, measure)
  3293. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3294. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3295. { updateHeightsInViewport(cm) }
  3296. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3297. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3298. }
  3299. }
  3300. // Re-synchronize the fake scrollbars with the actual size of the
  3301. // content.
  3302. function updateScrollbarsInner(cm, measure) {
  3303. var d = cm.display
  3304. var sizes = d.scrollbars.update(measure)
  3305. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3306. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3307. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3308. if (sizes.right && sizes.bottom) {
  3309. d.scrollbarFiller.style.display = "block"
  3310. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3311. d.scrollbarFiller.style.width = sizes.right + "px"
  3312. } else { d.scrollbarFiller.style.display = "" }
  3313. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3314. d.gutterFiller.style.display = "block"
  3315. d.gutterFiller.style.height = sizes.bottom + "px"
  3316. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3317. } else { d.gutterFiller.style.display = "" }
  3318. }
  3319. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3320. function initScrollbars(cm) {
  3321. if (cm.display.scrollbars) {
  3322. cm.display.scrollbars.clear()
  3323. if (cm.display.scrollbars.addClass)
  3324. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3325. }
  3326. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3327. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3328. // Prevent clicks in the scrollbars from killing focus
  3329. on(node, "mousedown", function () {
  3330. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3331. })
  3332. node.setAttribute("cm-not-content", "true")
  3333. }, function (pos, axis) {
  3334. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3335. else { updateScrollTop(cm, pos) }
  3336. }, cm)
  3337. if (cm.display.scrollbars.addClass)
  3338. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3339. }
  3340. // Operations are used to wrap a series of changes to the editor
  3341. // state in such a way that each change won't have to update the
  3342. // cursor and display (which would be awkward, slow, and
  3343. // error-prone). Instead, display updates are batched and then all
  3344. // combined and executed at once.
  3345. var nextOpId = 0
  3346. // Start a new operation.
  3347. function startOperation(cm) {
  3348. cm.curOp = {
  3349. cm: cm,
  3350. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3351. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3352. forceUpdate: false, // Used to force a redraw
  3353. updateInput: null, // Whether to reset the input textarea
  3354. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3355. changeObjs: null, // Accumulated changes, for firing change events
  3356. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3357. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3358. selectionChanged: false, // Whether the selection needs to be redrawn
  3359. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3360. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3361. scrollToPos: null, // Used to scroll to a specific position
  3362. focus: false,
  3363. id: ++nextOpId // Unique ID
  3364. }
  3365. pushOperation(cm.curOp)
  3366. }
  3367. // Finish an operation, updating the display and signalling delayed events
  3368. function endOperation(cm) {
  3369. var op = cm.curOp
  3370. finishOperation(op, function (group) {
  3371. for (var i = 0; i < group.ops.length; i++)
  3372. { group.ops[i].cm.curOp = null }
  3373. endOperations(group)
  3374. })
  3375. }
  3376. // The DOM updates done when an operation finishes are batched so
  3377. // that the minimum number of relayouts are required.
  3378. function endOperations(group) {
  3379. var ops = group.ops
  3380. for (var i = 0; i < ops.length; i++) // Read DOM
  3381. { endOperation_R1(ops[i]) }
  3382. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3383. { endOperation_W1(ops[i$1]) }
  3384. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3385. { endOperation_R2(ops[i$2]) }
  3386. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3387. { endOperation_W2(ops[i$3]) }
  3388. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3389. { endOperation_finish(ops[i$4]) }
  3390. }
  3391. function endOperation_R1(op) {
  3392. var cm = op.cm, display = cm.display
  3393. maybeClipScrollbars(cm)
  3394. if (op.updateMaxLine) { findMaxLine(cm) }
  3395. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3396. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3397. op.scrollToPos.to.line >= display.viewTo) ||
  3398. display.maxLineChanged && cm.options.lineWrapping
  3399. op.update = op.mustUpdate &&
  3400. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3401. }
  3402. function endOperation_W1(op) {
  3403. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3404. }
  3405. function endOperation_R2(op) {
  3406. var cm = op.cm, display = cm.display
  3407. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3408. op.barMeasure = measureForScrollbars(cm)
  3409. // If the max line changed since it was last measured, measure it,
  3410. // and ensure the document's width matches it.
  3411. // updateDisplay_W2 will use these properties to do the actual resizing
  3412. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3413. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3414. cm.display.sizerWidth = op.adjustWidthTo
  3415. op.barMeasure.scrollWidth =
  3416. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3417. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3418. }
  3419. if (op.updatedDisplay || op.selectionChanged)
  3420. { op.preparedSelection = display.input.prepareSelection(op.focus) }
  3421. }
  3422. function endOperation_W2(op) {
  3423. var cm = op.cm
  3424. if (op.adjustWidthTo != null) {
  3425. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3426. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3427. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3428. cm.display.maxLineChanged = false
  3429. }
  3430. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  3431. if (op.preparedSelection)
  3432. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3433. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3434. { updateScrollbars(cm, op.barMeasure) }
  3435. if (op.updatedDisplay)
  3436. { setDocumentHeight(cm, op.barMeasure) }
  3437. if (op.selectionChanged) { restartBlink(cm) }
  3438. if (cm.state.focused && op.updateInput)
  3439. { cm.display.input.reset(op.typing) }
  3440. if (takeFocus) { ensureFocus(op.cm) }
  3441. }
  3442. function endOperation_finish(op) {
  3443. var cm = op.cm, display = cm.display, doc = cm.doc
  3444. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3445. // Abort mouse wheel delta measurement, when scrolling explicitly
  3446. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3447. { display.wheelStartX = display.wheelStartY = null }
  3448. // Propagate the scroll position to the actual DOM scroller
  3449. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) }
  3450. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) }
  3451. // If we need to scroll a specific position into view, do so.
  3452. if (op.scrollToPos) {
  3453. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3454. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3455. maybeScrollWindow(cm, rect)
  3456. }
  3457. // Fire events for markers that are hidden/unidden by editing or
  3458. // undoing
  3459. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3460. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3461. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3462. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3463. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3464. if (display.wrapper.offsetHeight)
  3465. { doc.scrollTop = cm.display.scroller.scrollTop }
  3466. // Fire change events, and delayed event handlers
  3467. if (op.changeObjs)
  3468. { signal(cm, "changes", cm, op.changeObjs) }
  3469. if (op.update)
  3470. { op.update.finish() }
  3471. }
  3472. // Run the given function in an operation
  3473. function runInOp(cm, f) {
  3474. if (cm.curOp) { return f() }
  3475. startOperation(cm)
  3476. try { return f() }
  3477. finally { endOperation(cm) }
  3478. }
  3479. // Wraps a function in an operation. Returns the wrapped function.
  3480. function operation(cm, f) {
  3481. return function() {
  3482. if (cm.curOp) { return f.apply(cm, arguments) }
  3483. startOperation(cm)
  3484. try { return f.apply(cm, arguments) }
  3485. finally { endOperation(cm) }
  3486. }
  3487. }
  3488. // Used to add methods to editor and doc instances, wrapping them in
  3489. // operations.
  3490. function methodOp(f) {
  3491. return function() {
  3492. if (this.curOp) { return f.apply(this, arguments) }
  3493. startOperation(this)
  3494. try { return f.apply(this, arguments) }
  3495. finally { endOperation(this) }
  3496. }
  3497. }
  3498. function docMethodOp(f) {
  3499. return function() {
  3500. var cm = this.cm
  3501. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3502. startOperation(cm)
  3503. try { return f.apply(this, arguments) }
  3504. finally { endOperation(cm) }
  3505. }
  3506. }
  3507. // Updates the display.view data structure for a given change to the
  3508. // document. From and to are in pre-change coordinates. Lendiff is
  3509. // the amount of lines added or subtracted by the change. This is
  3510. // used for changes that span multiple lines, or change the way
  3511. // lines are divided into visual lines. regLineChange (below)
  3512. // registers single-line changes.
  3513. function regChange(cm, from, to, lendiff) {
  3514. if (from == null) { from = cm.doc.first }
  3515. if (to == null) { to = cm.doc.first + cm.doc.size }
  3516. if (!lendiff) { lendiff = 0 }
  3517. var display = cm.display
  3518. if (lendiff && to < display.viewTo &&
  3519. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3520. { display.updateLineNumbers = from }
  3521. cm.curOp.viewChanged = true
  3522. if (from >= display.viewTo) { // Change after
  3523. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3524. { resetView(cm) }
  3525. } else if (to <= display.viewFrom) { // Change before
  3526. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3527. resetView(cm)
  3528. } else {
  3529. display.viewFrom += lendiff
  3530. display.viewTo += lendiff
  3531. }
  3532. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3533. resetView(cm)
  3534. } else if (from <= display.viewFrom) { // Top overlap
  3535. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3536. if (cut) {
  3537. display.view = display.view.slice(cut.index)
  3538. display.viewFrom = cut.lineN
  3539. display.viewTo += lendiff
  3540. } else {
  3541. resetView(cm)
  3542. }
  3543. } else if (to >= display.viewTo) { // Bottom overlap
  3544. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3545. if (cut$1) {
  3546. display.view = display.view.slice(0, cut$1.index)
  3547. display.viewTo = cut$1.lineN
  3548. } else {
  3549. resetView(cm)
  3550. }
  3551. } else { // Gap in the middle
  3552. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3553. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3554. if (cutTop && cutBot) {
  3555. display.view = display.view.slice(0, cutTop.index)
  3556. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3557. .concat(display.view.slice(cutBot.index))
  3558. display.viewTo += lendiff
  3559. } else {
  3560. resetView(cm)
  3561. }
  3562. }
  3563. var ext = display.externalMeasured
  3564. if (ext) {
  3565. if (to < ext.lineN)
  3566. { ext.lineN += lendiff }
  3567. else if (from < ext.lineN + ext.size)
  3568. { display.externalMeasured = null }
  3569. }
  3570. }
  3571. // Register a change to a single line. Type must be one of "text",
  3572. // "gutter", "class", "widget"
  3573. function regLineChange(cm, line, type) {
  3574. cm.curOp.viewChanged = true
  3575. var display = cm.display, ext = cm.display.externalMeasured
  3576. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3577. { display.externalMeasured = null }
  3578. if (line < display.viewFrom || line >= display.viewTo) { return }
  3579. var lineView = display.view[findViewIndex(cm, line)]
  3580. if (lineView.node == null) { return }
  3581. var arr = lineView.changes || (lineView.changes = [])
  3582. if (indexOf(arr, type) == -1) { arr.push(type) }
  3583. }
  3584. // Clear the view.
  3585. function resetView(cm) {
  3586. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3587. cm.display.view = []
  3588. cm.display.viewOffset = 0
  3589. }
  3590. function viewCuttingPoint(cm, oldN, newN, dir) {
  3591. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3592. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3593. { return {index: index, lineN: newN} }
  3594. var n = cm.display.viewFrom
  3595. for (var i = 0; i < index; i++)
  3596. { n += view[i].size }
  3597. if (n != oldN) {
  3598. if (dir > 0) {
  3599. if (index == view.length - 1) { return null }
  3600. diff = (n + view[index].size) - oldN
  3601. index++
  3602. } else {
  3603. diff = n - oldN
  3604. }
  3605. oldN += diff; newN += diff
  3606. }
  3607. while (visualLineNo(cm.doc, newN) != newN) {
  3608. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3609. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3610. index += dir
  3611. }
  3612. return {index: index, lineN: newN}
  3613. }
  3614. // Force the view to cover a given range, adding empty view element
  3615. // or clipping off existing ones as needed.
  3616. function adjustView(cm, from, to) {
  3617. var display = cm.display, view = display.view
  3618. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3619. display.view = buildViewArray(cm, from, to)
  3620. display.viewFrom = from
  3621. } else {
  3622. if (display.viewFrom > from)
  3623. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3624. else if (display.viewFrom < from)
  3625. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3626. display.viewFrom = from
  3627. if (display.viewTo < to)
  3628. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3629. else if (display.viewTo > to)
  3630. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3631. }
  3632. display.viewTo = to
  3633. }
  3634. // Count the number of lines in the view whose DOM representation is
  3635. // out of date (or nonexistent).
  3636. function countDirtyView(cm) {
  3637. var view = cm.display.view, dirty = 0
  3638. for (var i = 0; i < view.length; i++) {
  3639. var lineView = view[i]
  3640. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3641. }
  3642. return dirty
  3643. }
  3644. // HIGHLIGHT WORKER
  3645. function startWorker(cm, time) {
  3646. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3647. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3648. }
  3649. function highlightWorker(cm) {
  3650. var doc = cm.doc
  3651. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3652. var end = +new Date + cm.options.workTime
  3653. var context = getContextBefore(cm, doc.highlightFrontier)
  3654. var changedLines = []
  3655. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3656. if (context.line >= cm.display.viewFrom) { // Visible
  3657. var oldStyles = line.styles
  3658. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
  3659. var highlighted = highlightLine(cm, line, context, true)
  3660. if (resetState) { context.state = resetState }
  3661. line.styles = highlighted.styles
  3662. var oldCls = line.styleClasses, newCls = highlighted.classes
  3663. if (newCls) { line.styleClasses = newCls }
  3664. else if (oldCls) { line.styleClasses = null }
  3665. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3666. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3667. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3668. if (ischange) { changedLines.push(context.line) }
  3669. line.stateAfter = context.save()
  3670. context.nextLine()
  3671. } else {
  3672. if (line.text.length <= cm.options.maxHighlightLength)
  3673. { processLine(cm, line.text, context) }
  3674. line.stateAfter = context.line % 5 == 0 ? context.save() : null
  3675. context.nextLine()
  3676. }
  3677. if (+new Date > end) {
  3678. startWorker(cm, cm.options.workDelay)
  3679. return true
  3680. }
  3681. })
  3682. doc.highlightFrontier = context.line
  3683. doc.modeFrontier = Math.max(doc.modeFrontier, context.line)
  3684. if (changedLines.length) { runInOp(cm, function () {
  3685. for (var i = 0; i < changedLines.length; i++)
  3686. { regLineChange(cm, changedLines[i], "text") }
  3687. }) }
  3688. }
  3689. // DISPLAY DRAWING
  3690. var DisplayUpdate = function(cm, viewport, force) {
  3691. var display = cm.display
  3692. this.viewport = viewport
  3693. // Store some values that we'll need later (but don't want to force a relayout for)
  3694. this.visible = visibleLines(display, cm.doc, viewport)
  3695. this.editorIsHidden = !display.wrapper.offsetWidth
  3696. this.wrapperHeight = display.wrapper.clientHeight
  3697. this.wrapperWidth = display.wrapper.clientWidth
  3698. this.oldDisplayWidth = displayWidth(cm)
  3699. this.force = force
  3700. this.dims = getDimensions(cm)
  3701. this.events = []
  3702. };
  3703. DisplayUpdate.prototype.signal = function (emitter, type) {
  3704. if (hasHandler(emitter, type))
  3705. { this.events.push(arguments) }
  3706. };
  3707. DisplayUpdate.prototype.finish = function () {
  3708. var this$1 = this;
  3709. for (var i = 0; i < this.events.length; i++)
  3710. { signal.apply(null, this$1.events[i]) }
  3711. };
  3712. function maybeClipScrollbars(cm) {
  3713. var display = cm.display
  3714. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3715. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3716. display.heightForcer.style.height = scrollGap(cm) + "px"
  3717. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3718. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3719. display.scrollbarsClipped = true
  3720. }
  3721. }
  3722. function selectionSnapshot(cm) {
  3723. if (cm.hasFocus()) { return null }
  3724. var active = activeElt()
  3725. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3726. var result = {activeElt: active}
  3727. if (window.getSelection) {
  3728. var sel = window.getSelection()
  3729. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3730. result.anchorNode = sel.anchorNode
  3731. result.anchorOffset = sel.anchorOffset
  3732. result.focusNode = sel.focusNode
  3733. result.focusOffset = sel.focusOffset
  3734. }
  3735. }
  3736. return result
  3737. }
  3738. function restoreSelection(snapshot) {
  3739. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3740. snapshot.activeElt.focus()
  3741. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3742. var sel = window.getSelection(), range = document.createRange()
  3743. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)
  3744. range.collapse(false)
  3745. sel.removeAllRanges()
  3746. sel.addRange(range)
  3747. sel.extend(snapshot.focusNode, snapshot.focusOffset)
  3748. }
  3749. }
  3750. // Does the actual updating of the line display. Bails out
  3751. // (returning false) when there is nothing to be done and forced is
  3752. // false.
  3753. function updateDisplayIfNeeded(cm, update) {
  3754. var display = cm.display, doc = cm.doc
  3755. if (update.editorIsHidden) {
  3756. resetView(cm)
  3757. return false
  3758. }
  3759. // Bail out if the visible area is already rendered and nothing changed.
  3760. if (!update.force &&
  3761. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3762. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3763. display.renderedView == display.view && countDirtyView(cm) == 0)
  3764. { return false }
  3765. if (maybeUpdateLineNumberWidth(cm)) {
  3766. resetView(cm)
  3767. update.dims = getDimensions(cm)
  3768. }
  3769. // Compute a suitable new viewport (from & to)
  3770. var end = doc.first + doc.size
  3771. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3772. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3773. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3774. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3775. if (sawCollapsedSpans) {
  3776. from = visualLineNo(cm.doc, from)
  3777. to = visualLineEndNo(cm.doc, to)
  3778. }
  3779. var different = from != display.viewFrom || to != display.viewTo ||
  3780. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3781. adjustView(cm, from, to)
  3782. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3783. // Position the mover div to align with the current scroll position
  3784. cm.display.mover.style.top = display.viewOffset + "px"
  3785. var toUpdate = countDirtyView(cm)
  3786. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3787. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3788. { return false }
  3789. // For big changes, we hide the enclosing element during the
  3790. // update, since that speeds up the operations on most browsers.
  3791. var selSnapshot = selectionSnapshot(cm)
  3792. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3793. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3794. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3795. display.renderedView = display.view
  3796. // There might have been a widget with a focused element that got
  3797. // hidden or updated, if so re-focus it.
  3798. restoreSelection(selSnapshot)
  3799. // Prevent selection and cursors from interfering with the scroll
  3800. // width and height.
  3801. removeChildren(display.cursorDiv)
  3802. removeChildren(display.selectionDiv)
  3803. display.gutters.style.height = display.sizer.style.minHeight = 0
  3804. if (different) {
  3805. display.lastWrapHeight = update.wrapperHeight
  3806. display.lastWrapWidth = update.wrapperWidth
  3807. startWorker(cm, 400)
  3808. }
  3809. display.updateLineNumbers = null
  3810. return true
  3811. }
  3812. function postUpdateDisplay(cm, update) {
  3813. var viewport = update.viewport
  3814. for (var first = true;; first = false) {
  3815. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3816. // Clip forced viewport to actual scrollable area.
  3817. if (viewport && viewport.top != null)
  3818. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3819. // Updated line heights might result in the drawn area not
  3820. // actually covering the viewport. Keep looping until it does.
  3821. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3822. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3823. { break }
  3824. }
  3825. if (!updateDisplayIfNeeded(cm, update)) { break }
  3826. updateHeightsInViewport(cm)
  3827. var barMeasure = measureForScrollbars(cm)
  3828. updateSelection(cm)
  3829. updateScrollbars(cm, barMeasure)
  3830. setDocumentHeight(cm, barMeasure)
  3831. update.force = false
  3832. }
  3833. update.signal(cm, "update", cm)
  3834. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3835. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3836. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3837. }
  3838. }
  3839. function updateDisplaySimple(cm, viewport) {
  3840. var update = new DisplayUpdate(cm, viewport)
  3841. if (updateDisplayIfNeeded(cm, update)) {
  3842. updateHeightsInViewport(cm)
  3843. postUpdateDisplay(cm, update)
  3844. var barMeasure = measureForScrollbars(cm)
  3845. updateSelection(cm)
  3846. updateScrollbars(cm, barMeasure)
  3847. setDocumentHeight(cm, barMeasure)
  3848. update.finish()
  3849. }
  3850. }
  3851. // Sync the actual display DOM structure with display.view, removing
  3852. // nodes for lines that are no longer in view, and creating the ones
  3853. // that are not there yet, and updating the ones that are out of
  3854. // date.
  3855. function patchDisplay(cm, updateNumbersFrom, dims) {
  3856. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3857. var container = display.lineDiv, cur = container.firstChild
  3858. function rm(node) {
  3859. var next = node.nextSibling
  3860. // Works around a throw-scroll bug in OS X Webkit
  3861. if (webkit && mac && cm.display.currentWheelTarget == node)
  3862. { node.style.display = "none" }
  3863. else
  3864. { node.parentNode.removeChild(node) }
  3865. return next
  3866. }
  3867. var view = display.view, lineN = display.viewFrom
  3868. // Loop over the elements in the view, syncing cur (the DOM nodes
  3869. // in display.lineDiv) with the view as we go.
  3870. for (var i = 0; i < view.length; i++) {
  3871. var lineView = view[i]
  3872. if (lineView.hidden) {
  3873. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3874. var node = buildLineElement(cm, lineView, lineN, dims)
  3875. container.insertBefore(node, cur)
  3876. } else { // Already drawn
  3877. while (cur != lineView.node) { cur = rm(cur) }
  3878. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3879. updateNumbersFrom <= lineN && lineView.lineNumber
  3880. if (lineView.changes) {
  3881. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3882. updateLineForChanges(cm, lineView, lineN, dims)
  3883. }
  3884. if (updateNumber) {
  3885. removeChildren(lineView.lineNumber)
  3886. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3887. }
  3888. cur = lineView.node.nextSibling
  3889. }
  3890. lineN += lineView.size
  3891. }
  3892. while (cur) { cur = rm(cur) }
  3893. }
  3894. function updateGutterSpace(cm) {
  3895. var width = cm.display.gutters.offsetWidth
  3896. cm.display.sizer.style.marginLeft = width + "px"
  3897. }
  3898. function setDocumentHeight(cm, measure) {
  3899. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3900. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3901. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3902. }
  3903. // Rebuild the gutter elements, ensure the margin to the left of the
  3904. // code matches their width.
  3905. function updateGutters(cm) {
  3906. var gutters = cm.display.gutters, specs = cm.options.gutters
  3907. removeChildren(gutters)
  3908. var i = 0
  3909. for (; i < specs.length; ++i) {
  3910. var gutterClass = specs[i]
  3911. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3912. if (gutterClass == "CodeMirror-linenumbers") {
  3913. cm.display.lineGutter = gElt
  3914. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3915. }
  3916. }
  3917. gutters.style.display = i ? "" : "none"
  3918. updateGutterSpace(cm)
  3919. }
  3920. // Make sure the gutters options contains the element
  3921. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3922. function setGuttersForLineNumbers(options) {
  3923. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3924. if (found == -1 && options.lineNumbers) {
  3925. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3926. } else if (found > -1 && !options.lineNumbers) {
  3927. options.gutters = options.gutters.slice(0)
  3928. options.gutters.splice(found, 1)
  3929. }
  3930. }
  3931. var wheelSamples = 0;
  3932. var wheelPixelsPerUnit = null;
  3933. // Fill in a browser-detected starting value on browsers where we
  3934. // know one. These don't have to be accurate -- the result of them
  3935. // being wrong would just be a slight flicker on the first wheel
  3936. // scroll (if it is large enough).
  3937. if (ie) { wheelPixelsPerUnit = -.53 }
  3938. else if (gecko) { wheelPixelsPerUnit = 15 }
  3939. else if (chrome) { wheelPixelsPerUnit = -.7 }
  3940. else if (safari) { wheelPixelsPerUnit = -1/3 }
  3941. function wheelEventDelta(e) {
  3942. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  3943. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  3944. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  3945. else if (dy == null) { dy = e.wheelDelta }
  3946. return {x: dx, y: dy}
  3947. }
  3948. function wheelEventPixels(e) {
  3949. var delta = wheelEventDelta(e)
  3950. delta.x *= wheelPixelsPerUnit
  3951. delta.y *= wheelPixelsPerUnit
  3952. return delta
  3953. }
  3954. function onScrollWheel(cm, e) {
  3955. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  3956. var display = cm.display, scroll = display.scroller
  3957. // Quit if there's nothing to scroll here
  3958. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  3959. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  3960. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3961. // Webkit browsers on OS X abort momentum scrolls when the target
  3962. // of the scroll event is removed from the scrollable element.
  3963. // This hack (see related code in patchDisplay) makes sure the
  3964. // element is kept around.
  3965. if (dy && mac && webkit) {
  3966. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3967. for (var i = 0; i < view.length; i++) {
  3968. if (view[i].node == cur) {
  3969. cm.display.currentWheelTarget = cur
  3970. break outer
  3971. }
  3972. }
  3973. }
  3974. }
  3975. // On some browsers, horizontal scrolling will cause redraws to
  3976. // happen before the gutter has been realigned, causing it to
  3977. // wriggle around in a most unseemly way. When we have an
  3978. // estimated pixels/delta value, we just handle horizontal
  3979. // scrolling entirely here. It'll be slightly off from native, but
  3980. // better than glitching out.
  3981. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3982. if (dy && canScrollY)
  3983. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) }
  3984. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit))
  3985. // Only prevent default scrolling if vertical scrolling is
  3986. // actually possible. Otherwise, it causes vertical scroll
  3987. // jitter on OSX trackpads when deltaX is small and deltaY
  3988. // is large (issue #3579)
  3989. if (!dy || (dy && canScrollY))
  3990. { e_preventDefault(e) }
  3991. display.wheelStartX = null // Abort measurement, if in progress
  3992. return
  3993. }
  3994. // 'Project' the visible viewport to cover the area that is being
  3995. // scrolled into view (if we know enough to estimate it).
  3996. if (dy && wheelPixelsPerUnit != null) {
  3997. var pixels = dy * wheelPixelsPerUnit
  3998. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  3999. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  4000. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  4001. updateDisplaySimple(cm, {top: top, bottom: bot})
  4002. }
  4003. if (wheelSamples < 20) {
  4004. if (display.wheelStartX == null) {
  4005. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  4006. display.wheelDX = dx; display.wheelDY = dy
  4007. setTimeout(function () {
  4008. if (display.wheelStartX == null) { return }
  4009. var movedX = scroll.scrollLeft - display.wheelStartX
  4010. var movedY = scroll.scrollTop - display.wheelStartY
  4011. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4012. (movedX && display.wheelDX && movedX / display.wheelDX)
  4013. display.wheelStartX = display.wheelStartY = null
  4014. if (!sample) { return }
  4015. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  4016. ++wheelSamples
  4017. }, 200)
  4018. } else {
  4019. display.wheelDX += dx; display.wheelDY += dy
  4020. }
  4021. }
  4022. }
  4023. // Selection objects are immutable. A new one is created every time
  4024. // the selection changes. A selection is one or more non-overlapping
  4025. // (and non-touching) ranges, sorted, and an integer that indicates
  4026. // which one is the primary selection (the one that's scrolled into
  4027. // view, that getCursor returns, etc).
  4028. var Selection = function(ranges, primIndex) {
  4029. this.ranges = ranges
  4030. this.primIndex = primIndex
  4031. };
  4032. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4033. Selection.prototype.equals = function (other) {
  4034. var this$1 = this;
  4035. if (other == this) { return true }
  4036. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4037. for (var i = 0; i < this.ranges.length; i++) {
  4038. var here = this$1.ranges[i], there = other.ranges[i]
  4039. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4040. }
  4041. return true
  4042. };
  4043. Selection.prototype.deepCopy = function () {
  4044. var this$1 = this;
  4045. var out = []
  4046. for (var i = 0; i < this.ranges.length; i++)
  4047. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  4048. return new Selection(out, this.primIndex)
  4049. };
  4050. Selection.prototype.somethingSelected = function () {
  4051. var this$1 = this;
  4052. for (var i = 0; i < this.ranges.length; i++)
  4053. { if (!this$1.ranges[i].empty()) { return true } }
  4054. return false
  4055. };
  4056. Selection.prototype.contains = function (pos, end) {
  4057. var this$1 = this;
  4058. if (!end) { end = pos }
  4059. for (var i = 0; i < this.ranges.length; i++) {
  4060. var range = this$1.ranges[i]
  4061. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4062. { return i }
  4063. }
  4064. return -1
  4065. };
  4066. var Range = function(anchor, head) {
  4067. this.anchor = anchor; this.head = head
  4068. };
  4069. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4070. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4071. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4072. // Take an unsorted, potentially overlapping set of ranges, and
  4073. // build a selection out of it. 'Consumes' ranges array (modifying
  4074. // it).
  4075. function normalizeSelection(ranges, primIndex) {
  4076. var prim = ranges[primIndex]
  4077. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  4078. primIndex = indexOf(ranges, prim)
  4079. for (var i = 1; i < ranges.length; i++) {
  4080. var cur = ranges[i], prev = ranges[i - 1]
  4081. if (cmp(prev.to(), cur.from()) >= 0) {
  4082. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  4083. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  4084. if (i <= primIndex) { --primIndex }
  4085. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  4086. }
  4087. }
  4088. return new Selection(ranges, primIndex)
  4089. }
  4090. function simpleSelection(anchor, head) {
  4091. return new Selection([new Range(anchor, head || anchor)], 0)
  4092. }
  4093. // Compute the position of the end of a change (its 'to' property
  4094. // refers to the pre-change end).
  4095. function changeEnd(change) {
  4096. if (!change.text) { return change.to }
  4097. return Pos(change.from.line + change.text.length - 1,
  4098. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4099. }
  4100. // Adjust a position to refer to the post-change position of the
  4101. // same text, or the end of the change if the change covers it.
  4102. function adjustForChange(pos, change) {
  4103. if (cmp(pos, change.from) < 0) { return pos }
  4104. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4105. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  4106. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  4107. return Pos(line, ch)
  4108. }
  4109. function computeSelAfterChange(doc, change) {
  4110. var out = []
  4111. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4112. var range = doc.sel.ranges[i]
  4113. out.push(new Range(adjustForChange(range.anchor, change),
  4114. adjustForChange(range.head, change)))
  4115. }
  4116. return normalizeSelection(out, doc.sel.primIndex)
  4117. }
  4118. function offsetPos(pos, old, nw) {
  4119. if (pos.line == old.line)
  4120. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4121. else
  4122. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4123. }
  4124. // Used by replaceSelections to allow moving the selection to the
  4125. // start or around the replaced test. Hint may be "start" or "around".
  4126. function computeReplacedSel(doc, changes, hint) {
  4127. var out = []
  4128. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  4129. for (var i = 0; i < changes.length; i++) {
  4130. var change = changes[i]
  4131. var from = offsetPos(change.from, oldPrev, newPrev)
  4132. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  4133. oldPrev = change.to
  4134. newPrev = to
  4135. if (hint == "around") {
  4136. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  4137. out[i] = new Range(inv ? to : from, inv ? from : to)
  4138. } else {
  4139. out[i] = new Range(from, from)
  4140. }
  4141. }
  4142. return new Selection(out, doc.sel.primIndex)
  4143. }
  4144. // Used to get the editor into a consistent state again when options change.
  4145. function loadMode(cm) {
  4146. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  4147. resetModeState(cm)
  4148. }
  4149. function resetModeState(cm) {
  4150. cm.doc.iter(function (line) {
  4151. if (line.stateAfter) { line.stateAfter = null }
  4152. if (line.styles) { line.styles = null }
  4153. })
  4154. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first
  4155. startWorker(cm, 100)
  4156. cm.state.modeGen++
  4157. if (cm.curOp) { regChange(cm) }
  4158. }
  4159. // DOCUMENT DATA STRUCTURE
  4160. // By default, updates that start and end at the beginning of a line
  4161. // are treated specially, in order to make the association of line
  4162. // widgets and marker elements with the text behave more intuitive.
  4163. function isWholeLineUpdate(doc, change) {
  4164. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4165. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4166. }
  4167. // Perform a change on the document data structure.
  4168. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4169. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4170. function update(line, text, spans) {
  4171. updateLine(line, text, spans, estimateHeight)
  4172. signalLater(line, "change", line, change)
  4173. }
  4174. function linesFor(start, end) {
  4175. var result = []
  4176. for (var i = start; i < end; ++i)
  4177. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  4178. return result
  4179. }
  4180. var from = change.from, to = change.to, text = change.text
  4181. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  4182. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  4183. // Adjust the line structure
  4184. if (change.full) {
  4185. doc.insert(0, linesFor(0, text.length))
  4186. doc.remove(text.length, doc.size - text.length)
  4187. } else if (isWholeLineUpdate(doc, change)) {
  4188. // This is a whole-line replace. Treated specially to make
  4189. // sure line objects move the way they are supposed to.
  4190. var added = linesFor(0, text.length - 1)
  4191. update(lastLine, lastLine.text, lastSpans)
  4192. if (nlines) { doc.remove(from.line, nlines) }
  4193. if (added.length) { doc.insert(from.line, added) }
  4194. } else if (firstLine == lastLine) {
  4195. if (text.length == 1) {
  4196. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4197. } else {
  4198. var added$1 = linesFor(1, text.length - 1)
  4199. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4200. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4201. doc.insert(from.line + 1, added$1)
  4202. }
  4203. } else if (text.length == 1) {
  4204. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4205. doc.remove(from.line + 1, nlines)
  4206. } else {
  4207. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4208. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4209. var added$2 = linesFor(1, text.length - 1)
  4210. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4211. doc.insert(from.line + 1, added$2)
  4212. }
  4213. signalLater(doc, "change", doc, change)
  4214. }
  4215. // Call f for all linked documents.
  4216. function linkedDocs(doc, f, sharedHistOnly) {
  4217. function propagate(doc, skip, sharedHist) {
  4218. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4219. var rel = doc.linked[i]
  4220. if (rel.doc == skip) { continue }
  4221. var shared = sharedHist && rel.sharedHist
  4222. if (sharedHistOnly && !shared) { continue }
  4223. f(rel.doc, shared)
  4224. propagate(rel.doc, doc, shared)
  4225. } }
  4226. }
  4227. propagate(doc, null, true)
  4228. }
  4229. // Attach a document to an editor.
  4230. function attachDoc(cm, doc) {
  4231. if (doc.cm) { throw new Error("This document is already in use.") }
  4232. cm.doc = doc
  4233. doc.cm = cm
  4234. estimateLineHeights(cm)
  4235. loadMode(cm)
  4236. setDirectionClass(cm)
  4237. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4238. cm.options.mode = doc.modeOption
  4239. regChange(cm)
  4240. }
  4241. function setDirectionClass(cm) {
  4242. ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl")
  4243. }
  4244. function directionChanged(cm) {
  4245. runInOp(cm, function () {
  4246. setDirectionClass(cm)
  4247. regChange(cm)
  4248. })
  4249. }
  4250. function History(startGen) {
  4251. // Arrays of change events and selections. Doing something adds an
  4252. // event to done and clears undo. Undoing moves events from done
  4253. // to undone, redoing moves them in the other direction.
  4254. this.done = []; this.undone = []
  4255. this.undoDepth = Infinity
  4256. // Used to track when changes can be merged into a single undo
  4257. // event
  4258. this.lastModTime = this.lastSelTime = 0
  4259. this.lastOp = this.lastSelOp = null
  4260. this.lastOrigin = this.lastSelOrigin = null
  4261. // Used by the isClean() method
  4262. this.generation = this.maxGeneration = startGen || 1
  4263. }
  4264. // Create a history change event from an updateDoc-style change
  4265. // object.
  4266. function historyChangeFromChange(doc, change) {
  4267. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4268. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4269. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4270. return histChange
  4271. }
  4272. // Pop all selection events off the end of a history array. Stop at
  4273. // a change event.
  4274. function clearSelectionEvents(array) {
  4275. while (array.length) {
  4276. var last = lst(array)
  4277. if (last.ranges) { array.pop() }
  4278. else { break }
  4279. }
  4280. }
  4281. // Find the top change event in the history. Pop off selection
  4282. // events that are in the way.
  4283. function lastChangeEvent(hist, force) {
  4284. if (force) {
  4285. clearSelectionEvents(hist.done)
  4286. return lst(hist.done)
  4287. } else if (hist.done.length && !lst(hist.done).ranges) {
  4288. return lst(hist.done)
  4289. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4290. hist.done.pop()
  4291. return lst(hist.done)
  4292. }
  4293. }
  4294. // Register a change in the history. Merges changes that are within
  4295. // a single operation, or are close together with an origin that
  4296. // allows merging (starting with "+") into a single event.
  4297. function addChangeToHistory(doc, change, selAfter, opId) {
  4298. var hist = doc.history
  4299. hist.undone.length = 0
  4300. var time = +new Date, cur
  4301. var last
  4302. if ((hist.lastOp == opId ||
  4303. hist.lastOrigin == change.origin && change.origin &&
  4304. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4305. change.origin.charAt(0) == "*")) &&
  4306. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4307. // Merge this change into the last event
  4308. last = lst(cur.changes)
  4309. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4310. // Optimized case for simple insertion -- don't want to add
  4311. // new changesets for every character typed
  4312. last.to = changeEnd(change)
  4313. } else {
  4314. // Add new sub-event
  4315. cur.changes.push(historyChangeFromChange(doc, change))
  4316. }
  4317. } else {
  4318. // Can not be merged, start a new event.
  4319. var before = lst(hist.done)
  4320. if (!before || !before.ranges)
  4321. { pushSelectionToHistory(doc.sel, hist.done) }
  4322. cur = {changes: [historyChangeFromChange(doc, change)],
  4323. generation: hist.generation}
  4324. hist.done.push(cur)
  4325. while (hist.done.length > hist.undoDepth) {
  4326. hist.done.shift()
  4327. if (!hist.done[0].ranges) { hist.done.shift() }
  4328. }
  4329. }
  4330. hist.done.push(selAfter)
  4331. hist.generation = ++hist.maxGeneration
  4332. hist.lastModTime = hist.lastSelTime = time
  4333. hist.lastOp = hist.lastSelOp = opId
  4334. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4335. if (!last) { signal(doc, "historyAdded") }
  4336. }
  4337. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4338. var ch = origin.charAt(0)
  4339. return ch == "*" ||
  4340. ch == "+" &&
  4341. prev.ranges.length == sel.ranges.length &&
  4342. prev.somethingSelected() == sel.somethingSelected() &&
  4343. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4344. }
  4345. // Called whenever the selection changes, sets the new selection as
  4346. // the pending selection in the history, and pushes the old pending
  4347. // selection into the 'done' array when it was significantly
  4348. // different (in number of selected ranges, emptiness, or time).
  4349. function addSelectionToHistory(doc, sel, opId, options) {
  4350. var hist = doc.history, origin = options && options.origin
  4351. // A new event is started when the previous origin does not match
  4352. // the current, or the origins don't allow matching. Origins
  4353. // starting with * are always merged, those starting with + are
  4354. // merged when similar and close together in time.
  4355. if (opId == hist.lastSelOp ||
  4356. (origin && hist.lastSelOrigin == origin &&
  4357. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4358. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4359. { hist.done[hist.done.length - 1] = sel }
  4360. else
  4361. { pushSelectionToHistory(sel, hist.done) }
  4362. hist.lastSelTime = +new Date
  4363. hist.lastSelOrigin = origin
  4364. hist.lastSelOp = opId
  4365. if (options && options.clearRedo !== false)
  4366. { clearSelectionEvents(hist.undone) }
  4367. }
  4368. function pushSelectionToHistory(sel, dest) {
  4369. var top = lst(dest)
  4370. if (!(top && top.ranges && top.equals(sel)))
  4371. { dest.push(sel) }
  4372. }
  4373. // Used to store marked span information in the history.
  4374. function attachLocalSpans(doc, change, from, to) {
  4375. var existing = change["spans_" + doc.id], n = 0
  4376. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4377. if (line.markedSpans)
  4378. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4379. ++n
  4380. })
  4381. }
  4382. // When un/re-doing restores text containing marked spans, those
  4383. // that have been explicitly cleared should not be restored.
  4384. function removeClearedSpans(spans) {
  4385. if (!spans) { return null }
  4386. var out
  4387. for (var i = 0; i < spans.length; ++i) {
  4388. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4389. else if (out) { out.push(spans[i]) }
  4390. }
  4391. return !out ? spans : out.length ? out : null
  4392. }
  4393. // Retrieve and filter the old marked spans stored in a change event.
  4394. function getOldSpans(doc, change) {
  4395. var found = change["spans_" + doc.id]
  4396. if (!found) { return null }
  4397. var nw = []
  4398. for (var i = 0; i < change.text.length; ++i)
  4399. { nw.push(removeClearedSpans(found[i])) }
  4400. return nw
  4401. }
  4402. // Used for un/re-doing changes from the history. Combines the
  4403. // result of computing the existing spans with the set of spans that
  4404. // existed in the history (so that deleting around a span and then
  4405. // undoing brings back the span).
  4406. function mergeOldSpans(doc, change) {
  4407. var old = getOldSpans(doc, change)
  4408. var stretched = stretchSpansOverChange(doc, change)
  4409. if (!old) { return stretched }
  4410. if (!stretched) { return old }
  4411. for (var i = 0; i < old.length; ++i) {
  4412. var oldCur = old[i], stretchCur = stretched[i]
  4413. if (oldCur && stretchCur) {
  4414. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4415. var span = stretchCur[j]
  4416. for (var k = 0; k < oldCur.length; ++k)
  4417. { if (oldCur[k].marker == span.marker) { continue spans } }
  4418. oldCur.push(span)
  4419. }
  4420. } else if (stretchCur) {
  4421. old[i] = stretchCur
  4422. }
  4423. }
  4424. return old
  4425. }
  4426. // Used both to provide a JSON-safe object in .getHistory, and, when
  4427. // detaching a document, to split the history in two
  4428. function copyHistoryArray(events, newGroup, instantiateSel) {
  4429. var copy = []
  4430. for (var i = 0; i < events.length; ++i) {
  4431. var event = events[i]
  4432. if (event.ranges) {
  4433. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4434. continue
  4435. }
  4436. var changes = event.changes, newChanges = []
  4437. copy.push({changes: newChanges})
  4438. for (var j = 0; j < changes.length; ++j) {
  4439. var change = changes[j], m = (void 0)
  4440. newChanges.push({from: change.from, to: change.to, text: change.text})
  4441. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4442. if (indexOf(newGroup, Number(m[1])) > -1) {
  4443. lst(newChanges)[prop] = change[prop]
  4444. delete change[prop]
  4445. }
  4446. } } }
  4447. }
  4448. }
  4449. return copy
  4450. }
  4451. // The 'scroll' parameter given to many of these indicated whether
  4452. // the new cursor position should be scrolled into view after
  4453. // modifying the selection.
  4454. // If shift is held or the extend flag is set, extends a range to
  4455. // include a given position (and optionally a second position).
  4456. // Otherwise, simply returns the range between the given positions.
  4457. // Used for cursor motion and such.
  4458. function extendRange(range, head, other, extend) {
  4459. if (extend) {
  4460. var anchor = range.anchor
  4461. if (other) {
  4462. var posBefore = cmp(head, anchor) < 0
  4463. if (posBefore != (cmp(other, anchor) < 0)) {
  4464. anchor = head
  4465. head = other
  4466. } else if (posBefore != (cmp(head, other) < 0)) {
  4467. head = other
  4468. }
  4469. }
  4470. return new Range(anchor, head)
  4471. } else {
  4472. return new Range(other || head, head)
  4473. }
  4474. }
  4475. // Extend the primary selection range, discard the rest.
  4476. function extendSelection(doc, head, other, options, extend) {
  4477. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend) }
  4478. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)
  4479. }
  4480. // Extend all selections (pos is an array of selections with length
  4481. // equal the number of selections)
  4482. function extendSelections(doc, heads, options) {
  4483. var out = []
  4484. var extend = doc.cm && (doc.cm.display.shift || doc.extend)
  4485. for (var i = 0; i < doc.sel.ranges.length; i++)
  4486. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) }
  4487. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4488. setSelection(doc, newSel, options)
  4489. }
  4490. // Updates a single range in the selection.
  4491. function replaceOneSelection(doc, i, range, options) {
  4492. var ranges = doc.sel.ranges.slice(0)
  4493. ranges[i] = range
  4494. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4495. }
  4496. // Reset the selection to a single range.
  4497. function setSimpleSelection(doc, anchor, head, options) {
  4498. setSelection(doc, simpleSelection(anchor, head), options)
  4499. }
  4500. // Give beforeSelectionChange handlers a change to influence a
  4501. // selection update.
  4502. function filterSelectionChange(doc, sel, options) {
  4503. var obj = {
  4504. ranges: sel.ranges,
  4505. update: function(ranges) {
  4506. var this$1 = this;
  4507. this.ranges = []
  4508. for (var i = 0; i < ranges.length; i++)
  4509. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4510. clipPos(doc, ranges[i].head)) }
  4511. },
  4512. origin: options && options.origin
  4513. }
  4514. signal(doc, "beforeSelectionChange", doc, obj)
  4515. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4516. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4517. else { return sel }
  4518. }
  4519. function setSelectionReplaceHistory(doc, sel, options) {
  4520. var done = doc.history.done, last = lst(done)
  4521. if (last && last.ranges) {
  4522. done[done.length - 1] = sel
  4523. setSelectionNoUndo(doc, sel, options)
  4524. } else {
  4525. setSelection(doc, sel, options)
  4526. }
  4527. }
  4528. // Set a new selection.
  4529. function setSelection(doc, sel, options) {
  4530. setSelectionNoUndo(doc, sel, options)
  4531. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4532. }
  4533. function setSelectionNoUndo(doc, sel, options) {
  4534. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4535. { sel = filterSelectionChange(doc, sel, options) }
  4536. var bias = options && options.bias ||
  4537. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4538. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4539. if (!(options && options.scroll === false) && doc.cm)
  4540. { ensureCursorVisible(doc.cm) }
  4541. }
  4542. function setSelectionInner(doc, sel) {
  4543. if (sel.equals(doc.sel)) { return }
  4544. doc.sel = sel
  4545. if (doc.cm) {
  4546. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4547. signalCursorActivity(doc.cm)
  4548. }
  4549. signalLater(doc, "cursorActivity", doc)
  4550. }
  4551. // Verify that the selection does not partially select any atomic
  4552. // marked ranges.
  4553. function reCheckSelection(doc) {
  4554. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))
  4555. }
  4556. // Return a selection that does not partially select any atomic
  4557. // ranges.
  4558. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4559. var out
  4560. for (var i = 0; i < sel.ranges.length; i++) {
  4561. var range = sel.ranges[i]
  4562. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4563. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4564. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4565. if (out || newAnchor != range.anchor || newHead != range.head) {
  4566. if (!out) { out = sel.ranges.slice(0, i) }
  4567. out[i] = new Range(newAnchor, newHead)
  4568. }
  4569. }
  4570. return out ? normalizeSelection(out, sel.primIndex) : sel
  4571. }
  4572. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4573. var line = getLine(doc, pos.line)
  4574. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4575. var sp = line.markedSpans[i], m = sp.marker
  4576. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4577. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4578. if (mayClear) {
  4579. signal(m, "beforeCursorEnter")
  4580. if (m.explicitlyCleared) {
  4581. if (!line.markedSpans) { break }
  4582. else {--i; continue}
  4583. }
  4584. }
  4585. if (!m.atomic) { continue }
  4586. if (oldPos) {
  4587. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4588. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4589. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4590. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4591. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4592. }
  4593. var far = m.find(dir < 0 ? -1 : 1)
  4594. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4595. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4596. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4597. }
  4598. } }
  4599. return pos
  4600. }
  4601. // Ensure a given position is not inside an atomic range.
  4602. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4603. var dir = bias || 1
  4604. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4605. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4606. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4607. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4608. if (!found) {
  4609. doc.cantEdit = true
  4610. return Pos(doc.first, 0)
  4611. }
  4612. return found
  4613. }
  4614. function movePos(doc, pos, dir, line) {
  4615. if (dir < 0 && pos.ch == 0) {
  4616. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4617. else { return null }
  4618. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4619. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4620. else { return null }
  4621. } else {
  4622. return new Pos(pos.line, pos.ch + dir)
  4623. }
  4624. }
  4625. function selectAll(cm) {
  4626. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4627. }
  4628. // UPDATING
  4629. // Allow "beforeChange" event handlers to influence a change
  4630. function filterChange(doc, change, update) {
  4631. var obj = {
  4632. canceled: false,
  4633. from: change.from,
  4634. to: change.to,
  4635. text: change.text,
  4636. origin: change.origin,
  4637. cancel: function () { return obj.canceled = true; }
  4638. }
  4639. if (update) { obj.update = function (from, to, text, origin) {
  4640. if (from) { obj.from = clipPos(doc, from) }
  4641. if (to) { obj.to = clipPos(doc, to) }
  4642. if (text) { obj.text = text }
  4643. if (origin !== undefined) { obj.origin = origin }
  4644. } }
  4645. signal(doc, "beforeChange", doc, obj)
  4646. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4647. if (obj.canceled) { return null }
  4648. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4649. }
  4650. // Apply a change to a document, and add it to the document's
  4651. // history, and propagating it to all linked documents.
  4652. function makeChange(doc, change, ignoreReadOnly) {
  4653. if (doc.cm) {
  4654. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4655. if (doc.cm.state.suppressEdits) { return }
  4656. }
  4657. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4658. change = filterChange(doc, change, true)
  4659. if (!change) { return }
  4660. }
  4661. // Possibly split or suppress the update based on the presence
  4662. // of read-only spans in its range.
  4663. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4664. if (split) {
  4665. for (var i = split.length - 1; i >= 0; --i)
  4666. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) }
  4667. } else {
  4668. makeChangeInner(doc, change)
  4669. }
  4670. }
  4671. function makeChangeInner(doc, change) {
  4672. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4673. var selAfter = computeSelAfterChange(doc, change)
  4674. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4675. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4676. var rebased = []
  4677. linkedDocs(doc, function (doc, sharedHist) {
  4678. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4679. rebaseHist(doc.history, change)
  4680. rebased.push(doc.history)
  4681. }
  4682. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4683. })
  4684. }
  4685. // Revert a change stored in a document's history.
  4686. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4687. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4688. var hist = doc.history, event, selAfter = doc.sel
  4689. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4690. // Verify that there is a useable event (so that ctrl-z won't
  4691. // needlessly clear selection events)
  4692. var i = 0
  4693. for (; i < source.length; i++) {
  4694. event = source[i]
  4695. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4696. { break }
  4697. }
  4698. if (i == source.length) { return }
  4699. hist.lastOrigin = hist.lastSelOrigin = null
  4700. for (;;) {
  4701. event = source.pop()
  4702. if (event.ranges) {
  4703. pushSelectionToHistory(event, dest)
  4704. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4705. setSelection(doc, event, {clearRedo: false})
  4706. return
  4707. }
  4708. selAfter = event
  4709. }
  4710. else { break }
  4711. }
  4712. // Build up a reverse change object to add to the opposite history
  4713. // stack (redo when undoing, and vice versa).
  4714. var antiChanges = []
  4715. pushSelectionToHistory(selAfter, dest)
  4716. dest.push({changes: antiChanges, generation: hist.generation})
  4717. hist.generation = event.generation || ++hist.maxGeneration
  4718. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4719. var loop = function ( i ) {
  4720. var change = event.changes[i]
  4721. change.origin = type
  4722. if (filter && !filterChange(doc, change, false)) {
  4723. source.length = 0
  4724. return {}
  4725. }
  4726. antiChanges.push(historyChangeFromChange(doc, change))
  4727. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4728. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4729. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4730. var rebased = []
  4731. // Propagate to the linked documents
  4732. linkedDocs(doc, function (doc, sharedHist) {
  4733. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4734. rebaseHist(doc.history, change)
  4735. rebased.push(doc.history)
  4736. }
  4737. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4738. })
  4739. };
  4740. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4741. var returned = loop( i$1 );
  4742. if ( returned ) return returned.v;
  4743. }
  4744. }
  4745. // Sub-views need their line numbers shifted when text is added
  4746. // above or below them in the parent document.
  4747. function shiftDoc(doc, distance) {
  4748. if (distance == 0) { return }
  4749. doc.first += distance
  4750. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4751. Pos(range.anchor.line + distance, range.anchor.ch),
  4752. Pos(range.head.line + distance, range.head.ch)
  4753. ); }), doc.sel.primIndex)
  4754. if (doc.cm) {
  4755. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4756. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4757. { regLineChange(doc.cm, l, "gutter") }
  4758. }
  4759. }
  4760. // More lower-level change function, handling only a single document
  4761. // (not linked ones).
  4762. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4763. if (doc.cm && !doc.cm.curOp)
  4764. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4765. if (change.to.line < doc.first) {
  4766. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4767. return
  4768. }
  4769. if (change.from.line > doc.lastLine()) { return }
  4770. // Clip the change to the size of this doc
  4771. if (change.from.line < doc.first) {
  4772. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4773. shiftDoc(doc, shift)
  4774. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4775. text: [lst(change.text)], origin: change.origin}
  4776. }
  4777. var last = doc.lastLine()
  4778. if (change.to.line > last) {
  4779. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4780. text: [change.text[0]], origin: change.origin}
  4781. }
  4782. change.removed = getBetween(doc, change.from, change.to)
  4783. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4784. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4785. else { updateDoc(doc, change, spans) }
  4786. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4787. }
  4788. // Handle the interaction of a change to a document with the editor
  4789. // that this document is part of.
  4790. function makeChangeSingleDocInEditor(cm, change, spans) {
  4791. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4792. var recomputeMaxLength = false, checkWidthStart = from.line
  4793. if (!cm.options.lineWrapping) {
  4794. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4795. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4796. if (line == display.maxLine) {
  4797. recomputeMaxLength = true
  4798. return true
  4799. }
  4800. })
  4801. }
  4802. if (doc.sel.contains(change.from, change.to) > -1)
  4803. { signalCursorActivity(cm) }
  4804. updateDoc(doc, change, spans, estimateHeight(cm))
  4805. if (!cm.options.lineWrapping) {
  4806. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4807. var len = lineLength(line)
  4808. if (len > display.maxLineLength) {
  4809. display.maxLine = line
  4810. display.maxLineLength = len
  4811. display.maxLineChanged = true
  4812. recomputeMaxLength = false
  4813. }
  4814. })
  4815. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4816. }
  4817. retreatFrontier(doc, from.line)
  4818. startWorker(cm, 400)
  4819. var lendiff = change.text.length - (to.line - from.line) - 1
  4820. // Remember that these lines changed, for updating the display
  4821. if (change.full)
  4822. { regChange(cm) }
  4823. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4824. { regLineChange(cm, from.line, "text") }
  4825. else
  4826. { regChange(cm, from.line, to.line + 1, lendiff) }
  4827. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4828. if (changeHandler || changesHandler) {
  4829. var obj = {
  4830. from: from, to: to,
  4831. text: change.text,
  4832. removed: change.removed,
  4833. origin: change.origin
  4834. }
  4835. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4836. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4837. }
  4838. cm.display.selForContextMenu = null
  4839. }
  4840. function replaceRange(doc, code, from, to, origin) {
  4841. if (!to) { to = from }
  4842. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp }
  4843. if (typeof code == "string") { code = doc.splitLines(code) }
  4844. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4845. }
  4846. // Rebasing/resetting history to deal with externally-sourced changes
  4847. function rebaseHistSelSingle(pos, from, to, diff) {
  4848. if (to < pos.line) {
  4849. pos.line += diff
  4850. } else if (from < pos.line) {
  4851. pos.line = from
  4852. pos.ch = 0
  4853. }
  4854. }
  4855. // Tries to rebase an array of history events given a change in the
  4856. // document. If the change touches the same lines as the event, the
  4857. // event, and everything 'behind' it, is discarded. If the change is
  4858. // before the event, the event's positions are updated. Uses a
  4859. // copy-on-write scheme for the positions, to avoid having to
  4860. // reallocate them all on every rebase, but also avoid problems with
  4861. // shared position objects being unsafely updated.
  4862. function rebaseHistArray(array, from, to, diff) {
  4863. for (var i = 0; i < array.length; ++i) {
  4864. var sub = array[i], ok = true
  4865. if (sub.ranges) {
  4866. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4867. for (var j = 0; j < sub.ranges.length; j++) {
  4868. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4869. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4870. }
  4871. continue
  4872. }
  4873. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4874. var cur = sub.changes[j$1]
  4875. if (to < cur.from.line) {
  4876. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4877. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4878. } else if (from <= cur.to.line) {
  4879. ok = false
  4880. break
  4881. }
  4882. }
  4883. if (!ok) {
  4884. array.splice(0, i + 1)
  4885. i = 0
  4886. }
  4887. }
  4888. }
  4889. function rebaseHist(hist, change) {
  4890. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4891. rebaseHistArray(hist.done, from, to, diff)
  4892. rebaseHistArray(hist.undone, from, to, diff)
  4893. }
  4894. // Utility for applying a change to a line by handle or number,
  4895. // returning the number and optionally registering the line as
  4896. // changed.
  4897. function changeLine(doc, handle, changeType, op) {
  4898. var no = handle, line = handle
  4899. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4900. else { no = lineNo(handle) }
  4901. if (no == null) { return null }
  4902. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4903. return line
  4904. }
  4905. // The document is represented as a BTree consisting of leaves, with
  4906. // chunk of lines in them, and branches, with up to ten leaves or
  4907. // other branch nodes below them. The top node is always a branch
  4908. // node, and is the document object itself (meaning it has
  4909. // additional methods and properties).
  4910. //
  4911. // All nodes have parent links. The tree is used both to go from
  4912. // line numbers to line objects, and to go from objects to numbers.
  4913. // It also indexes by height, and is used to convert between height
  4914. // and line object, and to find the total height of the document.
  4915. //
  4916. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4917. function LeafChunk(lines) {
  4918. var this$1 = this;
  4919. this.lines = lines
  4920. this.parent = null
  4921. var height = 0
  4922. for (var i = 0; i < lines.length; ++i) {
  4923. lines[i].parent = this$1
  4924. height += lines[i].height
  4925. }
  4926. this.height = height
  4927. }
  4928. LeafChunk.prototype = {
  4929. chunkSize: function chunkSize() { return this.lines.length },
  4930. // Remove the n lines at offset 'at'.
  4931. removeInner: function removeInner(at, n) {
  4932. var this$1 = this;
  4933. for (var i = at, e = at + n; i < e; ++i) {
  4934. var line = this$1.lines[i]
  4935. this$1.height -= line.height
  4936. cleanUpLine(line)
  4937. signalLater(line, "delete")
  4938. }
  4939. this.lines.splice(at, n)
  4940. },
  4941. // Helper used to collapse a small branch into a single leaf.
  4942. collapse: function collapse(lines) {
  4943. lines.push.apply(lines, this.lines)
  4944. },
  4945. // Insert the given array of lines at offset 'at', count them as
  4946. // having the given height.
  4947. insertInner: function insertInner(at, lines, height) {
  4948. var this$1 = this;
  4949. this.height += height
  4950. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4951. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4952. },
  4953. // Used to iterate over a part of the tree.
  4954. iterN: function iterN(at, n, op) {
  4955. var this$1 = this;
  4956. for (var e = at + n; at < e; ++at)
  4957. { if (op(this$1.lines[at])) { return true } }
  4958. }
  4959. }
  4960. function BranchChunk(children) {
  4961. var this$1 = this;
  4962. this.children = children
  4963. var size = 0, height = 0
  4964. for (var i = 0; i < children.length; ++i) {
  4965. var ch = children[i]
  4966. size += ch.chunkSize(); height += ch.height
  4967. ch.parent = this$1
  4968. }
  4969. this.size = size
  4970. this.height = height
  4971. this.parent = null
  4972. }
  4973. BranchChunk.prototype = {
  4974. chunkSize: function chunkSize() { return this.size },
  4975. removeInner: function removeInner(at, n) {
  4976. var this$1 = this;
  4977. this.size -= n
  4978. for (var i = 0; i < this.children.length; ++i) {
  4979. var child = this$1.children[i], sz = child.chunkSize()
  4980. if (at < sz) {
  4981. var rm = Math.min(n, sz - at), oldHeight = child.height
  4982. child.removeInner(at, rm)
  4983. this$1.height -= oldHeight - child.height
  4984. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  4985. if ((n -= rm) == 0) { break }
  4986. at = 0
  4987. } else { at -= sz }
  4988. }
  4989. // If the result is smaller than 25 lines, ensure that it is a
  4990. // single leaf node.
  4991. if (this.size - n < 25 &&
  4992. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  4993. var lines = []
  4994. this.collapse(lines)
  4995. this.children = [new LeafChunk(lines)]
  4996. this.children[0].parent = this
  4997. }
  4998. },
  4999. collapse: function collapse(lines) {
  5000. var this$1 = this;
  5001. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  5002. },
  5003. insertInner: function insertInner(at, lines, height) {
  5004. var this$1 = this;
  5005. this.size += lines.length
  5006. this.height += height
  5007. for (var i = 0; i < this.children.length; ++i) {
  5008. var child = this$1.children[i], sz = child.chunkSize()
  5009. if (at <= sz) {
  5010. child.insertInner(at, lines, height)
  5011. if (child.lines && child.lines.length > 50) {
  5012. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5013. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5014. var remaining = child.lines.length % 25 + 25
  5015. for (var pos = remaining; pos < child.lines.length;) {
  5016. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  5017. child.height -= leaf.height
  5018. this$1.children.splice(++i, 0, leaf)
  5019. leaf.parent = this$1
  5020. }
  5021. child.lines = child.lines.slice(0, remaining)
  5022. this$1.maybeSpill()
  5023. }
  5024. break
  5025. }
  5026. at -= sz
  5027. }
  5028. },
  5029. // When a node has grown, check whether it should be split.
  5030. maybeSpill: function maybeSpill() {
  5031. if (this.children.length <= 10) { return }
  5032. var me = this
  5033. do {
  5034. var spilled = me.children.splice(me.children.length - 5, 5)
  5035. var sibling = new BranchChunk(spilled)
  5036. if (!me.parent) { // Become the parent node
  5037. var copy = new BranchChunk(me.children)
  5038. copy.parent = me
  5039. me.children = [copy, sibling]
  5040. me = copy
  5041. } else {
  5042. me.size -= sibling.size
  5043. me.height -= sibling.height
  5044. var myIndex = indexOf(me.parent.children, me)
  5045. me.parent.children.splice(myIndex + 1, 0, sibling)
  5046. }
  5047. sibling.parent = me.parent
  5048. } while (me.children.length > 10)
  5049. me.parent.maybeSpill()
  5050. },
  5051. iterN: function iterN(at, n, op) {
  5052. var this$1 = this;
  5053. for (var i = 0; i < this.children.length; ++i) {
  5054. var child = this$1.children[i], sz = child.chunkSize()
  5055. if (at < sz) {
  5056. var used = Math.min(n, sz - at)
  5057. if (child.iterN(at, used, op)) { return true }
  5058. if ((n -= used) == 0) { break }
  5059. at = 0
  5060. } else { at -= sz }
  5061. }
  5062. }
  5063. }
  5064. // Line widgets are block elements displayed above or below a line.
  5065. var LineWidget = function(doc, node, options) {
  5066. var this$1 = this;
  5067. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5068. { this$1[opt] = options[opt] } } }
  5069. this.doc = doc
  5070. this.node = node
  5071. };
  5072. LineWidget.prototype.clear = function () {
  5073. var this$1 = this;
  5074. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  5075. if (no == null || !ws) { return }
  5076. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  5077. if (!ws.length) { line.widgets = null }
  5078. var height = widgetHeight(this)
  5079. updateLineHeight(line, Math.max(0, line.height - height))
  5080. if (cm) {
  5081. runInOp(cm, function () {
  5082. adjustScrollWhenAboveVisible(cm, line, -height)
  5083. regLineChange(cm, no, "widget")
  5084. })
  5085. signalLater(cm, "lineWidgetCleared", cm, this, no)
  5086. }
  5087. };
  5088. LineWidget.prototype.changed = function () {
  5089. var this$1 = this;
  5090. var oldH = this.height, cm = this.doc.cm, line = this.line
  5091. this.height = null
  5092. var diff = widgetHeight(this) - oldH
  5093. if (!diff) { return }
  5094. updateLineHeight(line, line.height + diff)
  5095. if (cm) {
  5096. runInOp(cm, function () {
  5097. cm.curOp.forceUpdate = true
  5098. adjustScrollWhenAboveVisible(cm, line, diff)
  5099. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line))
  5100. })
  5101. }
  5102. };
  5103. eventMixin(LineWidget)
  5104. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5105. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5106. { addToScrollTop(cm, diff) }
  5107. }
  5108. function addLineWidget(doc, handle, node, options) {
  5109. var widget = new LineWidget(doc, node, options)
  5110. var cm = doc.cm
  5111. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  5112. changeLine(doc, handle, "widget", function (line) {
  5113. var widgets = line.widgets || (line.widgets = [])
  5114. if (widget.insertAt == null) { widgets.push(widget) }
  5115. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  5116. widget.line = line
  5117. if (cm && !lineIsHidden(doc, line)) {
  5118. var aboveVisible = heightAtLine(line) < doc.scrollTop
  5119. updateLineHeight(line, line.height + widgetHeight(widget))
  5120. if (aboveVisible) { addToScrollTop(cm, widget.height) }
  5121. cm.curOp.forceUpdate = true
  5122. }
  5123. return true
  5124. })
  5125. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle))
  5126. return widget
  5127. }
  5128. // TEXTMARKERS
  5129. // Created with markText and setBookmark methods. A TextMarker is a
  5130. // handle that can be used to clear or find a marked position in the
  5131. // document. Line objects hold arrays (markedSpans) containing
  5132. // {from, to, marker} object pointing to such marker objects, and
  5133. // indicating that such a marker is present on that line. Multiple
  5134. // lines may point to the same marker when it spans across lines.
  5135. // The spans will have null for their from/to properties when the
  5136. // marker continues beyond the start/end of the line. Markers have
  5137. // links back to the lines they currently touch.
  5138. // Collapsed markers have unique ids, in order to be able to order
  5139. // them, which is needed for uniquely determining an outer marker
  5140. // when they overlap (they may nest, but not partially overlap).
  5141. var nextMarkerId = 0
  5142. var TextMarker = function(doc, type) {
  5143. this.lines = []
  5144. this.type = type
  5145. this.doc = doc
  5146. this.id = ++nextMarkerId
  5147. };
  5148. // Clear the marker.
  5149. TextMarker.prototype.clear = function () {
  5150. var this$1 = this;
  5151. if (this.explicitlyCleared) { return }
  5152. var cm = this.doc.cm, withOp = cm && !cm.curOp
  5153. if (withOp) { startOperation(cm) }
  5154. if (hasHandler(this, "clear")) {
  5155. var found = this.find()
  5156. if (found) { signalLater(this, "clear", found.from, found.to) }
  5157. }
  5158. var min = null, max = null
  5159. for (var i = 0; i < this.lines.length; ++i) {
  5160. var line = this$1.lines[i]
  5161. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5162. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  5163. else if (cm) {
  5164. if (span.to != null) { max = lineNo(line) }
  5165. if (span.from != null) { min = lineNo(line) }
  5166. }
  5167. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  5168. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5169. { updateLineHeight(line, textHeight(cm.display)) }
  5170. }
  5171. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5172. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  5173. if (len > cm.display.maxLineLength) {
  5174. cm.display.maxLine = visual
  5175. cm.display.maxLineLength = len
  5176. cm.display.maxLineChanged = true
  5177. }
  5178. } }
  5179. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  5180. this.lines.length = 0
  5181. this.explicitlyCleared = true
  5182. if (this.atomic && this.doc.cantEdit) {
  5183. this.doc.cantEdit = false
  5184. if (cm) { reCheckSelection(cm.doc) }
  5185. }
  5186. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) }
  5187. if (withOp) { endOperation(cm) }
  5188. if (this.parent) { this.parent.clear() }
  5189. };
  5190. // Find the position of the marker in the document. Returns a {from,
  5191. // to} object by default. Side can be passed to get a specific side
  5192. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5193. // Pos objects returned contain a line object, rather than a line
  5194. // number (used to prevent looking up the same line twice).
  5195. TextMarker.prototype.find = function (side, lineObj) {
  5196. var this$1 = this;
  5197. if (side == null && this.type == "bookmark") { side = 1 }
  5198. var from, to
  5199. for (var i = 0; i < this.lines.length; ++i) {
  5200. var line = this$1.lines[i]
  5201. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5202. if (span.from != null) {
  5203. from = Pos(lineObj ? line : lineNo(line), span.from)
  5204. if (side == -1) { return from }
  5205. }
  5206. if (span.to != null) {
  5207. to = Pos(lineObj ? line : lineNo(line), span.to)
  5208. if (side == 1) { return to }
  5209. }
  5210. }
  5211. return from && {from: from, to: to}
  5212. };
  5213. // Signals that the marker's widget changed, and surrounding layout
  5214. // should be recomputed.
  5215. TextMarker.prototype.changed = function () {
  5216. var this$1 = this;
  5217. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5218. if (!pos || !cm) { return }
  5219. runInOp(cm, function () {
  5220. var line = pos.line, lineN = lineNo(pos.line)
  5221. var view = findViewForLine(cm, lineN)
  5222. if (view) {
  5223. clearLineMeasurementCacheFor(view)
  5224. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5225. }
  5226. cm.curOp.updateMaxLine = true
  5227. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5228. var oldHeight = widget.height
  5229. widget.height = null
  5230. var dHeight = widgetHeight(widget) - oldHeight
  5231. if (dHeight)
  5232. { updateLineHeight(line, line.height + dHeight) }
  5233. }
  5234. signalLater(cm, "markerChanged", cm, this$1)
  5235. })
  5236. };
  5237. TextMarker.prototype.attachLine = function (line) {
  5238. if (!this.lines.length && this.doc.cm) {
  5239. var op = this.doc.cm.curOp
  5240. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5241. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5242. }
  5243. this.lines.push(line)
  5244. };
  5245. TextMarker.prototype.detachLine = function (line) {
  5246. this.lines.splice(indexOf(this.lines, line), 1)
  5247. if (!this.lines.length && this.doc.cm) {
  5248. var op = this.doc.cm.curOp
  5249. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5250. }
  5251. };
  5252. eventMixin(TextMarker)
  5253. // Create a marker, wire it up to the right lines, and
  5254. function markText(doc, from, to, options, type) {
  5255. // Shared markers (across linked documents) are handled separately
  5256. // (markTextShared will call out to this again, once per
  5257. // document).
  5258. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5259. // Ensure we are in an operation.
  5260. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5261. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5262. if (options) { copyObj(options, marker, false) }
  5263. // Don't connect empty markers unless clearWhenEmpty is false
  5264. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5265. { return marker }
  5266. if (marker.replacedWith) {
  5267. // Showing up as a widget implies collapsed (widget replaces text)
  5268. marker.collapsed = true
  5269. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget")
  5270. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5271. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5272. }
  5273. if (marker.collapsed) {
  5274. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5275. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5276. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5277. seeCollapsedSpans()
  5278. }
  5279. if (marker.addToHistory)
  5280. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5281. var curLine = from.line, cm = doc.cm, updateMaxLine
  5282. doc.iter(curLine, to.line + 1, function (line) {
  5283. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5284. { updateMaxLine = true }
  5285. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5286. addMarkedSpan(line, new MarkedSpan(marker,
  5287. curLine == from.line ? from.ch : null,
  5288. curLine == to.line ? to.ch : null))
  5289. ++curLine
  5290. })
  5291. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5292. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5293. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5294. }) }
  5295. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5296. if (marker.readOnly) {
  5297. seeReadOnlySpans()
  5298. if (doc.history.done.length || doc.history.undone.length)
  5299. { doc.clearHistory() }
  5300. }
  5301. if (marker.collapsed) {
  5302. marker.id = ++nextMarkerId
  5303. marker.atomic = true
  5304. }
  5305. if (cm) {
  5306. // Sync editor state
  5307. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5308. if (marker.collapsed)
  5309. { regChange(cm, from.line, to.line + 1) }
  5310. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5311. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5312. if (marker.atomic) { reCheckSelection(cm.doc) }
  5313. signalLater(cm, "markerAdded", cm, marker)
  5314. }
  5315. return marker
  5316. }
  5317. // SHARED TEXTMARKERS
  5318. // A shared marker spans multiple linked documents. It is
  5319. // implemented as a meta-marker-object controlling multiple normal
  5320. // markers.
  5321. var SharedTextMarker = function(markers, primary) {
  5322. var this$1 = this;
  5323. this.markers = markers
  5324. this.primary = primary
  5325. for (var i = 0; i < markers.length; ++i)
  5326. { markers[i].parent = this$1 }
  5327. };
  5328. SharedTextMarker.prototype.clear = function () {
  5329. var this$1 = this;
  5330. if (this.explicitlyCleared) { return }
  5331. this.explicitlyCleared = true
  5332. for (var i = 0; i < this.markers.length; ++i)
  5333. { this$1.markers[i].clear() }
  5334. signalLater(this, "clear")
  5335. };
  5336. SharedTextMarker.prototype.find = function (side, lineObj) {
  5337. return this.primary.find(side, lineObj)
  5338. };
  5339. eventMixin(SharedTextMarker)
  5340. function markTextShared(doc, from, to, options, type) {
  5341. options = copyObj(options)
  5342. options.shared = false
  5343. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5344. var widget = options.widgetNode
  5345. linkedDocs(doc, function (doc) {
  5346. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5347. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5348. for (var i = 0; i < doc.linked.length; ++i)
  5349. { if (doc.linked[i].isParent) { return } }
  5350. primary = lst(markers)
  5351. })
  5352. return new SharedTextMarker(markers, primary)
  5353. }
  5354. function findSharedMarkers(doc) {
  5355. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5356. }
  5357. function copySharedMarkers(doc, markers) {
  5358. for (var i = 0; i < markers.length; i++) {
  5359. var marker = markers[i], pos = marker.find()
  5360. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5361. if (cmp(mFrom, mTo)) {
  5362. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5363. marker.markers.push(subMark)
  5364. subMark.parent = marker
  5365. }
  5366. }
  5367. }
  5368. function detachSharedMarkers(markers) {
  5369. var loop = function ( i ) {
  5370. var marker = markers[i], linked = [marker.primary.doc]
  5371. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5372. for (var j = 0; j < marker.markers.length; j++) {
  5373. var subMarker = marker.markers[j]
  5374. if (indexOf(linked, subMarker.doc) == -1) {
  5375. subMarker.parent = null
  5376. marker.markers.splice(j--, 1)
  5377. }
  5378. }
  5379. };
  5380. for (var i = 0; i < markers.length; i++) loop( i );
  5381. }
  5382. var nextDocId = 0
  5383. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5384. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5385. if (firstLine == null) { firstLine = 0 }
  5386. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5387. this.first = firstLine
  5388. this.scrollTop = this.scrollLeft = 0
  5389. this.cantEdit = false
  5390. this.cleanGeneration = 1
  5391. this.modeFrontier = this.highlightFrontier = firstLine
  5392. var start = Pos(firstLine, 0)
  5393. this.sel = simpleSelection(start)
  5394. this.history = new History(null)
  5395. this.id = ++nextDocId
  5396. this.modeOption = mode
  5397. this.lineSep = lineSep
  5398. this.direction = (direction == "rtl") ? "rtl" : "ltr"
  5399. this.extend = false
  5400. if (typeof text == "string") { text = this.splitLines(text) }
  5401. updateDoc(this, {from: start, to: start, text: text})
  5402. setSelection(this, simpleSelection(start), sel_dontScroll)
  5403. }
  5404. Doc.prototype = createObj(BranchChunk.prototype, {
  5405. constructor: Doc,
  5406. // Iterate over the document. Supports two forms -- with only one
  5407. // argument, it calls that for each line in the document. With
  5408. // three, it iterates over the range given by the first two (with
  5409. // the second being non-inclusive).
  5410. iter: function(from, to, op) {
  5411. if (op) { this.iterN(from - this.first, to - from, op) }
  5412. else { this.iterN(this.first, this.first + this.size, from) }
  5413. },
  5414. // Non-public interface for adding and removing lines.
  5415. insert: function(at, lines) {
  5416. var height = 0
  5417. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5418. this.insertInner(at - this.first, lines, height)
  5419. },
  5420. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5421. // From here, the methods are part of the public interface. Most
  5422. // are also available from CodeMirror (editor) instances.
  5423. getValue: function(lineSep) {
  5424. var lines = getLines(this, this.first, this.first + this.size)
  5425. if (lineSep === false) { return lines }
  5426. return lines.join(lineSep || this.lineSeparator())
  5427. },
  5428. setValue: docMethodOp(function(code) {
  5429. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5430. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5431. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5432. if (this.cm) { scrollToCoords(this.cm, 0, 0) }
  5433. setSelection(this, simpleSelection(top), sel_dontScroll)
  5434. }),
  5435. replaceRange: function(code, from, to, origin) {
  5436. from = clipPos(this, from)
  5437. to = to ? clipPos(this, to) : from
  5438. replaceRange(this, code, from, to, origin)
  5439. },
  5440. getRange: function(from, to, lineSep) {
  5441. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5442. if (lineSep === false) { return lines }
  5443. return lines.join(lineSep || this.lineSeparator())
  5444. },
  5445. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5446. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5447. getLineNumber: function(line) {return lineNo(line)},
  5448. getLineHandleVisualStart: function(line) {
  5449. if (typeof line == "number") { line = getLine(this, line) }
  5450. return visualLine(line)
  5451. },
  5452. lineCount: function() {return this.size},
  5453. firstLine: function() {return this.first},
  5454. lastLine: function() {return this.first + this.size - 1},
  5455. clipPos: function(pos) {return clipPos(this, pos)},
  5456. getCursor: function(start) {
  5457. var range = this.sel.primary(), pos
  5458. if (start == null || start == "head") { pos = range.head }
  5459. else if (start == "anchor") { pos = range.anchor }
  5460. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5461. else { pos = range.from() }
  5462. return pos
  5463. },
  5464. listSelections: function() { return this.sel.ranges },
  5465. somethingSelected: function() {return this.sel.somethingSelected()},
  5466. setCursor: docMethodOp(function(line, ch, options) {
  5467. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5468. }),
  5469. setSelection: docMethodOp(function(anchor, head, options) {
  5470. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5471. }),
  5472. extendSelection: docMethodOp(function(head, other, options) {
  5473. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5474. }),
  5475. extendSelections: docMethodOp(function(heads, options) {
  5476. extendSelections(this, clipPosArray(this, heads), options)
  5477. }),
  5478. extendSelectionsBy: docMethodOp(function(f, options) {
  5479. var heads = map(this.sel.ranges, f)
  5480. extendSelections(this, clipPosArray(this, heads), options)
  5481. }),
  5482. setSelections: docMethodOp(function(ranges, primary, options) {
  5483. var this$1 = this;
  5484. if (!ranges.length) { return }
  5485. var out = []
  5486. for (var i = 0; i < ranges.length; i++)
  5487. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5488. clipPos(this$1, ranges[i].head)) }
  5489. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5490. setSelection(this, normalizeSelection(out, primary), options)
  5491. }),
  5492. addSelection: docMethodOp(function(anchor, head, options) {
  5493. var ranges = this.sel.ranges.slice(0)
  5494. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5495. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5496. }),
  5497. getSelection: function(lineSep) {
  5498. var this$1 = this;
  5499. var ranges = this.sel.ranges, lines
  5500. for (var i = 0; i < ranges.length; i++) {
  5501. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5502. lines = lines ? lines.concat(sel) : sel
  5503. }
  5504. if (lineSep === false) { return lines }
  5505. else { return lines.join(lineSep || this.lineSeparator()) }
  5506. },
  5507. getSelections: function(lineSep) {
  5508. var this$1 = this;
  5509. var parts = [], ranges = this.sel.ranges
  5510. for (var i = 0; i < ranges.length; i++) {
  5511. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5512. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5513. parts[i] = sel
  5514. }
  5515. return parts
  5516. },
  5517. replaceSelection: function(code, collapse, origin) {
  5518. var dup = []
  5519. for (var i = 0; i < this.sel.ranges.length; i++)
  5520. { dup[i] = code }
  5521. this.replaceSelections(dup, collapse, origin || "+input")
  5522. },
  5523. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5524. var this$1 = this;
  5525. var changes = [], sel = this.sel
  5526. for (var i = 0; i < sel.ranges.length; i++) {
  5527. var range = sel.ranges[i]
  5528. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5529. }
  5530. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5531. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5532. { makeChange(this$1, changes[i$1]) }
  5533. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5534. else if (this.cm) { ensureCursorVisible(this.cm) }
  5535. }),
  5536. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5537. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5538. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5539. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5540. setExtending: function(val) {this.extend = val},
  5541. getExtending: function() {return this.extend},
  5542. historySize: function() {
  5543. var hist = this.history, done = 0, undone = 0
  5544. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5545. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5546. return {undo: done, redo: undone}
  5547. },
  5548. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5549. markClean: function() {
  5550. this.cleanGeneration = this.changeGeneration(true)
  5551. },
  5552. changeGeneration: function(forceSplit) {
  5553. if (forceSplit)
  5554. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5555. return this.history.generation
  5556. },
  5557. isClean: function (gen) {
  5558. return this.history.generation == (gen || this.cleanGeneration)
  5559. },
  5560. getHistory: function() {
  5561. return {done: copyHistoryArray(this.history.done),
  5562. undone: copyHistoryArray(this.history.undone)}
  5563. },
  5564. setHistory: function(histData) {
  5565. var hist = this.history = new History(this.history.maxGeneration)
  5566. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5567. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5568. },
  5569. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5570. return changeLine(this, line, "gutter", function (line) {
  5571. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5572. markers[gutterID] = value
  5573. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5574. return true
  5575. })
  5576. }),
  5577. clearGutter: docMethodOp(function(gutterID) {
  5578. var this$1 = this;
  5579. this.iter(function (line) {
  5580. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5581. changeLine(this$1, line, "gutter", function () {
  5582. line.gutterMarkers[gutterID] = null
  5583. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5584. return true
  5585. })
  5586. }
  5587. })
  5588. }),
  5589. lineInfo: function(line) {
  5590. var n
  5591. if (typeof line == "number") {
  5592. if (!isLine(this, line)) { return null }
  5593. n = line
  5594. line = getLine(this, line)
  5595. if (!line) { return null }
  5596. } else {
  5597. n = lineNo(line)
  5598. if (n == null) { return null }
  5599. }
  5600. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5601. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5602. widgets: line.widgets}
  5603. },
  5604. addLineClass: docMethodOp(function(handle, where, cls) {
  5605. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5606. var prop = where == "text" ? "textClass"
  5607. : where == "background" ? "bgClass"
  5608. : where == "gutter" ? "gutterClass" : "wrapClass"
  5609. if (!line[prop]) { line[prop] = cls }
  5610. else if (classTest(cls).test(line[prop])) { return false }
  5611. else { line[prop] += " " + cls }
  5612. return true
  5613. })
  5614. }),
  5615. removeLineClass: docMethodOp(function(handle, where, cls) {
  5616. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5617. var prop = where == "text" ? "textClass"
  5618. : where == "background" ? "bgClass"
  5619. : where == "gutter" ? "gutterClass" : "wrapClass"
  5620. var cur = line[prop]
  5621. if (!cur) { return false }
  5622. else if (cls == null) { line[prop] = null }
  5623. else {
  5624. var found = cur.match(classTest(cls))
  5625. if (!found) { return false }
  5626. var end = found.index + found[0].length
  5627. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5628. }
  5629. return true
  5630. })
  5631. }),
  5632. addLineWidget: docMethodOp(function(handle, node, options) {
  5633. return addLineWidget(this, handle, node, options)
  5634. }),
  5635. removeLineWidget: function(widget) { widget.clear() },
  5636. markText: function(from, to, options) {
  5637. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5638. },
  5639. setBookmark: function(pos, options) {
  5640. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5641. insertLeft: options && options.insertLeft,
  5642. clearWhenEmpty: false, shared: options && options.shared,
  5643. handleMouseEvents: options && options.handleMouseEvents}
  5644. pos = clipPos(this, pos)
  5645. return markText(this, pos, pos, realOpts, "bookmark")
  5646. },
  5647. findMarksAt: function(pos) {
  5648. pos = clipPos(this, pos)
  5649. var markers = [], spans = getLine(this, pos.line).markedSpans
  5650. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5651. var span = spans[i]
  5652. if ((span.from == null || span.from <= pos.ch) &&
  5653. (span.to == null || span.to >= pos.ch))
  5654. { markers.push(span.marker.parent || span.marker) }
  5655. } }
  5656. return markers
  5657. },
  5658. findMarks: function(from, to, filter) {
  5659. from = clipPos(this, from); to = clipPos(this, to)
  5660. var found = [], lineNo = from.line
  5661. this.iter(from.line, to.line + 1, function (line) {
  5662. var spans = line.markedSpans
  5663. if (spans) { for (var i = 0; i < spans.length; i++) {
  5664. var span = spans[i]
  5665. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5666. span.from == null && lineNo != from.line ||
  5667. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5668. (!filter || filter(span.marker)))
  5669. { found.push(span.marker.parent || span.marker) }
  5670. } }
  5671. ++lineNo
  5672. })
  5673. return found
  5674. },
  5675. getAllMarks: function() {
  5676. var markers = []
  5677. this.iter(function (line) {
  5678. var sps = line.markedSpans
  5679. if (sps) { for (var i = 0; i < sps.length; ++i)
  5680. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5681. })
  5682. return markers
  5683. },
  5684. posFromIndex: function(off) {
  5685. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5686. this.iter(function (line) {
  5687. var sz = line.text.length + sepSize
  5688. if (sz > off) { ch = off; return true }
  5689. off -= sz
  5690. ++lineNo
  5691. })
  5692. return clipPos(this, Pos(lineNo, ch))
  5693. },
  5694. indexFromPos: function (coords) {
  5695. coords = clipPos(this, coords)
  5696. var index = coords.ch
  5697. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5698. var sepSize = this.lineSeparator().length
  5699. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5700. index += line.text.length + sepSize
  5701. })
  5702. return index
  5703. },
  5704. copy: function(copyHistory) {
  5705. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5706. this.modeOption, this.first, this.lineSep, this.direction)
  5707. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5708. doc.sel = this.sel
  5709. doc.extend = false
  5710. if (copyHistory) {
  5711. doc.history.undoDepth = this.history.undoDepth
  5712. doc.setHistory(this.getHistory())
  5713. }
  5714. return doc
  5715. },
  5716. linkedDoc: function(options) {
  5717. if (!options) { options = {} }
  5718. var from = this.first, to = this.first + this.size
  5719. if (options.from != null && options.from > from) { from = options.from }
  5720. if (options.to != null && options.to < to) { to = options.to }
  5721. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)
  5722. if (options.sharedHist) { copy.history = this.history
  5723. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5724. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5725. copySharedMarkers(copy, findSharedMarkers(this))
  5726. return copy
  5727. },
  5728. unlinkDoc: function(other) {
  5729. var this$1 = this;
  5730. if (other instanceof CodeMirror) { other = other.doc }
  5731. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5732. var link = this$1.linked[i]
  5733. if (link.doc != other) { continue }
  5734. this$1.linked.splice(i, 1)
  5735. other.unlinkDoc(this$1)
  5736. detachSharedMarkers(findSharedMarkers(this$1))
  5737. break
  5738. } }
  5739. // If the histories were shared, split them again
  5740. if (other.history == this.history) {
  5741. var splitIds = [other.id]
  5742. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5743. other.history = new History(null)
  5744. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5745. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5746. }
  5747. },
  5748. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5749. getMode: function() {return this.mode},
  5750. getEditor: function() {return this.cm},
  5751. splitLines: function(str) {
  5752. if (this.lineSep) { return str.split(this.lineSep) }
  5753. return splitLinesAuto(str)
  5754. },
  5755. lineSeparator: function() { return this.lineSep || "\n" },
  5756. setDirection: docMethodOp(function (dir) {
  5757. if (dir != "rtl") { dir = "ltr" }
  5758. if (dir == this.direction) { return }
  5759. this.direction = dir
  5760. this.iter(function (line) { return line.order = null; })
  5761. if (this.cm) { directionChanged(this.cm) }
  5762. })
  5763. })
  5764. // Public alias.
  5765. Doc.prototype.eachLine = Doc.prototype.iter
  5766. // Kludge to work around strange IE behavior where it'll sometimes
  5767. // re-fire a series of drag-related events right after the drop (#1551)
  5768. var lastDrop = 0
  5769. function onDrop(e) {
  5770. var cm = this
  5771. clearDragCursor(cm)
  5772. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5773. { return }
  5774. e_preventDefault(e)
  5775. if (ie) { lastDrop = +new Date }
  5776. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5777. if (!pos || cm.isReadOnly()) { return }
  5778. // Might be a file drop, in which case we simply extract the text
  5779. // and insert it.
  5780. if (files && files.length && window.FileReader && window.File) {
  5781. var n = files.length, text = Array(n), read = 0
  5782. var loadFile = function (file, i) {
  5783. if (cm.options.allowDropFileTypes &&
  5784. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5785. { return }
  5786. var reader = new FileReader
  5787. reader.onload = operation(cm, function () {
  5788. var content = reader.result
  5789. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5790. text[i] = content
  5791. if (++read == n) {
  5792. pos = clipPos(cm.doc, pos)
  5793. var change = {from: pos, to: pos,
  5794. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5795. origin: "paste"}
  5796. makeChange(cm.doc, change)
  5797. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5798. }
  5799. })
  5800. reader.readAsText(file)
  5801. }
  5802. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5803. } else { // Normal drop
  5804. // Don't do a replace if the drop happened inside of the selected text.
  5805. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5806. cm.state.draggingText(e)
  5807. // Ensure the editor is re-focused
  5808. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5809. return
  5810. }
  5811. try {
  5812. var text$1 = e.dataTransfer.getData("Text")
  5813. if (text$1) {
  5814. var selected
  5815. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5816. { selected = cm.listSelections() }
  5817. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5818. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5819. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5820. cm.replaceSelection(text$1, "around", "paste")
  5821. cm.display.input.focus()
  5822. }
  5823. }
  5824. catch(e){}
  5825. }
  5826. }
  5827. function onDragStart(cm, e) {
  5828. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5829. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5830. e.dataTransfer.setData("Text", cm.getSelection())
  5831. e.dataTransfer.effectAllowed = "copyMove"
  5832. // Use dummy image instead of default browsers image.
  5833. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5834. if (e.dataTransfer.setDragImage && !safari) {
  5835. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5836. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5837. if (presto) {
  5838. img.width = img.height = 1
  5839. cm.display.wrapper.appendChild(img)
  5840. // Force a relayout, or Opera won't use our image for some obscure reason
  5841. img._top = img.offsetTop
  5842. }
  5843. e.dataTransfer.setDragImage(img, 0, 0)
  5844. if (presto) { img.parentNode.removeChild(img) }
  5845. }
  5846. }
  5847. function onDragOver(cm, e) {
  5848. var pos = posFromMouse(cm, e)
  5849. if (!pos) { return }
  5850. var frag = document.createDocumentFragment()
  5851. drawSelectionCursor(cm, pos, frag)
  5852. if (!cm.display.dragCursor) {
  5853. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5854. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5855. }
  5856. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5857. }
  5858. function clearDragCursor(cm) {
  5859. if (cm.display.dragCursor) {
  5860. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5861. cm.display.dragCursor = null
  5862. }
  5863. }
  5864. // These must be handled carefully, because naively registering a
  5865. // handler for each editor will cause the editors to never be
  5866. // garbage collected.
  5867. function forEachCodeMirror(f) {
  5868. if (!document.getElementsByClassName) { return }
  5869. var byClass = document.getElementsByClassName("CodeMirror")
  5870. for (var i = 0; i < byClass.length; i++) {
  5871. var cm = byClass[i].CodeMirror
  5872. if (cm) { f(cm) }
  5873. }
  5874. }
  5875. var globalsRegistered = false
  5876. function ensureGlobalHandlers() {
  5877. if (globalsRegistered) { return }
  5878. registerGlobalHandlers()
  5879. globalsRegistered = true
  5880. }
  5881. function registerGlobalHandlers() {
  5882. // When the window resizes, we need to refresh active editors.
  5883. var resizeTimer
  5884. on(window, "resize", function () {
  5885. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5886. resizeTimer = null
  5887. forEachCodeMirror(onResize)
  5888. }, 100) }
  5889. })
  5890. // When the window loses focus, we want to show the editor as blurred
  5891. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5892. }
  5893. // Called when the window resizes
  5894. function onResize(cm) {
  5895. var d = cm.display
  5896. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5897. { return }
  5898. // Might be a text scaling operation, clear size caches.
  5899. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5900. d.scrollbarsClipped = false
  5901. cm.setSize()
  5902. }
  5903. var keyNames = {
  5904. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5905. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5906. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5907. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5908. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5909. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5910. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5911. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5912. }
  5913. // Number keys
  5914. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5915. // Alphabetic keys
  5916. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5917. // Function keys
  5918. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5919. var keyMap = {}
  5920. keyMap.basic = {
  5921. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5922. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5923. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5924. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5925. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5926. "Esc": "singleSelection"
  5927. }
  5928. // Note that the save and find-related commands aren't defined by
  5929. // default. User code or addons can define them. Unknown commands
  5930. // are simply ignored.
  5931. keyMap.pcDefault = {
  5932. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5933. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5934. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5935. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5936. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5937. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5938. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5939. fallthrough: "basic"
  5940. }
  5941. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5942. keyMap.emacsy = {
  5943. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5944. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5945. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5946. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5947. "Ctrl-O": "openLine"
  5948. }
  5949. keyMap.macDefault = {
  5950. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5951. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5952. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5953. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5954. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5955. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5956. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5957. fallthrough: ["basic", "emacsy"]
  5958. }
  5959. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5960. // KEYMAP DISPATCH
  5961. function normalizeKeyName(name) {
  5962. var parts = name.split(/-(?!$)/)
  5963. name = parts[parts.length - 1]
  5964. var alt, ctrl, shift, cmd
  5965. for (var i = 0; i < parts.length - 1; i++) {
  5966. var mod = parts[i]
  5967. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5968. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5969. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5970. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5971. else { throw new Error("Unrecognized modifier name: " + mod) }
  5972. }
  5973. if (alt) { name = "Alt-" + name }
  5974. if (ctrl) { name = "Ctrl-" + name }
  5975. if (cmd) { name = "Cmd-" + name }
  5976. if (shift) { name = "Shift-" + name }
  5977. return name
  5978. }
  5979. // This is a kludge to keep keymaps mostly working as raw objects
  5980. // (backwards compatibility) while at the same time support features
  5981. // like normalization and multi-stroke key bindings. It compiles a
  5982. // new normalized keymap, and then updates the old object to reflect
  5983. // this.
  5984. function normalizeKeyMap(keymap) {
  5985. var copy = {}
  5986. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  5987. var value = keymap[keyname]
  5988. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  5989. if (value == "...") { delete keymap[keyname]; continue }
  5990. var keys = map(keyname.split(" "), normalizeKeyName)
  5991. for (var i = 0; i < keys.length; i++) {
  5992. var val = (void 0), name = (void 0)
  5993. if (i == keys.length - 1) {
  5994. name = keys.join(" ")
  5995. val = value
  5996. } else {
  5997. name = keys.slice(0, i + 1).join(" ")
  5998. val = "..."
  5999. }
  6000. var prev = copy[name]
  6001. if (!prev) { copy[name] = val }
  6002. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6003. }
  6004. delete keymap[keyname]
  6005. } }
  6006. for (var prop in copy) { keymap[prop] = copy[prop] }
  6007. return keymap
  6008. }
  6009. function lookupKey(key, map, handle, context) {
  6010. map = getKeyMap(map)
  6011. var found = map.call ? map.call(key, context) : map[key]
  6012. if (found === false) { return "nothing" }
  6013. if (found === "...") { return "multi" }
  6014. if (found != null && handle(found)) { return "handled" }
  6015. if (map.fallthrough) {
  6016. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6017. { return lookupKey(key, map.fallthrough, handle, context) }
  6018. for (var i = 0; i < map.fallthrough.length; i++) {
  6019. var result = lookupKey(key, map.fallthrough[i], handle, context)
  6020. if (result) { return result }
  6021. }
  6022. }
  6023. }
  6024. // Modifier key presses don't count as 'real' key presses for the
  6025. // purpose of keymap fallthrough.
  6026. function isModifierKey(value) {
  6027. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  6028. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6029. }
  6030. function addModifierNames(name, event, noShift) {
  6031. var base = name
  6032. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  6033. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  6034. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  6035. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  6036. return name
  6037. }
  6038. // Look up the name of a key as indicated by an event object.
  6039. function keyName(event, noShift) {
  6040. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6041. var name = keyNames[event.keyCode]
  6042. if (name == null || event.altGraphKey) { return false }
  6043. return addModifierNames(name, event, noShift)
  6044. }
  6045. function getKeyMap(val) {
  6046. return typeof val == "string" ? keyMap[val] : val
  6047. }
  6048. // Helper for deleting text near the selection(s), used to implement
  6049. // backspace, delete, and similar functionality.
  6050. function deleteNearSelection(cm, compute) {
  6051. var ranges = cm.doc.sel.ranges, kill = []
  6052. // Build up a set of ranges to kill first, merging overlapping
  6053. // ranges.
  6054. for (var i = 0; i < ranges.length; i++) {
  6055. var toKill = compute(ranges[i])
  6056. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6057. var replaced = kill.pop()
  6058. if (cmp(replaced.from, toKill.from) < 0) {
  6059. toKill.from = replaced.from
  6060. break
  6061. }
  6062. }
  6063. kill.push(toKill)
  6064. }
  6065. // Next, remove those actual ranges.
  6066. runInOp(cm, function () {
  6067. for (var i = kill.length - 1; i >= 0; i--)
  6068. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  6069. ensureCursorVisible(cm)
  6070. })
  6071. }
  6072. // Commands are parameter-less actions that can be performed on an
  6073. // editor, mostly used for keybindings.
  6074. var commands = {
  6075. selectAll: selectAll,
  6076. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6077. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6078. if (range.empty()) {
  6079. var len = getLine(cm.doc, range.head.line).text.length
  6080. if (range.head.ch == len && range.head.line < cm.lastLine())
  6081. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6082. else
  6083. { return {from: range.head, to: Pos(range.head.line, len)} }
  6084. } else {
  6085. return {from: range.from(), to: range.to()}
  6086. }
  6087. }); },
  6088. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6089. from: Pos(range.from().line, 0),
  6090. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6091. }); }); },
  6092. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6093. from: Pos(range.from().line, 0), to: range.from()
  6094. }); }); },
  6095. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6096. var top = cm.charCoords(range.head, "div").top + 5
  6097. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  6098. return {from: leftPos, to: range.from()}
  6099. }); },
  6100. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6101. var top = cm.charCoords(range.head, "div").top + 5
  6102. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6103. return {from: range.from(), to: rightPos }
  6104. }); },
  6105. undo: function (cm) { return cm.undo(); },
  6106. redo: function (cm) { return cm.redo(); },
  6107. undoSelection: function (cm) { return cm.undoSelection(); },
  6108. redoSelection: function (cm) { return cm.redoSelection(); },
  6109. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6110. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6111. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6112. {origin: "+move", bias: 1}
  6113. ); },
  6114. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6115. {origin: "+move", bias: 1}
  6116. ); },
  6117. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6118. {origin: "+move", bias: -1}
  6119. ); },
  6120. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6121. var top = cm.cursorCoords(range.head, "div").top + 5
  6122. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6123. }, sel_move); },
  6124. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6125. var top = cm.cursorCoords(range.head, "div").top + 5
  6126. return cm.coordsChar({left: 0, top: top}, "div")
  6127. }, sel_move); },
  6128. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6129. var top = cm.cursorCoords(range.head, "div").top + 5
  6130. var pos = cm.coordsChar({left: 0, top: top}, "div")
  6131. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6132. return pos
  6133. }, sel_move); },
  6134. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6135. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6136. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6137. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6138. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6139. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6140. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6141. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6142. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6143. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6144. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6145. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6146. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6147. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6148. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6149. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6150. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6151. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6152. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6153. indentMore: function (cm) { return cm.indentSelection("add"); },
  6154. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6155. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6156. insertSoftTab: function (cm) {
  6157. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  6158. for (var i = 0; i < ranges.length; i++) {
  6159. var pos = ranges[i].from()
  6160. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  6161. spaces.push(spaceStr(tabSize - col % tabSize))
  6162. }
  6163. cm.replaceSelections(spaces)
  6164. },
  6165. defaultTab: function (cm) {
  6166. if (cm.somethingSelected()) { cm.indentSelection("add") }
  6167. else { cm.execCommand("insertTab") }
  6168. },
  6169. // Swap the two chars left and right of each selection's head.
  6170. // Move cursor behind the two swapped characters afterwards.
  6171. //
  6172. // Doesn't consider line feeds a character.
  6173. // Doesn't scan more than one line above to find a character.
  6174. // Doesn't do anything on an empty line.
  6175. // Doesn't do anything with non-empty selections.
  6176. transposeChars: function (cm) { return runInOp(cm, function () {
  6177. var ranges = cm.listSelections(), newSel = []
  6178. for (var i = 0; i < ranges.length; i++) {
  6179. if (!ranges[i].empty()) { continue }
  6180. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  6181. if (line) {
  6182. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  6183. if (cur.ch > 0) {
  6184. cur = new Pos(cur.line, cur.ch + 1)
  6185. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6186. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  6187. } else if (cur.line > cm.doc.first) {
  6188. var prev = getLine(cm.doc, cur.line - 1).text
  6189. if (prev) {
  6190. cur = new Pos(cur.line, 1)
  6191. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6192. prev.charAt(prev.length - 1),
  6193. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  6194. }
  6195. }
  6196. }
  6197. newSel.push(new Range(cur, cur))
  6198. }
  6199. cm.setSelections(newSel)
  6200. }); },
  6201. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6202. var sels = cm.listSelections()
  6203. for (var i = sels.length - 1; i >= 0; i--)
  6204. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  6205. sels = cm.listSelections()
  6206. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6207. { cm.indentLine(sels[i$1].from().line, null, true) }
  6208. ensureCursorVisible(cm)
  6209. }); },
  6210. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6211. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6212. }
  6213. function lineStart(cm, lineN) {
  6214. var line = getLine(cm.doc, lineN)
  6215. var visual = visualLine(line)
  6216. if (visual != line) { lineN = lineNo(visual) }
  6217. return endOfLine(true, cm, visual, lineN, 1)
  6218. }
  6219. function lineEnd(cm, lineN) {
  6220. var line = getLine(cm.doc, lineN)
  6221. var visual = visualLineEnd(line)
  6222. if (visual != line) { lineN = lineNo(visual) }
  6223. return endOfLine(true, cm, line, lineN, -1)
  6224. }
  6225. function lineStartSmart(cm, pos) {
  6226. var start = lineStart(cm, pos.line)
  6227. var line = getLine(cm.doc, start.line)
  6228. var order = getOrder(line, cm.doc.direction)
  6229. if (!order || order[0].level == 0) {
  6230. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6231. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6232. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6233. }
  6234. return start
  6235. }
  6236. // Run a handler that was bound to a key.
  6237. function doHandleBinding(cm, bound, dropShift) {
  6238. if (typeof bound == "string") {
  6239. bound = commands[bound]
  6240. if (!bound) { return false }
  6241. }
  6242. // Ensure previous input has been read, so that the handler sees a
  6243. // consistent view of the document
  6244. cm.display.input.ensurePolled()
  6245. var prevShift = cm.display.shift, done = false
  6246. try {
  6247. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6248. if (dropShift) { cm.display.shift = false }
  6249. done = bound(cm) != Pass
  6250. } finally {
  6251. cm.display.shift = prevShift
  6252. cm.state.suppressEdits = false
  6253. }
  6254. return done
  6255. }
  6256. function lookupKeyForEditor(cm, name, handle) {
  6257. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6258. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6259. if (result) { return result }
  6260. }
  6261. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6262. || lookupKey(name, cm.options.keyMap, handle, cm)
  6263. }
  6264. // Note that, despite the name, this function is also used to check
  6265. // for bound mouse clicks.
  6266. var stopSeq = new Delayed
  6267. function dispatchKey(cm, name, e, handle) {
  6268. var seq = cm.state.keySeq
  6269. if (seq) {
  6270. if (isModifierKey(name)) { return "handled" }
  6271. stopSeq.set(50, function () {
  6272. if (cm.state.keySeq == seq) {
  6273. cm.state.keySeq = null
  6274. cm.display.input.reset()
  6275. }
  6276. })
  6277. name = seq + " " + name
  6278. }
  6279. var result = lookupKeyForEditor(cm, name, handle)
  6280. if (result == "multi")
  6281. { cm.state.keySeq = name }
  6282. if (result == "handled")
  6283. { signalLater(cm, "keyHandled", cm, name, e) }
  6284. if (result == "handled" || result == "multi") {
  6285. e_preventDefault(e)
  6286. restartBlink(cm)
  6287. }
  6288. if (seq && !result && /\'$/.test(name)) {
  6289. e_preventDefault(e)
  6290. return true
  6291. }
  6292. return !!result
  6293. }
  6294. // Handle a key from the keydown event.
  6295. function handleKeyBinding(cm, e) {
  6296. var name = keyName(e, true)
  6297. if (!name) { return false }
  6298. if (e.shiftKey && !cm.state.keySeq) {
  6299. // First try to resolve full name (including 'Shift-'). Failing
  6300. // that, see if there is a cursor-motion command (starting with
  6301. // 'go') bound to the keyname without 'Shift-'.
  6302. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6303. || dispatchKey(cm, name, e, function (b) {
  6304. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6305. { return doHandleBinding(cm, b) }
  6306. })
  6307. } else {
  6308. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6309. }
  6310. }
  6311. // Handle a key from the keypress event
  6312. function handleCharBinding(cm, e, ch) {
  6313. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6314. }
  6315. var lastStoppedKey = null
  6316. function onKeyDown(e) {
  6317. var cm = this
  6318. cm.curOp.focus = activeElt()
  6319. if (signalDOMEvent(cm, e)) { return }
  6320. // IE does strange things with escape.
  6321. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6322. var code = e.keyCode
  6323. cm.display.shift = code == 16 || e.shiftKey
  6324. var handled = handleKeyBinding(cm, e)
  6325. if (presto) {
  6326. lastStoppedKey = handled ? code : null
  6327. // Opera has no cut event... we try to at least catch the key combo
  6328. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6329. { cm.replaceSelection("", null, "cut") }
  6330. }
  6331. // Turn mouse into crosshair when Alt is held on Mac.
  6332. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6333. { showCrossHair(cm) }
  6334. }
  6335. function showCrossHair(cm) {
  6336. var lineDiv = cm.display.lineDiv
  6337. addClass(lineDiv, "CodeMirror-crosshair")
  6338. function up(e) {
  6339. if (e.keyCode == 18 || !e.altKey) {
  6340. rmClass(lineDiv, "CodeMirror-crosshair")
  6341. off(document, "keyup", up)
  6342. off(document, "mouseover", up)
  6343. }
  6344. }
  6345. on(document, "keyup", up)
  6346. on(document, "mouseover", up)
  6347. }
  6348. function onKeyUp(e) {
  6349. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6350. signalDOMEvent(this, e)
  6351. }
  6352. function onKeyPress(e) {
  6353. var cm = this
  6354. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6355. var keyCode = e.keyCode, charCode = e.charCode
  6356. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6357. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6358. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6359. // Some browsers fire keypress events for backspace
  6360. if (ch == "\x08") { return }
  6361. if (handleCharBinding(cm, e, ch)) { return }
  6362. cm.display.input.onKeyPress(e)
  6363. }
  6364. var DOUBLECLICK_DELAY = 400
  6365. var PastClick = function(time, pos, button) {
  6366. this.time = time
  6367. this.pos = pos
  6368. this.button = button
  6369. };
  6370. PastClick.prototype.compare = function (time, pos, button) {
  6371. return this.time + DOUBLECLICK_DELAY > time &&
  6372. cmp(pos, this.pos) == 0 && button == this.button
  6373. };
  6374. var lastClick;
  6375. var lastDoubleClick;
  6376. function clickRepeat(pos, button) {
  6377. var now = +new Date
  6378. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6379. lastClick = lastDoubleClick = null
  6380. return "triple"
  6381. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6382. lastDoubleClick = new PastClick(now, pos, button)
  6383. lastClick = null
  6384. return "double"
  6385. } else {
  6386. lastClick = new PastClick(now, pos, button)
  6387. lastDoubleClick = null
  6388. return "single"
  6389. }
  6390. }
  6391. // A mouse down can be a single click, double click, triple click,
  6392. // start of selection drag, start of text drag, new cursor
  6393. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6394. // middle-click-paste. Or it might be a click on something we should
  6395. // not interfere with, such as a scrollbar or widget.
  6396. function onMouseDown(e) {
  6397. var cm = this, display = cm.display
  6398. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6399. display.input.ensurePolled()
  6400. display.shift = e.shiftKey
  6401. if (eventInWidget(display, e)) {
  6402. if (!webkit) {
  6403. // Briefly turn off draggability, to allow widgets to do
  6404. // normal dragging things.
  6405. display.scroller.draggable = false
  6406. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6407. }
  6408. return
  6409. }
  6410. if (clickInGutter(cm, e)) { return }
  6411. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"
  6412. window.focus()
  6413. // #3261: make sure, that we're not starting a second selection
  6414. if (button == 1 && cm.state.selectingText)
  6415. { cm.state.selectingText(e) }
  6416. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6417. if (button == 1) {
  6418. if (pos) { leftButtonDown(cm, pos, repeat, e) }
  6419. else if (e_target(e) == display.scroller) { e_preventDefault(e) }
  6420. } else if (button == 2) {
  6421. if (pos) { extendSelection(cm.doc, pos) }
  6422. setTimeout(function () { return display.input.focus(); }, 20)
  6423. } else if (button == 3) {
  6424. if (captureRightClick) { onContextMenu(cm, e) }
  6425. else { delayBlurEvent(cm) }
  6426. }
  6427. }
  6428. function handleMappedButton(cm, button, pos, repeat, event) {
  6429. var name = "Click"
  6430. if (repeat == "double") { name = "Double" + name }
  6431. else if (repeat == "triple") { name = "Triple" + name }
  6432. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name
  6433. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6434. if (typeof bound == "string") { bound = commands[bound] }
  6435. if (!bound) { return false }
  6436. var done = false
  6437. try {
  6438. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6439. done = bound(cm, pos) != Pass
  6440. } finally {
  6441. cm.state.suppressEdits = false
  6442. }
  6443. return done
  6444. })
  6445. }
  6446. function configureMouse(cm, repeat, event) {
  6447. var option = cm.getOption("configureMouse")
  6448. var value = option ? option(cm, repeat, event) : {}
  6449. if (value.unit == null) {
  6450. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  6451. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"
  6452. }
  6453. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey }
  6454. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey }
  6455. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) }
  6456. return value
  6457. }
  6458. function leftButtonDown(cm, pos, repeat, event) {
  6459. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6460. else { cm.curOp.focus = activeElt() }
  6461. var behavior = configureMouse(cm, repeat, event)
  6462. var sel = cm.doc.sel, contained
  6463. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6464. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6465. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6466. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6467. { leftButtonStartDrag(cm, event, pos, behavior) }
  6468. else
  6469. { leftButtonSelect(cm, event, pos, behavior) }
  6470. }
  6471. // Start a text drag. When it ends, see if any dragging actually
  6472. // happen, and treat as a click if it didn't.
  6473. function leftButtonStartDrag(cm, event, pos, behavior) {
  6474. var display = cm.display, moved = false
  6475. var dragEnd = operation(cm, function (e) {
  6476. if (webkit) { display.scroller.draggable = false }
  6477. cm.state.draggingText = false
  6478. off(document, "mouseup", dragEnd)
  6479. off(document, "mousemove", mouseMove)
  6480. off(display.scroller, "dragstart", dragStart)
  6481. off(display.scroller, "drop", dragEnd)
  6482. if (!moved) {
  6483. e_preventDefault(e)
  6484. if (!behavior.addNew)
  6485. { extendSelection(cm.doc, pos, null, null, behavior.extend) }
  6486. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6487. if (webkit || ie && ie_version == 9)
  6488. { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
  6489. else
  6490. { display.input.focus() }
  6491. }
  6492. })
  6493. var mouseMove = function(e2) {
  6494. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  6495. }
  6496. var dragStart = function () { return moved = true; }
  6497. // Let the drag handler handle this.
  6498. if (webkit) { display.scroller.draggable = true }
  6499. cm.state.draggingText = dragEnd
  6500. dragEnd.copy = !behavior.moveOnDrag
  6501. // IE's approach to draggable
  6502. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6503. on(document, "mouseup", dragEnd)
  6504. on(document, "mousemove", mouseMove)
  6505. on(display.scroller, "dragstart", dragStart)
  6506. on(display.scroller, "drop", dragEnd)
  6507. delayBlurEvent(cm)
  6508. setTimeout(function () { return display.input.focus(); }, 20)
  6509. }
  6510. function rangeForUnit(cm, pos, unit) {
  6511. if (unit == "char") { return new Range(pos, pos) }
  6512. if (unit == "word") { return cm.findWordAt(pos) }
  6513. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6514. var result = unit(cm, pos)
  6515. return new Range(result.from, result.to)
  6516. }
  6517. // Normal selection, as opposed to text dragging.
  6518. function leftButtonSelect(cm, event, start, behavior) {
  6519. var display = cm.display, doc = cm.doc
  6520. e_preventDefault(event)
  6521. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6522. if (behavior.addNew && !behavior.extend) {
  6523. ourIndex = doc.sel.contains(start)
  6524. if (ourIndex > -1)
  6525. { ourRange = ranges[ourIndex] }
  6526. else
  6527. { ourRange = new Range(start, start) }
  6528. } else {
  6529. ourRange = doc.sel.primary()
  6530. ourIndex = doc.sel.primIndex
  6531. }
  6532. if (behavior.unit == "rectangle") {
  6533. if (!behavior.addNew) { ourRange = new Range(start, start) }
  6534. start = posFromMouse(cm, event, true, true)
  6535. ourIndex = -1
  6536. } else {
  6537. var range = rangeForUnit(cm, start, behavior.unit)
  6538. if (behavior.extend)
  6539. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) }
  6540. else
  6541. { ourRange = range }
  6542. }
  6543. if (!behavior.addNew) {
  6544. ourIndex = 0
  6545. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6546. startSel = doc.sel
  6547. } else if (ourIndex == -1) {
  6548. ourIndex = ranges.length
  6549. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6550. {scroll: false, origin: "*mouse"})
  6551. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6552. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6553. {scroll: false, origin: "*mouse"})
  6554. startSel = doc.sel
  6555. } else {
  6556. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6557. }
  6558. var lastPos = start
  6559. function extendTo(pos) {
  6560. if (cmp(lastPos, pos) == 0) { return }
  6561. lastPos = pos
  6562. if (behavior.unit == "rectangle") {
  6563. var ranges = [], tabSize = cm.options.tabSize
  6564. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6565. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6566. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6567. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6568. line <= end; line++) {
  6569. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6570. if (left == right)
  6571. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6572. else if (text.length > leftPos)
  6573. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6574. }
  6575. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6576. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6577. {origin: "*mouse", scroll: false})
  6578. cm.scrollIntoView(pos)
  6579. } else {
  6580. var oldRange = ourRange
  6581. var range = rangeForUnit(cm, pos, behavior.unit)
  6582. var anchor = oldRange.anchor, head
  6583. if (cmp(range.anchor, anchor) > 0) {
  6584. head = range.head
  6585. anchor = minPos(oldRange.from(), range.anchor)
  6586. } else {
  6587. head = range.anchor
  6588. anchor = maxPos(oldRange.to(), range.head)
  6589. }
  6590. var ranges$1 = startSel.ranges.slice(0)
  6591. ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head)
  6592. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6593. }
  6594. }
  6595. var editorSize = display.wrapper.getBoundingClientRect()
  6596. // Used to ensure timeout re-tries don't fire when another extend
  6597. // happened in the meantime (clearTimeout isn't reliable -- at
  6598. // least on Chrome, the timeouts still happen even when cleared,
  6599. // if the clear happens after their scheduled firing time).
  6600. var counter = 0
  6601. function extend(e) {
  6602. var curCount = ++counter
  6603. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle")
  6604. if (!cur) { return }
  6605. if (cmp(cur, lastPos) != 0) {
  6606. cm.curOp.focus = activeElt()
  6607. extendTo(cur)
  6608. var visible = visibleLines(display, doc)
  6609. if (cur.line >= visible.to || cur.line < visible.from)
  6610. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6611. } else {
  6612. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6613. if (outside) { setTimeout(operation(cm, function () {
  6614. if (counter != curCount) { return }
  6615. display.scroller.scrollTop += outside
  6616. extend(e)
  6617. }), 50) }
  6618. }
  6619. }
  6620. function done(e) {
  6621. cm.state.selectingText = false
  6622. counter = Infinity
  6623. e_preventDefault(e)
  6624. display.input.focus()
  6625. off(document, "mousemove", move)
  6626. off(document, "mouseup", up)
  6627. doc.history.lastSelOrigin = null
  6628. }
  6629. var move = operation(cm, function (e) {
  6630. if (!e_button(e)) { done(e) }
  6631. else { extend(e) }
  6632. })
  6633. var up = operation(cm, done)
  6634. cm.state.selectingText = up
  6635. on(document, "mousemove", move)
  6636. on(document, "mouseup", up)
  6637. }
  6638. // Determines whether an event happened in the gutter, and fires the
  6639. // handlers for the corresponding event.
  6640. function gutterEvent(cm, e, type, prevent) {
  6641. var mX, mY
  6642. try { mX = e.clientX; mY = e.clientY }
  6643. catch(e) { return false }
  6644. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6645. if (prevent) { e_preventDefault(e) }
  6646. var display = cm.display
  6647. var lineBox = display.lineDiv.getBoundingClientRect()
  6648. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6649. mY -= lineBox.top - display.viewOffset
  6650. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6651. var g = display.gutters.childNodes[i]
  6652. if (g && g.getBoundingClientRect().right >= mX) {
  6653. var line = lineAtHeight(cm.doc, mY)
  6654. var gutter = cm.options.gutters[i]
  6655. signal(cm, type, cm, line, gutter, e)
  6656. return e_defaultPrevented(e)
  6657. }
  6658. }
  6659. }
  6660. function clickInGutter(cm, e) {
  6661. return gutterEvent(cm, e, "gutterClick", true)
  6662. }
  6663. // CONTEXT MENU HANDLING
  6664. // To make the context menu work, we need to briefly unhide the
  6665. // textarea (making it as unobtrusive as possible) to let the
  6666. // right-click take effect on it.
  6667. function onContextMenu(cm, e) {
  6668. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6669. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6670. cm.display.input.onContextMenu(e)
  6671. }
  6672. function contextMenuInGutter(cm, e) {
  6673. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6674. return gutterEvent(cm, e, "gutterContextMenu", false)
  6675. }
  6676. function themeChanged(cm) {
  6677. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6678. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6679. clearCaches(cm)
  6680. }
  6681. var Init = {toString: function(){return "CodeMirror.Init"}}
  6682. var defaults = {}
  6683. var optionHandlers = {}
  6684. function defineOptions(CodeMirror) {
  6685. var optionHandlers = CodeMirror.optionHandlers
  6686. function option(name, deflt, handle, notOnInit) {
  6687. CodeMirror.defaults[name] = deflt
  6688. if (handle) { optionHandlers[name] =
  6689. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6690. }
  6691. CodeMirror.defineOption = option
  6692. // Passed to option handlers when there is no old value.
  6693. CodeMirror.Init = Init
  6694. // These two are, on init, called from the constructor because they
  6695. // have to be initialized before the editor can start at all.
  6696. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6697. option("mode", null, function (cm, val) {
  6698. cm.doc.modeOption = val
  6699. loadMode(cm)
  6700. }, true)
  6701. option("indentUnit", 2, loadMode, true)
  6702. option("indentWithTabs", false)
  6703. option("smartIndent", true)
  6704. option("tabSize", 4, function (cm) {
  6705. resetModeState(cm)
  6706. clearCaches(cm)
  6707. regChange(cm)
  6708. }, true)
  6709. option("lineSeparator", null, function (cm, val) {
  6710. cm.doc.lineSep = val
  6711. if (!val) { return }
  6712. var newBreaks = [], lineNo = cm.doc.first
  6713. cm.doc.iter(function (line) {
  6714. for (var pos = 0;;) {
  6715. var found = line.text.indexOf(val, pos)
  6716. if (found == -1) { break }
  6717. pos = found + val.length
  6718. newBreaks.push(Pos(lineNo, found))
  6719. }
  6720. lineNo++
  6721. })
  6722. for (var i = newBreaks.length - 1; i >= 0; i--)
  6723. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6724. })
  6725. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6726. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6727. if (old != Init) { cm.refresh() }
  6728. })
  6729. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6730. option("electricChars", true)
  6731. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6732. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6733. }, true)
  6734. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6735. option("rtlMoveVisually", !windows)
  6736. option("wholeLineUpdateBefore", true)
  6737. option("theme", "default", function (cm) {
  6738. themeChanged(cm)
  6739. guttersChanged(cm)
  6740. }, true)
  6741. option("keyMap", "default", function (cm, val, old) {
  6742. var next = getKeyMap(val)
  6743. var prev = old != Init && getKeyMap(old)
  6744. if (prev && prev.detach) { prev.detach(cm, next) }
  6745. if (next.attach) { next.attach(cm, prev || null) }
  6746. })
  6747. option("extraKeys", null)
  6748. option("configureMouse", null)
  6749. option("lineWrapping", false, wrappingChanged, true)
  6750. option("gutters", [], function (cm) {
  6751. setGuttersForLineNumbers(cm.options)
  6752. guttersChanged(cm)
  6753. }, true)
  6754. option("fixedGutter", true, function (cm, val) {
  6755. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6756. cm.refresh()
  6757. }, true)
  6758. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6759. option("scrollbarStyle", "native", function (cm) {
  6760. initScrollbars(cm)
  6761. updateScrollbars(cm)
  6762. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6763. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6764. }, true)
  6765. option("lineNumbers", false, function (cm) {
  6766. setGuttersForLineNumbers(cm.options)
  6767. guttersChanged(cm)
  6768. }, true)
  6769. option("firstLineNumber", 1, guttersChanged, true)
  6770. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6771. option("showCursorWhenSelecting", false, updateSelection, true)
  6772. option("resetSelectionOnContextMenu", true)
  6773. option("lineWiseCopyCut", true)
  6774. option("pasteLinesPerSelection", true)
  6775. option("readOnly", false, function (cm, val) {
  6776. if (val == "nocursor") {
  6777. onBlur(cm)
  6778. cm.display.input.blur()
  6779. }
  6780. cm.display.input.readOnlyChanged(val)
  6781. })
  6782. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6783. option("dragDrop", true, dragDropChanged)
  6784. option("allowDropFileTypes", null)
  6785. option("cursorBlinkRate", 530)
  6786. option("cursorScrollMargin", 0)
  6787. option("cursorHeight", 1, updateSelection, true)
  6788. option("singleCursorHeightPerLine", true, updateSelection, true)
  6789. option("workTime", 100)
  6790. option("workDelay", 100)
  6791. option("flattenSpans", true, resetModeState, true)
  6792. option("addModeClass", false, resetModeState, true)
  6793. option("pollInterval", 100)
  6794. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6795. option("historyEventDelay", 1250)
  6796. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6797. option("maxHighlightLength", 10000, resetModeState, true)
  6798. option("moveInputWithCursor", true, function (cm, val) {
  6799. if (!val) { cm.display.input.resetPosition() }
  6800. })
  6801. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6802. option("autofocus", null)
  6803. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true)
  6804. }
  6805. function guttersChanged(cm) {
  6806. updateGutters(cm)
  6807. regChange(cm)
  6808. alignHorizontally(cm)
  6809. }
  6810. function dragDropChanged(cm, value, old) {
  6811. var wasOn = old && old != Init
  6812. if (!value != !wasOn) {
  6813. var funcs = cm.display.dragFunctions
  6814. var toggle = value ? on : off
  6815. toggle(cm.display.scroller, "dragstart", funcs.start)
  6816. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6817. toggle(cm.display.scroller, "dragover", funcs.over)
  6818. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6819. toggle(cm.display.scroller, "drop", funcs.drop)
  6820. }
  6821. }
  6822. function wrappingChanged(cm) {
  6823. if (cm.options.lineWrapping) {
  6824. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6825. cm.display.sizer.style.minWidth = ""
  6826. cm.display.sizerWidth = null
  6827. } else {
  6828. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6829. findMaxLine(cm)
  6830. }
  6831. estimateLineHeights(cm)
  6832. regChange(cm)
  6833. clearCaches(cm)
  6834. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6835. }
  6836. // A CodeMirror instance represents an editor. This is the object
  6837. // that user code is usually dealing with.
  6838. function CodeMirror(place, options) {
  6839. var this$1 = this;
  6840. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  6841. this.options = options = options ? copyObj(options) : {}
  6842. // Determine effective options based on given values and defaults.
  6843. copyObj(defaults, options, false)
  6844. setGuttersForLineNumbers(options)
  6845. var doc = options.value
  6846. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) }
  6847. this.doc = doc
  6848. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  6849. var display = this.display = new Display(place, doc, input)
  6850. display.wrapper.CodeMirror = this
  6851. updateGutters(this)
  6852. themeChanged(this)
  6853. if (options.lineWrapping)
  6854. { this.display.wrapper.className += " CodeMirror-wrap" }
  6855. initScrollbars(this)
  6856. this.state = {
  6857. keyMaps: [], // stores maps added by addKeyMap
  6858. overlays: [], // highlighting overlays, as added by addOverlay
  6859. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  6860. overwrite: false,
  6861. delayingBlurEvent: false,
  6862. focused: false,
  6863. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  6864. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  6865. selectingText: false,
  6866. draggingText: false,
  6867. highlight: new Delayed(), // stores highlight worker timeout
  6868. keySeq: null, // Unfinished key sequence
  6869. specialChars: null
  6870. }
  6871. if (options.autofocus && !mobile) { display.input.focus() }
  6872. // Override magic textarea content restore that IE sometimes does
  6873. // on our hidden textarea on reload
  6874. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  6875. registerEventHandlers(this)
  6876. ensureGlobalHandlers()
  6877. startOperation(this)
  6878. this.curOp.forceUpdate = true
  6879. attachDoc(this, doc)
  6880. if ((options.autofocus && !mobile) || this.hasFocus())
  6881. { setTimeout(bind(onFocus, this), 20) }
  6882. else
  6883. { onBlur(this) }
  6884. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  6885. { optionHandlers[opt](this$1, options[opt], Init) } }
  6886. maybeUpdateLineNumberWidth(this)
  6887. if (options.finishInit) { options.finishInit(this) }
  6888. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  6889. endOperation(this)
  6890. // Suppress optimizelegibility in Webkit, since it breaks text
  6891. // measuring on line wrapping boundaries.
  6892. if (webkit && options.lineWrapping &&
  6893. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  6894. { display.lineDiv.style.textRendering = "auto" }
  6895. }
  6896. // The default configuration options.
  6897. CodeMirror.defaults = defaults
  6898. // Functions to run when options are changed.
  6899. CodeMirror.optionHandlers = optionHandlers
  6900. // Attach the necessary event handlers when initializing the editor
  6901. function registerEventHandlers(cm) {
  6902. var d = cm.display
  6903. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  6904. // Older IE's will not fire a second mousedown for a double click
  6905. if (ie && ie_version < 11)
  6906. { on(d.scroller, "dblclick", operation(cm, function (e) {
  6907. if (signalDOMEvent(cm, e)) { return }
  6908. var pos = posFromMouse(cm, e)
  6909. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  6910. e_preventDefault(e)
  6911. var word = cm.findWordAt(pos)
  6912. extendSelection(cm.doc, word.anchor, word.head)
  6913. })) }
  6914. else
  6915. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  6916. // Some browsers fire contextmenu *after* opening the menu, at
  6917. // which point we can't mess with it anymore. Context menu is
  6918. // handled in onMouseDown for these browsers.
  6919. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  6920. // Used to suppress mouse event handling when a touch happens
  6921. var touchFinished, prevTouch = {end: 0}
  6922. function finishTouch() {
  6923. if (d.activeTouch) {
  6924. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  6925. prevTouch = d.activeTouch
  6926. prevTouch.end = +new Date
  6927. }
  6928. }
  6929. function isMouseLikeTouchEvent(e) {
  6930. if (e.touches.length != 1) { return false }
  6931. var touch = e.touches[0]
  6932. return touch.radiusX <= 1 && touch.radiusY <= 1
  6933. }
  6934. function farAway(touch, other) {
  6935. if (other.left == null) { return true }
  6936. var dx = other.left - touch.left, dy = other.top - touch.top
  6937. return dx * dx + dy * dy > 20 * 20
  6938. }
  6939. on(d.scroller, "touchstart", function (e) {
  6940. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  6941. d.input.ensurePolled()
  6942. clearTimeout(touchFinished)
  6943. var now = +new Date
  6944. d.activeTouch = {start: now, moved: false,
  6945. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  6946. if (e.touches.length == 1) {
  6947. d.activeTouch.left = e.touches[0].pageX
  6948. d.activeTouch.top = e.touches[0].pageY
  6949. }
  6950. }
  6951. })
  6952. on(d.scroller, "touchmove", function () {
  6953. if (d.activeTouch) { d.activeTouch.moved = true }
  6954. })
  6955. on(d.scroller, "touchend", function (e) {
  6956. var touch = d.activeTouch
  6957. if (touch && !eventInWidget(d, e) && touch.left != null &&
  6958. !touch.moved && new Date - touch.start < 300) {
  6959. var pos = cm.coordsChar(d.activeTouch, "page"), range
  6960. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  6961. { range = new Range(pos, pos) }
  6962. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  6963. { range = cm.findWordAt(pos) }
  6964. else // Triple tap
  6965. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6966. cm.setSelection(range.anchor, range.head)
  6967. cm.focus()
  6968. e_preventDefault(e)
  6969. }
  6970. finishTouch()
  6971. })
  6972. on(d.scroller, "touchcancel", finishTouch)
  6973. // Sync scrolling between fake scrollbars and real scrollable
  6974. // area, ensure viewport is updated when scrolling.
  6975. on(d.scroller, "scroll", function () {
  6976. if (d.scroller.clientHeight) {
  6977. updateScrollTop(cm, d.scroller.scrollTop)
  6978. setScrollLeft(cm, d.scroller.scrollLeft, true)
  6979. signal(cm, "scroll", cm)
  6980. }
  6981. })
  6982. // Listen to wheel events in order to try and update the viewport on time.
  6983. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  6984. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  6985. // Prevent wrapper from ever scrolling
  6986. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  6987. d.dragFunctions = {
  6988. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  6989. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  6990. start: function (e) { return onDragStart(cm, e); },
  6991. drop: operation(cm, onDrop),
  6992. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  6993. }
  6994. var inp = d.input.getField()
  6995. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  6996. on(inp, "keydown", operation(cm, onKeyDown))
  6997. on(inp, "keypress", operation(cm, onKeyPress))
  6998. on(inp, "focus", function (e) { return onFocus(cm, e); })
  6999. on(inp, "blur", function (e) { return onBlur(cm, e); })
  7000. }
  7001. var initHooks = []
  7002. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  7003. // Indent the given line. The how parameter can be "smart",
  7004. // "add"/null, "subtract", or "prev". When aggressive is false
  7005. // (typically set to true for forced single-line indents), empty
  7006. // lines are not indented, and places where the mode returns Pass
  7007. // are left alone.
  7008. function indentLine(cm, n, how, aggressive) {
  7009. var doc = cm.doc, state
  7010. if (how == null) { how = "add" }
  7011. if (how == "smart") {
  7012. // Fall back to "prev" when the mode doesn't have an indentation
  7013. // method.
  7014. if (!doc.mode.indent) { how = "prev" }
  7015. else { state = getContextBefore(cm, n).state }
  7016. }
  7017. var tabSize = cm.options.tabSize
  7018. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  7019. if (line.stateAfter) { line.stateAfter = null }
  7020. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  7021. if (!aggressive && !/\S/.test(line.text)) {
  7022. indentation = 0
  7023. how = "not"
  7024. } else if (how == "smart") {
  7025. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  7026. if (indentation == Pass || indentation > 150) {
  7027. if (!aggressive) { return }
  7028. how = "prev"
  7029. }
  7030. }
  7031. if (how == "prev") {
  7032. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  7033. else { indentation = 0 }
  7034. } else if (how == "add") {
  7035. indentation = curSpace + cm.options.indentUnit
  7036. } else if (how == "subtract") {
  7037. indentation = curSpace - cm.options.indentUnit
  7038. } else if (typeof how == "number") {
  7039. indentation = curSpace + how
  7040. }
  7041. indentation = Math.max(0, indentation)
  7042. var indentString = "", pos = 0
  7043. if (cm.options.indentWithTabs)
  7044. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  7045. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  7046. if (indentString != curSpaceString) {
  7047. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  7048. line.stateAfter = null
  7049. return true
  7050. } else {
  7051. // Ensure that, if the cursor was in the whitespace at the start
  7052. // of the line, it is moved to the end of that space.
  7053. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7054. var range = doc.sel.ranges[i$1]
  7055. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7056. var pos$1 = Pos(n, curSpaceString.length)
  7057. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  7058. break
  7059. }
  7060. }
  7061. }
  7062. }
  7063. // This will be set to a {lineWise: bool, text: [string]} object, so
  7064. // that, when pasting, we know what kind of selections the copied
  7065. // text was made out of.
  7066. var lastCopied = null
  7067. function setLastCopied(newLastCopied) {
  7068. lastCopied = newLastCopied
  7069. }
  7070. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7071. var doc = cm.doc
  7072. cm.display.shift = false
  7073. if (!sel) { sel = doc.sel }
  7074. var paste = cm.state.pasteIncoming || origin == "paste"
  7075. var textLines = splitLinesAuto(inserted), multiPaste = null
  7076. // When pasing N lines into N selections, insert one line per selection
  7077. if (paste && sel.ranges.length > 1) {
  7078. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7079. if (sel.ranges.length % lastCopied.text.length == 0) {
  7080. multiPaste = []
  7081. for (var i = 0; i < lastCopied.text.length; i++)
  7082. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  7083. }
  7084. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7085. multiPaste = map(textLines, function (l) { return [l]; })
  7086. }
  7087. }
  7088. var updateInput
  7089. // Normal behavior is to insert the new text into every selection
  7090. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7091. var range = sel.ranges[i$1]
  7092. var from = range.from(), to = range.to()
  7093. if (range.empty()) {
  7094. if (deleted && deleted > 0) // Handle deletion
  7095. { from = Pos(from.line, from.ch - deleted) }
  7096. else if (cm.state.overwrite && !paste) // Handle overwrite
  7097. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  7098. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7099. { from = to = Pos(from.line, 0) }
  7100. }
  7101. updateInput = cm.curOp.updateInput
  7102. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7103. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  7104. makeChange(cm.doc, changeEvent)
  7105. signalLater(cm, "inputRead", cm, changeEvent)
  7106. }
  7107. if (inserted && !paste)
  7108. { triggerElectric(cm, inserted) }
  7109. ensureCursorVisible(cm)
  7110. cm.curOp.updateInput = updateInput
  7111. cm.curOp.typing = true
  7112. cm.state.pasteIncoming = cm.state.cutIncoming = false
  7113. }
  7114. function handlePaste(e, cm) {
  7115. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  7116. if (pasted) {
  7117. e.preventDefault()
  7118. if (!cm.isReadOnly() && !cm.options.disableInput)
  7119. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  7120. return true
  7121. }
  7122. }
  7123. function triggerElectric(cm, inserted) {
  7124. // When an 'electric' character is inserted, immediately trigger a reindent
  7125. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7126. var sel = cm.doc.sel
  7127. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7128. var range = sel.ranges[i]
  7129. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7130. var mode = cm.getModeAt(range.head)
  7131. var indented = false
  7132. if (mode.electricChars) {
  7133. for (var j = 0; j < mode.electricChars.length; j++)
  7134. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7135. indented = indentLine(cm, range.head.line, "smart")
  7136. break
  7137. } }
  7138. } else if (mode.electricInput) {
  7139. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7140. { indented = indentLine(cm, range.head.line, "smart") }
  7141. }
  7142. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  7143. }
  7144. }
  7145. function copyableRanges(cm) {
  7146. var text = [], ranges = []
  7147. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7148. var line = cm.doc.sel.ranges[i].head.line
  7149. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  7150. ranges.push(lineRange)
  7151. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  7152. }
  7153. return {text: text, ranges: ranges}
  7154. }
  7155. function disableBrowserMagic(field, spellcheck) {
  7156. field.setAttribute("autocorrect", "off")
  7157. field.setAttribute("autocapitalize", "off")
  7158. field.setAttribute("spellcheck", !!spellcheck)
  7159. }
  7160. function hiddenTextarea() {
  7161. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  7162. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  7163. // The textarea is kept positioned near the cursor to prevent the
  7164. // fact that it'll be scrolled into view on input from scrolling
  7165. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7166. // very slow. So make the area wide instead.
  7167. if (webkit) { te.style.width = "1000px" }
  7168. else { te.setAttribute("wrap", "off") }
  7169. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7170. if (ios) { te.style.border = "1px solid black" }
  7171. disableBrowserMagic(te)
  7172. return div
  7173. }
  7174. // The publicly visible API. Note that methodOp(f) means
  7175. // 'wrap f in an operation, performed on its `this` parameter'.
  7176. // This is not the complete set of editor methods. Most of the
  7177. // methods defined on the Doc type are also injected into
  7178. // CodeMirror.prototype, for backwards compatibility and
  7179. // convenience.
  7180. function addEditorMethods(CodeMirror) {
  7181. var optionHandlers = CodeMirror.optionHandlers
  7182. var helpers = CodeMirror.helpers = {}
  7183. CodeMirror.prototype = {
  7184. constructor: CodeMirror,
  7185. focus: function(){window.focus(); this.display.input.focus()},
  7186. setOption: function(option, value) {
  7187. var options = this.options, old = options[option]
  7188. if (options[option] == value && option != "mode") { return }
  7189. options[option] = value
  7190. if (optionHandlers.hasOwnProperty(option))
  7191. { operation(this, optionHandlers[option])(this, value, old) }
  7192. signal(this, "optionChange", this, option)
  7193. },
  7194. getOption: function(option) {return this.options[option]},
  7195. getDoc: function() {return this.doc},
  7196. addKeyMap: function(map, bottom) {
  7197. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  7198. },
  7199. removeKeyMap: function(map) {
  7200. var maps = this.state.keyMaps
  7201. for (var i = 0; i < maps.length; ++i)
  7202. { if (maps[i] == map || maps[i].name == map) {
  7203. maps.splice(i, 1)
  7204. return true
  7205. } }
  7206. },
  7207. addOverlay: methodOp(function(spec, options) {
  7208. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  7209. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7210. insertSorted(this.state.overlays,
  7211. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7212. priority: (options && options.priority) || 0},
  7213. function (overlay) { return overlay.priority; })
  7214. this.state.modeGen++
  7215. regChange(this)
  7216. }),
  7217. removeOverlay: methodOp(function(spec) {
  7218. var this$1 = this;
  7219. var overlays = this.state.overlays
  7220. for (var i = 0; i < overlays.length; ++i) {
  7221. var cur = overlays[i].modeSpec
  7222. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7223. overlays.splice(i, 1)
  7224. this$1.state.modeGen++
  7225. regChange(this$1)
  7226. return
  7227. }
  7228. }
  7229. }),
  7230. indentLine: methodOp(function(n, dir, aggressive) {
  7231. if (typeof dir != "string" && typeof dir != "number") {
  7232. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  7233. else { dir = dir ? "add" : "subtract" }
  7234. }
  7235. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  7236. }),
  7237. indentSelection: methodOp(function(how) {
  7238. var this$1 = this;
  7239. var ranges = this.doc.sel.ranges, end = -1
  7240. for (var i = 0; i < ranges.length; i++) {
  7241. var range = ranges[i]
  7242. if (!range.empty()) {
  7243. var from = range.from(), to = range.to()
  7244. var start = Math.max(end, from.line)
  7245. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  7246. for (var j = start; j < end; ++j)
  7247. { indentLine(this$1, j, how) }
  7248. var newRanges = this$1.doc.sel.ranges
  7249. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7250. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  7251. } else if (range.head.line > end) {
  7252. indentLine(this$1, range.head.line, how, true)
  7253. end = range.head.line
  7254. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  7255. }
  7256. }
  7257. }),
  7258. // Fetch the parser token for a given character. Useful for hacks
  7259. // that want to inspect the mode state (say, for completion).
  7260. getTokenAt: function(pos, precise) {
  7261. return takeToken(this, pos, precise)
  7262. },
  7263. getLineTokens: function(line, precise) {
  7264. return takeToken(this, Pos(line), precise, true)
  7265. },
  7266. getTokenTypeAt: function(pos) {
  7267. pos = clipPos(this.doc, pos)
  7268. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7269. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7270. var type
  7271. if (ch == 0) { type = styles[2] }
  7272. else { for (;;) {
  7273. var mid = (before + after) >> 1
  7274. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7275. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7276. else { type = styles[mid * 2 + 2]; break }
  7277. } }
  7278. var cut = type ? type.indexOf("overlay ") : -1
  7279. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7280. },
  7281. getModeAt: function(pos) {
  7282. var mode = this.doc.mode
  7283. if (!mode.innerMode) { return mode }
  7284. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7285. },
  7286. getHelper: function(pos, type) {
  7287. return this.getHelpers(pos, type)[0]
  7288. },
  7289. getHelpers: function(pos, type) {
  7290. var this$1 = this;
  7291. var found = []
  7292. if (!helpers.hasOwnProperty(type)) { return found }
  7293. var help = helpers[type], mode = this.getModeAt(pos)
  7294. if (typeof mode[type] == "string") {
  7295. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7296. } else if (mode[type]) {
  7297. for (var i = 0; i < mode[type].length; i++) {
  7298. var val = help[mode[type][i]]
  7299. if (val) { found.push(val) }
  7300. }
  7301. } else if (mode.helperType && help[mode.helperType]) {
  7302. found.push(help[mode.helperType])
  7303. } else if (help[mode.name]) {
  7304. found.push(help[mode.name])
  7305. }
  7306. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7307. var cur = help._global[i$1]
  7308. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7309. { found.push(cur.val) }
  7310. }
  7311. return found
  7312. },
  7313. getStateAfter: function(line, precise) {
  7314. var doc = this.doc
  7315. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7316. return getContextBefore(this, line + 1, precise).state
  7317. },
  7318. cursorCoords: function(start, mode) {
  7319. var pos, range = this.doc.sel.primary()
  7320. if (start == null) { pos = range.head }
  7321. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7322. else { pos = start ? range.from() : range.to() }
  7323. return cursorCoords(this, pos, mode || "page")
  7324. },
  7325. charCoords: function(pos, mode) {
  7326. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7327. },
  7328. coordsChar: function(coords, mode) {
  7329. coords = fromCoordSystem(this, coords, mode || "page")
  7330. return coordsChar(this, coords.left, coords.top)
  7331. },
  7332. lineAtHeight: function(height, mode) {
  7333. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7334. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7335. },
  7336. heightAtLine: function(line, mode, includeWidgets) {
  7337. var end = false, lineObj
  7338. if (typeof line == "number") {
  7339. var last = this.doc.first + this.doc.size - 1
  7340. if (line < this.doc.first) { line = this.doc.first }
  7341. else if (line > last) { line = last; end = true }
  7342. lineObj = getLine(this.doc, line)
  7343. } else {
  7344. lineObj = line
  7345. }
  7346. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7347. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7348. },
  7349. defaultTextHeight: function() { return textHeight(this.display) },
  7350. defaultCharWidth: function() { return charWidth(this.display) },
  7351. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7352. addWidget: function(pos, node, scroll, vert, horiz) {
  7353. var display = this.display
  7354. pos = cursorCoords(this, clipPos(this.doc, pos))
  7355. var top = pos.bottom, left = pos.left
  7356. node.style.position = "absolute"
  7357. node.setAttribute("cm-ignore-events", "true")
  7358. this.display.input.setUneditable(node)
  7359. display.sizer.appendChild(node)
  7360. if (vert == "over") {
  7361. top = pos.top
  7362. } else if (vert == "above" || vert == "near") {
  7363. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7364. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7365. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7366. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7367. { top = pos.top - node.offsetHeight }
  7368. else if (pos.bottom + node.offsetHeight <= vspace)
  7369. { top = pos.bottom }
  7370. if (left + node.offsetWidth > hspace)
  7371. { left = hspace - node.offsetWidth }
  7372. }
  7373. node.style.top = top + "px"
  7374. node.style.left = node.style.right = ""
  7375. if (horiz == "right") {
  7376. left = display.sizer.clientWidth - node.offsetWidth
  7377. node.style.right = "0px"
  7378. } else {
  7379. if (horiz == "left") { left = 0 }
  7380. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7381. node.style.left = left + "px"
  7382. }
  7383. if (scroll)
  7384. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) }
  7385. },
  7386. triggerOnKeyDown: methodOp(onKeyDown),
  7387. triggerOnKeyPress: methodOp(onKeyPress),
  7388. triggerOnKeyUp: onKeyUp,
  7389. triggerOnMouseDown: methodOp(onMouseDown),
  7390. execCommand: function(cmd) {
  7391. if (commands.hasOwnProperty(cmd))
  7392. { return commands[cmd].call(null, this) }
  7393. },
  7394. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7395. findPosH: function(from, amount, unit, visually) {
  7396. var this$1 = this;
  7397. var dir = 1
  7398. if (amount < 0) { dir = -1; amount = -amount }
  7399. var cur = clipPos(this.doc, from)
  7400. for (var i = 0; i < amount; ++i) {
  7401. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7402. if (cur.hitSide) { break }
  7403. }
  7404. return cur
  7405. },
  7406. moveH: methodOp(function(dir, unit) {
  7407. var this$1 = this;
  7408. this.extendSelectionsBy(function (range) {
  7409. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7410. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7411. else
  7412. { return dir < 0 ? range.from() : range.to() }
  7413. }, sel_move)
  7414. }),
  7415. deleteH: methodOp(function(dir, unit) {
  7416. var sel = this.doc.sel, doc = this.doc
  7417. if (sel.somethingSelected())
  7418. { doc.replaceSelection("", null, "+delete") }
  7419. else
  7420. { deleteNearSelection(this, function (range) {
  7421. var other = findPosH(doc, range.head, dir, unit, false)
  7422. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7423. }) }
  7424. }),
  7425. findPosV: function(from, amount, unit, goalColumn) {
  7426. var this$1 = this;
  7427. var dir = 1, x = goalColumn
  7428. if (amount < 0) { dir = -1; amount = -amount }
  7429. var cur = clipPos(this.doc, from)
  7430. for (var i = 0; i < amount; ++i) {
  7431. var coords = cursorCoords(this$1, cur, "div")
  7432. if (x == null) { x = coords.left }
  7433. else { coords.left = x }
  7434. cur = findPosV(this$1, coords, dir, unit)
  7435. if (cur.hitSide) { break }
  7436. }
  7437. return cur
  7438. },
  7439. moveV: methodOp(function(dir, unit) {
  7440. var this$1 = this;
  7441. var doc = this.doc, goals = []
  7442. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7443. doc.extendSelectionsBy(function (range) {
  7444. if (collapse)
  7445. { return dir < 0 ? range.from() : range.to() }
  7446. var headPos = cursorCoords(this$1, range.head, "div")
  7447. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7448. goals.push(headPos.left)
  7449. var pos = findPosV(this$1, headPos, dir, unit)
  7450. if (unit == "page" && range == doc.sel.primary())
  7451. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top) }
  7452. return pos
  7453. }, sel_move)
  7454. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7455. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7456. }),
  7457. // Find the word at the given position (as returned by coordsChar).
  7458. findWordAt: function(pos) {
  7459. var doc = this.doc, line = getLine(doc, pos.line).text
  7460. var start = pos.ch, end = pos.ch
  7461. if (line) {
  7462. var helper = this.getHelper(pos, "wordChars")
  7463. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end }
  7464. var startChar = line.charAt(start)
  7465. var check = isWordChar(startChar, helper)
  7466. ? function (ch) { return isWordChar(ch, helper); }
  7467. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7468. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7469. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7470. while (end < line.length && check(line.charAt(end))) { ++end }
  7471. }
  7472. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7473. },
  7474. toggleOverwrite: function(value) {
  7475. if (value != null && value == this.state.overwrite) { return }
  7476. if (this.state.overwrite = !this.state.overwrite)
  7477. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7478. else
  7479. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7480. signal(this, "overwriteToggle", this, this.state.overwrite)
  7481. },
  7482. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7483. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7484. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }),
  7485. getScrollInfo: function() {
  7486. var scroller = this.display.scroller
  7487. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7488. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7489. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7490. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7491. },
  7492. scrollIntoView: methodOp(function(range, margin) {
  7493. if (range == null) {
  7494. range = {from: this.doc.sel.primary().head, to: null}
  7495. if (margin == null) { margin = this.options.cursorScrollMargin }
  7496. } else if (typeof range == "number") {
  7497. range = {from: Pos(range, 0), to: null}
  7498. } else if (range.from == null) {
  7499. range = {from: range, to: null}
  7500. }
  7501. if (!range.to) { range.to = range.from }
  7502. range.margin = margin || 0
  7503. if (range.from.line != null) {
  7504. scrollToRange(this, range)
  7505. } else {
  7506. scrollToCoordsRange(this, range.from, range.to, range.margin)
  7507. }
  7508. }),
  7509. setSize: methodOp(function(width, height) {
  7510. var this$1 = this;
  7511. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7512. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7513. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7514. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7515. var lineNo = this.display.viewFrom
  7516. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7517. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7518. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7519. ++lineNo
  7520. })
  7521. this.curOp.forceUpdate = true
  7522. signal(this, "refresh", this)
  7523. }),
  7524. operation: function(f){return runInOp(this, f)},
  7525. startOperation: function(){return startOperation(this)},
  7526. endOperation: function(){return endOperation(this)},
  7527. refresh: methodOp(function() {
  7528. var oldHeight = this.display.cachedTextHeight
  7529. regChange(this)
  7530. this.curOp.forceUpdate = true
  7531. clearCaches(this)
  7532. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)
  7533. updateGutterSpace(this)
  7534. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7535. { estimateLineHeights(this) }
  7536. signal(this, "refresh", this)
  7537. }),
  7538. swapDoc: methodOp(function(doc) {
  7539. var old = this.doc
  7540. old.cm = null
  7541. attachDoc(this, doc)
  7542. clearCaches(this)
  7543. this.display.input.reset()
  7544. scrollToCoords(this, doc.scrollLeft, doc.scrollTop)
  7545. this.curOp.forceScroll = true
  7546. signalLater(this, "swapDoc", this, old)
  7547. return old
  7548. }),
  7549. getInputField: function(){return this.display.input.getField()},
  7550. getWrapperElement: function(){return this.display.wrapper},
  7551. getScrollerElement: function(){return this.display.scroller},
  7552. getGutterElement: function(){return this.display.gutters}
  7553. }
  7554. eventMixin(CodeMirror)
  7555. CodeMirror.registerHelper = function(type, name, value) {
  7556. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7557. helpers[type][name] = value
  7558. }
  7559. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7560. CodeMirror.registerHelper(type, name, value)
  7561. helpers[type]._global.push({pred: predicate, val: value})
  7562. }
  7563. }
  7564. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7565. // right), unit can be "char", "column" (like char, but doesn't
  7566. // cross line boundaries), "word" (across next word), or "group" (to
  7567. // the start of next group of word or non-word-non-whitespace
  7568. // chars). The visually param controls whether, in right-to-left
  7569. // text, direction 1 means to move towards the next index in the
  7570. // string, or towards the character to the right of the current
  7571. // position. The resulting position will have a hitSide=true
  7572. // property if it reached the end of the document.
  7573. function findPosH(doc, pos, dir, unit, visually) {
  7574. var oldPos = pos
  7575. var origDir = dir
  7576. var lineObj = getLine(doc, pos.line)
  7577. function findNextLine() {
  7578. var l = pos.line + dir
  7579. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7580. pos = new Pos(l, pos.ch, pos.sticky)
  7581. return lineObj = getLine(doc, l)
  7582. }
  7583. function moveOnce(boundToLine) {
  7584. var next
  7585. if (visually) {
  7586. next = moveVisually(doc.cm, lineObj, pos, dir)
  7587. } else {
  7588. next = moveLogically(lineObj, pos, dir)
  7589. }
  7590. if (next == null) {
  7591. if (!boundToLine && findNextLine())
  7592. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) }
  7593. else
  7594. { return false }
  7595. } else {
  7596. pos = next
  7597. }
  7598. return true
  7599. }
  7600. if (unit == "char") {
  7601. moveOnce()
  7602. } else if (unit == "column") {
  7603. moveOnce(true)
  7604. } else if (unit == "word" || unit == "group") {
  7605. var sawType = null, group = unit == "group"
  7606. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7607. for (var first = true;; first = false) {
  7608. if (dir < 0 && !moveOnce(!first)) { break }
  7609. var cur = lineObj.text.charAt(pos.ch) || "\n"
  7610. var type = isWordChar(cur, helper) ? "w"
  7611. : group && cur == "\n" ? "n"
  7612. : !group || /\s/.test(cur) ? null
  7613. : "p"
  7614. if (group && !first && !type) { type = "s" }
  7615. if (sawType && sawType != type) {
  7616. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"}
  7617. break
  7618. }
  7619. if (type) { sawType = type }
  7620. if (dir > 0 && !moveOnce(!first)) { break }
  7621. }
  7622. }
  7623. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  7624. if (equalCursorPos(oldPos, result)) { result.hitSide = true }
  7625. return result
  7626. }
  7627. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7628. // "page" or "line". The resulting position will have a hitSide=true
  7629. // property if it reached the end of the document.
  7630. function findPosV(cm, pos, dir, unit) {
  7631. var doc = cm.doc, x = pos.left, y
  7632. if (unit == "page") {
  7633. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7634. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7635. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7636. } else if (unit == "line") {
  7637. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7638. }
  7639. var target
  7640. for (;;) {
  7641. target = coordsChar(cm, x, y)
  7642. if (!target.outside) { break }
  7643. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7644. y += dir * 5
  7645. }
  7646. return target
  7647. }
  7648. // CONTENTEDITABLE INPUT STYLE
  7649. var ContentEditableInput = function(cm) {
  7650. this.cm = cm
  7651. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7652. this.polling = new Delayed()
  7653. this.composing = null
  7654. this.gracePeriod = false
  7655. this.readDOMTimeout = null
  7656. };
  7657. ContentEditableInput.prototype.init = function (display) {
  7658. var this$1 = this;
  7659. var input = this, cm = input.cm
  7660. var div = input.div = display.lineDiv
  7661. disableBrowserMagic(div, cm.options.spellcheck)
  7662. on(div, "paste", function (e) {
  7663. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7664. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7665. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) }
  7666. })
  7667. on(div, "compositionstart", function (e) {
  7668. this$1.composing = {data: e.data, done: false}
  7669. })
  7670. on(div, "compositionupdate", function (e) {
  7671. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7672. })
  7673. on(div, "compositionend", function (e) {
  7674. if (this$1.composing) {
  7675. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7676. this$1.composing.done = true
  7677. }
  7678. })
  7679. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7680. on(div, "input", function () {
  7681. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7682. })
  7683. function onCopyCut(e) {
  7684. if (signalDOMEvent(cm, e)) { return }
  7685. if (cm.somethingSelected()) {
  7686. setLastCopied({lineWise: false, text: cm.getSelections()})
  7687. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7688. } else if (!cm.options.lineWiseCopyCut) {
  7689. return
  7690. } else {
  7691. var ranges = copyableRanges(cm)
  7692. setLastCopied({lineWise: true, text: ranges.text})
  7693. if (e.type == "cut") {
  7694. cm.operation(function () {
  7695. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7696. cm.replaceSelection("", null, "cut")
  7697. })
  7698. }
  7699. }
  7700. if (e.clipboardData) {
  7701. e.clipboardData.clearData()
  7702. var content = lastCopied.text.join("\n")
  7703. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7704. e.clipboardData.setData("Text", content)
  7705. if (e.clipboardData.getData("Text") == content) {
  7706. e.preventDefault()
  7707. return
  7708. }
  7709. }
  7710. // Old-fashioned briefly-focus-a-textarea hack
  7711. var kludge = hiddenTextarea(), te = kludge.firstChild
  7712. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7713. te.value = lastCopied.text.join("\n")
  7714. var hadFocus = document.activeElement
  7715. selectInput(te)
  7716. setTimeout(function () {
  7717. cm.display.lineSpace.removeChild(kludge)
  7718. hadFocus.focus()
  7719. if (hadFocus == div) { input.showPrimarySelection() }
  7720. }, 50)
  7721. }
  7722. on(div, "copy", onCopyCut)
  7723. on(div, "cut", onCopyCut)
  7724. };
  7725. ContentEditableInput.prototype.prepareSelection = function () {
  7726. var result = prepareSelection(this.cm, false)
  7727. result.focus = this.cm.state.focused
  7728. return result
  7729. };
  7730. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7731. if (!info || !this.cm.display.view.length) { return }
  7732. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7733. this.showMultipleSelections(info)
  7734. };
  7735. ContentEditableInput.prototype.showPrimarySelection = function () {
  7736. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()
  7737. var from = prim.from(), to = prim.to()
  7738. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7739. sel.removeAllRanges()
  7740. return
  7741. }
  7742. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7743. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  7744. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7745. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7746. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7747. { return }
  7748. var view = cm.display.view
  7749. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7750. {node: view[0].measure.map[2], offset: 0}
  7751. var end = to.line < cm.display.viewTo && posToDOM(cm, to)
  7752. if (!end) {
  7753. var measure = view[view.length - 1].measure
  7754. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7755. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7756. }
  7757. if (!start || !end) {
  7758. sel.removeAllRanges()
  7759. return
  7760. }
  7761. var old = sel.rangeCount && sel.getRangeAt(0), rng
  7762. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7763. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7764. if (rng) {
  7765. if (!gecko && cm.state.focused) {
  7766. sel.collapse(start.node, start.offset)
  7767. if (!rng.collapsed) {
  7768. sel.removeAllRanges()
  7769. sel.addRange(rng)
  7770. }
  7771. } else {
  7772. sel.removeAllRanges()
  7773. sel.addRange(rng)
  7774. }
  7775. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7776. else if (gecko) { this.startGracePeriod() }
  7777. }
  7778. this.rememberSelection()
  7779. };
  7780. ContentEditableInput.prototype.startGracePeriod = function () {
  7781. var this$1 = this;
  7782. clearTimeout(this.gracePeriod)
  7783. this.gracePeriod = setTimeout(function () {
  7784. this$1.gracePeriod = false
  7785. if (this$1.selectionChanged())
  7786. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7787. }, 20)
  7788. };
  7789. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7790. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7791. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7792. };
  7793. ContentEditableInput.prototype.rememberSelection = function () {
  7794. var sel = window.getSelection()
  7795. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7796. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7797. };
  7798. ContentEditableInput.prototype.selectionInEditor = function () {
  7799. var sel = window.getSelection()
  7800. if (!sel.rangeCount) { return false }
  7801. var node = sel.getRangeAt(0).commonAncestorContainer
  7802. return contains(this.div, node)
  7803. };
  7804. ContentEditableInput.prototype.focus = function () {
  7805. if (this.cm.options.readOnly != "nocursor") {
  7806. if (!this.selectionInEditor())
  7807. { this.showSelection(this.prepareSelection(), true) }
  7808. this.div.focus()
  7809. }
  7810. };
  7811. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7812. ContentEditableInput.prototype.getField = function () { return this.div };
  7813. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7814. ContentEditableInput.prototype.receivedFocus = function () {
  7815. var input = this
  7816. if (this.selectionInEditor())
  7817. { this.pollSelection() }
  7818. else
  7819. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7820. function poll() {
  7821. if (input.cm.state.focused) {
  7822. input.pollSelection()
  7823. input.polling.set(input.cm.options.pollInterval, poll)
  7824. }
  7825. }
  7826. this.polling.set(this.cm.options.pollInterval, poll)
  7827. };
  7828. ContentEditableInput.prototype.selectionChanged = function () {
  7829. var sel = window.getSelection()
  7830. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7831. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7832. };
  7833. ContentEditableInput.prototype.pollSelection = function () {
  7834. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  7835. var sel = window.getSelection(), cm = this.cm
  7836. // On Android Chrome (version 56, at least), backspacing into an
  7837. // uneditable block element will put the cursor in that element,
  7838. // and then, because it's not editable, hide the virtual keyboard.
  7839. // Because Android doesn't allow us to actually detect backspace
  7840. // presses in a sane way, this code checks for when that happens
  7841. // and simulates a backspace press in this case.
  7842. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  7843. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs})
  7844. this.blur()
  7845. this.focus()
  7846. return
  7847. }
  7848. if (this.composing) { return }
  7849. this.rememberSelection()
  7850. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7851. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  7852. if (anchor && head) { runInOp(cm, function () {
  7853. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  7854. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  7855. }) }
  7856. };
  7857. ContentEditableInput.prototype.pollContent = function () {
  7858. if (this.readDOMTimeout != null) {
  7859. clearTimeout(this.readDOMTimeout)
  7860. this.readDOMTimeout = null
  7861. }
  7862. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  7863. var from = sel.from(), to = sel.to()
  7864. if (from.ch == 0 && from.line > cm.firstLine())
  7865. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  7866. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  7867. { to = Pos(to.line + 1, 0) }
  7868. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  7869. var fromIndex, fromLine, fromNode
  7870. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  7871. fromLine = lineNo(display.view[0].line)
  7872. fromNode = display.view[0].node
  7873. } else {
  7874. fromLine = lineNo(display.view[fromIndex].line)
  7875. fromNode = display.view[fromIndex - 1].node.nextSibling
  7876. }
  7877. var toIndex = findViewIndex(cm, to.line)
  7878. var toLine, toNode
  7879. if (toIndex == display.view.length - 1) {
  7880. toLine = display.viewTo - 1
  7881. toNode = display.lineDiv.lastChild
  7882. } else {
  7883. toLine = lineNo(display.view[toIndex + 1].line) - 1
  7884. toNode = display.view[toIndex + 1].node.previousSibling
  7885. }
  7886. if (!fromNode) { return false }
  7887. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  7888. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  7889. while (newText.length > 1 && oldText.length > 1) {
  7890. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  7891. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  7892. else { break }
  7893. }
  7894. var cutFront = 0, cutEnd = 0
  7895. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  7896. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  7897. { ++cutFront }
  7898. var newBot = lst(newText), oldBot = lst(oldText)
  7899. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  7900. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  7901. while (cutEnd < maxCutEnd &&
  7902. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  7903. { ++cutEnd }
  7904. // Try to move start of change to start of selection if ambiguous
  7905. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  7906. while (cutFront && cutFront > from.ch &&
  7907. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  7908. cutFront--
  7909. cutEnd++
  7910. }
  7911. }
  7912. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  7913. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  7914. var chFrom = Pos(fromLine, cutFront)
  7915. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  7916. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  7917. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  7918. return true
  7919. }
  7920. };
  7921. ContentEditableInput.prototype.ensurePolled = function () {
  7922. this.forceCompositionEnd()
  7923. };
  7924. ContentEditableInput.prototype.reset = function () {
  7925. this.forceCompositionEnd()
  7926. };
  7927. ContentEditableInput.prototype.forceCompositionEnd = function () {
  7928. if (!this.composing) { return }
  7929. clearTimeout(this.readDOMTimeout)
  7930. this.composing = null
  7931. this.updateFromDOM()
  7932. this.div.blur()
  7933. this.div.focus()
  7934. };
  7935. ContentEditableInput.prototype.readFromDOMSoon = function () {
  7936. var this$1 = this;
  7937. if (this.readDOMTimeout != null) { return }
  7938. this.readDOMTimeout = setTimeout(function () {
  7939. this$1.readDOMTimeout = null
  7940. if (this$1.composing) {
  7941. if (this$1.composing.done) { this$1.composing = null }
  7942. else { return }
  7943. }
  7944. this$1.updateFromDOM()
  7945. }, 80)
  7946. };
  7947. ContentEditableInput.prototype.updateFromDOM = function () {
  7948. var this$1 = this;
  7949. if (this.cm.isReadOnly() || !this.pollContent())
  7950. { runInOp(this.cm, function () { return regChange(this$1.cm); }) }
  7951. };
  7952. ContentEditableInput.prototype.setUneditable = function (node) {
  7953. node.contentEditable = "false"
  7954. };
  7955. ContentEditableInput.prototype.onKeyPress = function (e) {
  7956. if (e.charCode == 0) { return }
  7957. e.preventDefault()
  7958. if (!this.cm.isReadOnly())
  7959. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  7960. };
  7961. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  7962. this.div.contentEditable = String(val != "nocursor")
  7963. };
  7964. ContentEditableInput.prototype.onContextMenu = function () {};
  7965. ContentEditableInput.prototype.resetPosition = function () {};
  7966. ContentEditableInput.prototype.needsContentAttribute = true
  7967. function posToDOM(cm, pos) {
  7968. var view = findViewForLine(cm, pos.line)
  7969. if (!view || view.hidden) { return null }
  7970. var line = getLine(cm.doc, pos.line)
  7971. var info = mapFromLineView(view, line, pos.line)
  7972. var order = getOrder(line, cm.doc.direction), side = "left"
  7973. if (order) {
  7974. var partPos = getBidiPartAt(order, pos.ch)
  7975. side = partPos % 2 ? "right" : "left"
  7976. }
  7977. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  7978. result.offset = result.collapse == "right" ? result.end : result.start
  7979. return result
  7980. }
  7981. function isInGutter(node) {
  7982. for (var scan = node; scan; scan = scan.parentNode)
  7983. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  7984. return false
  7985. }
  7986. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  7987. function domTextBetween(cm, from, to, fromLine, toLine) {
  7988. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  7989. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  7990. function close() {
  7991. if (closing) {
  7992. text += lineSep
  7993. closing = false
  7994. }
  7995. }
  7996. function addText(str) {
  7997. if (str) {
  7998. close()
  7999. text += str
  8000. }
  8001. }
  8002. function walk(node) {
  8003. if (node.nodeType == 1) {
  8004. var cmText = node.getAttribute("cm-text")
  8005. if (cmText != null) {
  8006. addText(cmText || node.textContent.replace(/\u200b/g, ""))
  8007. return
  8008. }
  8009. var markerID = node.getAttribute("cm-marker"), range
  8010. if (markerID) {
  8011. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  8012. if (found.length && (range = found[0].find(0)))
  8013. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) }
  8014. return
  8015. }
  8016. if (node.getAttribute("contenteditable") == "false") { return }
  8017. var isBlock = /^(pre|div|p)$/i.test(node.nodeName)
  8018. if (isBlock) { close() }
  8019. for (var i = 0; i < node.childNodes.length; i++)
  8020. { walk(node.childNodes[i]) }
  8021. if (isBlock) { closing = true }
  8022. } else if (node.nodeType == 3) {
  8023. addText(node.nodeValue)
  8024. }
  8025. }
  8026. for (;;) {
  8027. walk(from)
  8028. if (from == to) { break }
  8029. from = from.nextSibling
  8030. }
  8031. return text
  8032. }
  8033. function domToPos(cm, node, offset) {
  8034. var lineNode
  8035. if (node == cm.display.lineDiv) {
  8036. lineNode = cm.display.lineDiv.childNodes[offset]
  8037. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8038. node = null; offset = 0
  8039. } else {
  8040. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8041. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8042. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8043. }
  8044. }
  8045. for (var i = 0; i < cm.display.view.length; i++) {
  8046. var lineView = cm.display.view[i]
  8047. if (lineView.node == lineNode)
  8048. { return locateNodeInLineView(lineView, node, offset) }
  8049. }
  8050. }
  8051. function locateNodeInLineView(lineView, node, offset) {
  8052. var wrapper = lineView.text.firstChild, bad = false
  8053. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8054. if (node == wrapper) {
  8055. bad = true
  8056. node = wrapper.childNodes[offset]
  8057. offset = 0
  8058. if (!node) {
  8059. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  8060. return badPos(Pos(lineNo(line), line.text.length), bad)
  8061. }
  8062. }
  8063. var textNode = node.nodeType == 3 ? node : null, topNode = node
  8064. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8065. textNode = node.firstChild
  8066. if (offset) { offset = textNode.nodeValue.length }
  8067. }
  8068. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  8069. var measure = lineView.measure, maps = measure.maps
  8070. function find(textNode, topNode, offset) {
  8071. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8072. var map = i < 0 ? measure.map : maps[i]
  8073. for (var j = 0; j < map.length; j += 3) {
  8074. var curNode = map[j + 2]
  8075. if (curNode == textNode || curNode == topNode) {
  8076. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  8077. var ch = map[j] + offset
  8078. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  8079. return Pos(line, ch)
  8080. }
  8081. }
  8082. }
  8083. }
  8084. var found = find(textNode, topNode, offset)
  8085. if (found) { return badPos(found, bad) }
  8086. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8087. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8088. found = find(after, after.firstChild, 0)
  8089. if (found)
  8090. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8091. else
  8092. { dist += after.textContent.length }
  8093. }
  8094. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8095. found = find(before, before.firstChild, -1)
  8096. if (found)
  8097. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8098. else
  8099. { dist$1 += before.textContent.length }
  8100. }
  8101. }
  8102. // TEXTAREA INPUT STYLE
  8103. var TextareaInput = function(cm) {
  8104. this.cm = cm
  8105. // See input.poll and input.reset
  8106. this.prevInput = ""
  8107. // Flag that indicates whether we expect input to appear real soon
  8108. // now (after some event like 'keypress' or 'input') and are
  8109. // polling intensively.
  8110. this.pollingFast = false
  8111. // Self-resetting timeout for the poller
  8112. this.polling = new Delayed()
  8113. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8114. this.hasSelection = false
  8115. this.composing = null
  8116. };
  8117. TextareaInput.prototype.init = function (display) {
  8118. var this$1 = this;
  8119. var input = this, cm = this.cm
  8120. // Wraps and hides input textarea
  8121. var div = this.wrapper = hiddenTextarea()
  8122. // The semihidden textarea that is focused when the editor is
  8123. // focused, and receives input.
  8124. var te = this.textarea = div.firstChild
  8125. display.wrapper.insertBefore(div, display.wrapper.firstChild)
  8126. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8127. if (ios) { te.style.width = "0px" }
  8128. on(te, "input", function () {
  8129. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  8130. input.poll()
  8131. })
  8132. on(te, "paste", function (e) {
  8133. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8134. cm.state.pasteIncoming = true
  8135. input.fastPoll()
  8136. })
  8137. function prepareCopyCut(e) {
  8138. if (signalDOMEvent(cm, e)) { return }
  8139. if (cm.somethingSelected()) {
  8140. setLastCopied({lineWise: false, text: cm.getSelections()})
  8141. } else if (!cm.options.lineWiseCopyCut) {
  8142. return
  8143. } else {
  8144. var ranges = copyableRanges(cm)
  8145. setLastCopied({lineWise: true, text: ranges.text})
  8146. if (e.type == "cut") {
  8147. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  8148. } else {
  8149. input.prevInput = ""
  8150. te.value = ranges.text.join("\n")
  8151. selectInput(te)
  8152. }
  8153. }
  8154. if (e.type == "cut") { cm.state.cutIncoming = true }
  8155. }
  8156. on(te, "cut", prepareCopyCut)
  8157. on(te, "copy", prepareCopyCut)
  8158. on(display.scroller, "paste", function (e) {
  8159. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8160. cm.state.pasteIncoming = true
  8161. input.focus()
  8162. })
  8163. // Prevent normal selection in the editor (we handle our own)
  8164. on(display.lineSpace, "selectstart", function (e) {
  8165. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  8166. })
  8167. on(te, "compositionstart", function () {
  8168. var start = cm.getCursor("from")
  8169. if (input.composing) { input.composing.range.clear() }
  8170. input.composing = {
  8171. start: start,
  8172. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8173. }
  8174. })
  8175. on(te, "compositionend", function () {
  8176. if (input.composing) {
  8177. input.poll()
  8178. input.composing.range.clear()
  8179. input.composing = null
  8180. }
  8181. })
  8182. };
  8183. TextareaInput.prototype.prepareSelection = function () {
  8184. // Redraw the selection and/or cursor
  8185. var cm = this.cm, display = cm.display, doc = cm.doc
  8186. var result = prepareSelection(cm)
  8187. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8188. if (cm.options.moveInputWithCursor) {
  8189. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  8190. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  8191. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8192. headPos.top + lineOff.top - wrapOff.top))
  8193. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8194. headPos.left + lineOff.left - wrapOff.left))
  8195. }
  8196. return result
  8197. };
  8198. TextareaInput.prototype.showSelection = function (drawn) {
  8199. var cm = this.cm, display = cm.display
  8200. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  8201. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  8202. if (drawn.teTop != null) {
  8203. this.wrapper.style.top = drawn.teTop + "px"
  8204. this.wrapper.style.left = drawn.teLeft + "px"
  8205. }
  8206. };
  8207. // Reset the input to correspond to the selection (or to be empty,
  8208. // when not typing and nothing is selected)
  8209. TextareaInput.prototype.reset = function (typing) {
  8210. if (this.contextMenuPending || this.composing) { return }
  8211. var cm = this.cm
  8212. if (cm.somethingSelected()) {
  8213. this.prevInput = ""
  8214. var content = cm.getSelection()
  8215. this.textarea.value = content
  8216. if (cm.state.focused) { selectInput(this.textarea) }
  8217. if (ie && ie_version >= 9) { this.hasSelection = content }
  8218. } else if (!typing) {
  8219. this.prevInput = this.textarea.value = ""
  8220. if (ie && ie_version >= 9) { this.hasSelection = null }
  8221. }
  8222. };
  8223. TextareaInput.prototype.getField = function () { return this.textarea };
  8224. TextareaInput.prototype.supportsTouch = function () { return false };
  8225. TextareaInput.prototype.focus = function () {
  8226. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8227. try { this.textarea.focus() }
  8228. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8229. }
  8230. };
  8231. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  8232. TextareaInput.prototype.resetPosition = function () {
  8233. this.wrapper.style.top = this.wrapper.style.left = 0
  8234. };
  8235. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  8236. // Poll for input changes, using the normal rate of polling. This
  8237. // runs as long as the editor is focused.
  8238. TextareaInput.prototype.slowPoll = function () {
  8239. var this$1 = this;
  8240. if (this.pollingFast) { return }
  8241. this.polling.set(this.cm.options.pollInterval, function () {
  8242. this$1.poll()
  8243. if (this$1.cm.state.focused) { this$1.slowPoll() }
  8244. })
  8245. };
  8246. // When an event has just come in that is likely to add or change
  8247. // something in the input textarea, we poll faster, to ensure that
  8248. // the change appears on the screen quickly.
  8249. TextareaInput.prototype.fastPoll = function () {
  8250. var missed = false, input = this
  8251. input.pollingFast = true
  8252. function p() {
  8253. var changed = input.poll()
  8254. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  8255. else {input.pollingFast = false; input.slowPoll()}
  8256. }
  8257. input.polling.set(20, p)
  8258. };
  8259. // Read input from the textarea, and update the document to match.
  8260. // When something is selected, it is present in the textarea, and
  8261. // selected (unless it is huge, in which case a placeholder is
  8262. // used). When nothing is selected, the cursor sits after previously
  8263. // seen text (can be empty), which is stored in prevInput (we must
  8264. // not reset the textarea when typing, because that breaks IME).
  8265. TextareaInput.prototype.poll = function () {
  8266. var this$1 = this;
  8267. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  8268. // Since this is called a *lot*, try to bail out as cheaply as
  8269. // possible when it is clear that nothing happened. hasSelection
  8270. // will be the case when there is a lot of text in the textarea,
  8271. // in which case reading its value would be expensive.
  8272. if (this.contextMenuPending || !cm.state.focused ||
  8273. (hasSelection(input) && !prevInput && !this.composing) ||
  8274. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8275. { return false }
  8276. var text = input.value
  8277. // If nothing changed, bail.
  8278. if (text == prevInput && !cm.somethingSelected()) { return false }
  8279. // Work around nonsensical selection resetting in IE9/10, and
  8280. // inexplicable appearance of private area unicode characters on
  8281. // some key combos in Mac (#2689).
  8282. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8283. mac && /[\uf700-\uf7ff]/.test(text)) {
  8284. cm.display.input.reset()
  8285. return false
  8286. }
  8287. if (cm.doc.sel == cm.display.selForContextMenu) {
  8288. var first = text.charCodeAt(0)
  8289. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  8290. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8291. }
  8292. // Find the part of the input that is actually new
  8293. var same = 0, l = Math.min(prevInput.length, text.length)
  8294. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8295. runInOp(cm, function () {
  8296. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8297. null, this$1.composing ? "*compose" : null)
  8298. // Don't leave long text in the textarea, since it makes further polling slow
  8299. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8300. else { this$1.prevInput = text }
  8301. if (this$1.composing) {
  8302. this$1.composing.range.clear()
  8303. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8304. {className: "CodeMirror-composing"})
  8305. }
  8306. })
  8307. return true
  8308. };
  8309. TextareaInput.prototype.ensurePolled = function () {
  8310. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8311. };
  8312. TextareaInput.prototype.onKeyPress = function () {
  8313. if (ie && ie_version >= 9) { this.hasSelection = null }
  8314. this.fastPoll()
  8315. };
  8316. TextareaInput.prototype.onContextMenu = function (e) {
  8317. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8318. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8319. if (!pos || presto) { return } // Opera is difficult.
  8320. // Reset the current text selection only if the click is done outside of the selection
  8321. // and 'resetSelectionOnContextMenu' option is true.
  8322. var reset = cm.options.resetSelectionOnContextMenu
  8323. if (reset && cm.doc.sel.contains(pos) == -1)
  8324. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8325. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8326. input.wrapper.style.cssText = "position: absolute"
  8327. var wrapperBox = input.wrapper.getBoundingClientRect()
  8328. 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);"
  8329. var oldScrollY
  8330. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8331. display.input.focus()
  8332. if (webkit) { window.scrollTo(null, oldScrollY) }
  8333. display.input.reset()
  8334. // Adds "Select all" to context menu in FF
  8335. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8336. input.contextMenuPending = true
  8337. display.selForContextMenu = cm.doc.sel
  8338. clearTimeout(display.detectingSelectAll)
  8339. // Select-all will be greyed out if there's nothing to select, so
  8340. // this adds a zero-width space so that we can later check whether
  8341. // it got selected.
  8342. function prepareSelectAllHack() {
  8343. if (te.selectionStart != null) {
  8344. var selected = cm.somethingSelected()
  8345. var extval = "\u200b" + (selected ? te.value : "")
  8346. te.value = "\u21da" // Used to catch context-menu undo
  8347. te.value = extval
  8348. input.prevInput = selected ? "" : "\u200b"
  8349. te.selectionStart = 1; te.selectionEnd = extval.length
  8350. // Re-set this, in case some other handler touched the
  8351. // selection in the meantime.
  8352. display.selForContextMenu = cm.doc.sel
  8353. }
  8354. }
  8355. function rehide() {
  8356. input.contextMenuPending = false
  8357. input.wrapper.style.cssText = oldWrapperCSS
  8358. te.style.cssText = oldCSS
  8359. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8360. // Try to detect the user choosing select-all
  8361. if (te.selectionStart != null) {
  8362. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8363. var i = 0, poll = function () {
  8364. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8365. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8366. operation(cm, selectAll)(cm)
  8367. } else if (i++ < 10) {
  8368. display.detectingSelectAll = setTimeout(poll, 500)
  8369. } else {
  8370. display.selForContextMenu = null
  8371. display.input.reset()
  8372. }
  8373. }
  8374. display.detectingSelectAll = setTimeout(poll, 200)
  8375. }
  8376. }
  8377. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8378. if (captureRightClick) {
  8379. e_stop(e)
  8380. var mouseup = function () {
  8381. off(window, "mouseup", mouseup)
  8382. setTimeout(rehide, 20)
  8383. }
  8384. on(window, "mouseup", mouseup)
  8385. } else {
  8386. setTimeout(rehide, 50)
  8387. }
  8388. };
  8389. TextareaInput.prototype.readOnlyChanged = function (val) {
  8390. if (!val) { this.reset() }
  8391. this.textarea.disabled = val == "nocursor"
  8392. };
  8393. TextareaInput.prototype.setUneditable = function () {};
  8394. TextareaInput.prototype.needsContentAttribute = false
  8395. function fromTextArea(textarea, options) {
  8396. options = options ? copyObj(options) : {}
  8397. options.value = textarea.value
  8398. if (!options.tabindex && textarea.tabIndex)
  8399. { options.tabindex = textarea.tabIndex }
  8400. if (!options.placeholder && textarea.placeholder)
  8401. { options.placeholder = textarea.placeholder }
  8402. // Set autofocus to true if this textarea is focused, or if it has
  8403. // autofocus and no other element is focused.
  8404. if (options.autofocus == null) {
  8405. var hasFocus = activeElt()
  8406. options.autofocus = hasFocus == textarea ||
  8407. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8408. }
  8409. function save() {textarea.value = cm.getValue()}
  8410. var realSubmit
  8411. if (textarea.form) {
  8412. on(textarea.form, "submit", save)
  8413. // Deplorable hack to make the submit method do the right thing.
  8414. if (!options.leaveSubmitMethodAlone) {
  8415. var form = textarea.form
  8416. realSubmit = form.submit
  8417. try {
  8418. var wrappedSubmit = form.submit = function () {
  8419. save()
  8420. form.submit = realSubmit
  8421. form.submit()
  8422. form.submit = wrappedSubmit
  8423. }
  8424. } catch(e) {}
  8425. }
  8426. }
  8427. options.finishInit = function (cm) {
  8428. cm.save = save
  8429. cm.getTextArea = function () { return textarea; }
  8430. cm.toTextArea = function () {
  8431. cm.toTextArea = isNaN // Prevent this from being ran twice
  8432. save()
  8433. textarea.parentNode.removeChild(cm.getWrapperElement())
  8434. textarea.style.display = ""
  8435. if (textarea.form) {
  8436. off(textarea.form, "submit", save)
  8437. if (typeof textarea.form.submit == "function")
  8438. { textarea.form.submit = realSubmit }
  8439. }
  8440. }
  8441. }
  8442. textarea.style.display = "none"
  8443. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8444. options)
  8445. return cm
  8446. }
  8447. function addLegacyProps(CodeMirror) {
  8448. CodeMirror.off = off
  8449. CodeMirror.on = on
  8450. CodeMirror.wheelEventPixels = wheelEventPixels
  8451. CodeMirror.Doc = Doc
  8452. CodeMirror.splitLines = splitLinesAuto
  8453. CodeMirror.countColumn = countColumn
  8454. CodeMirror.findColumn = findColumn
  8455. CodeMirror.isWordChar = isWordCharBasic
  8456. CodeMirror.Pass = Pass
  8457. CodeMirror.signal = signal
  8458. CodeMirror.Line = Line
  8459. CodeMirror.changeEnd = changeEnd
  8460. CodeMirror.scrollbarModel = scrollbarModel
  8461. CodeMirror.Pos = Pos
  8462. CodeMirror.cmpPos = cmp
  8463. CodeMirror.modes = modes
  8464. CodeMirror.mimeModes = mimeModes
  8465. CodeMirror.resolveMode = resolveMode
  8466. CodeMirror.getMode = getMode
  8467. CodeMirror.modeExtensions = modeExtensions
  8468. CodeMirror.extendMode = extendMode
  8469. CodeMirror.copyState = copyState
  8470. CodeMirror.startState = startState
  8471. CodeMirror.innerMode = innerMode
  8472. CodeMirror.commands = commands
  8473. CodeMirror.keyMap = keyMap
  8474. CodeMirror.keyName = keyName
  8475. CodeMirror.isModifierKey = isModifierKey
  8476. CodeMirror.lookupKey = lookupKey
  8477. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8478. CodeMirror.StringStream = StringStream
  8479. CodeMirror.SharedTextMarker = SharedTextMarker
  8480. CodeMirror.TextMarker = TextMarker
  8481. CodeMirror.LineWidget = LineWidget
  8482. CodeMirror.e_preventDefault = e_preventDefault
  8483. CodeMirror.e_stopPropagation = e_stopPropagation
  8484. CodeMirror.e_stop = e_stop
  8485. CodeMirror.addClass = addClass
  8486. CodeMirror.contains = contains
  8487. CodeMirror.rmClass = rmClass
  8488. CodeMirror.keyNames = keyNames
  8489. }
  8490. // EDITOR CONSTRUCTOR
  8491. defineOptions(CodeMirror)
  8492. addEditorMethods(CodeMirror)
  8493. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8494. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8495. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8496. { CodeMirror.prototype[prop] = (function(method) {
  8497. return function() {return method.apply(this.doc, arguments)}
  8498. })(Doc.prototype[prop]) } }
  8499. eventMixin(Doc)
  8500. // INPUT HANDLING
  8501. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8502. // MODE DEFINITION AND QUERYING
  8503. // Extra arguments are stored as the mode's dependencies, which is
  8504. // used by (legacy) mechanisms like loadmode.js to automatically
  8505. // load a mode. (Preferred mechanism is the require/define calls.)
  8506. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8507. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8508. defineMode.apply(this, arguments)
  8509. }
  8510. CodeMirror.defineMIME = defineMIME
  8511. // Minimal default mode.
  8512. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8513. CodeMirror.defineMIME("text/plain", "null")
  8514. // EXTENSIONS
  8515. CodeMirror.defineExtension = function (name, func) {
  8516. CodeMirror.prototype[name] = func
  8517. }
  8518. CodeMirror.defineDocExtension = function (name, func) {
  8519. Doc.prototype[name] = func
  8520. }
  8521. CodeMirror.fromTextArea = fromTextArea
  8522. addLegacyProps(CodeMirror)
  8523. CodeMirror.version = "5.29.0"
  8524. return CodeMirror;
  8525. })));