codemirror.js 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645
  1. // CodeMirror v5.0, 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(mod) {
  9. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10. module.exports = mod();
  11. else if (typeof define == "function" && define.amd) // AMD
  12. return define([], mod);
  13. else // Plain browser env
  14. this.CodeMirror = mod();
  15. })(function() {
  16. "use strict";
  17. // BROWSER SNIFFING
  18. // Kludges for bugs and behavior differences that can't be feature
  19. // detected are enabled based on userAgent etc sniffing.
  20. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  21. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  22. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  23. var ie = ie_upto10 || ie_11up;
  24. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  25. var webkit = /WebKit\//.test(navigator.userAgent);
  26. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  27. var chrome = /Chrome\//.test(navigator.userAgent);
  28. var presto = /Opera\//.test(navigator.userAgent);
  29. var safari = /Apple Computer/.test(navigator.vendor);
  30. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  31. var phantom = /PhantomJS/.test(navigator.userAgent);
  32. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  33. // This is woefully incomplete. Suggestions for alternative methods welcome.
  34. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  35. var mac = ios || /Mac/.test(navigator.platform);
  36. var windows = /win/i.test(navigator.platform);
  37. var presto_version = presto && navigator.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. // Optimize some code when these features are not used.
  44. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  45. // EDITOR CONSTRUCTOR
  46. // A CodeMirror instance represents an editor. This is the object
  47. // that user code is usually dealing with.
  48. function CodeMirror(place, options) {
  49. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  50. this.options = options = options ? copyObj(options) : {};
  51. // Determine effective options based on given values and defaults.
  52. copyObj(defaults, options, false);
  53. setGuttersForLineNumbers(options);
  54. var doc = options.value;
  55. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  56. this.doc = doc;
  57. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  58. var display = this.display = new Display(place, doc, input);
  59. display.wrapper.CodeMirror = this;
  60. updateGutters(this);
  61. themeChanged(this);
  62. if (options.lineWrapping)
  63. this.display.wrapper.className += " CodeMirror-wrap";
  64. if (options.autofocus && !mobile) display.input.focus();
  65. initScrollbars(this);
  66. this.state = {
  67. keyMaps: [], // stores maps added by addKeyMap
  68. overlays: [], // highlighting overlays, as added by addOverlay
  69. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  70. overwrite: false, focused: false,
  71. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  72. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  73. draggingText: false,
  74. highlight: new Delayed(), // stores highlight worker timeout
  75. keySeq: null // Unfinished key sequence
  76. };
  77. var cm = this;
  78. // Override magic textarea content restore that IE sometimes does
  79. // on our hidden textarea on reload
  80. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  81. registerEventHandlers(this);
  82. ensureGlobalHandlers();
  83. startOperation(this);
  84. this.curOp.forceUpdate = true;
  85. attachDoc(this, doc);
  86. if ((options.autofocus && !mobile) || cm.hasFocus())
  87. setTimeout(bind(onFocus, this), 20);
  88. else
  89. onBlur(this);
  90. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  91. optionHandlers[opt](this, options[opt], Init);
  92. maybeUpdateLineNumberWidth(this);
  93. if (options.finishInit) options.finishInit(this);
  94. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  95. endOperation(this);
  96. // Suppress optimizelegibility in Webkit, since it breaks text
  97. // measuring on line wrapping boundaries.
  98. if (webkit && options.lineWrapping &&
  99. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  100. display.lineDiv.style.textRendering = "auto";
  101. }
  102. // DISPLAY CONSTRUCTOR
  103. // The display handles the DOM integration, both for input reading
  104. // and content drawing. It holds references to DOM nodes and
  105. // display-related state.
  106. function Display(place, doc, input) {
  107. var d = this;
  108. this.input = input;
  109. // Covers bottom-right square when both scrollbars are present.
  110. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  111. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  112. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  113. // and h scrollbar is present.
  114. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  115. d.gutterFiller.setAttribute("cm-not-content", "true");
  116. // Will contain the actual code, positioned to cover the viewport.
  117. d.lineDiv = elt("div", null, "CodeMirror-code");
  118. // Elements are added to these to represent selection and cursors.
  119. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  120. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  121. // A visibility: hidden element used to find the size of things.
  122. d.measure = elt("div", null, "CodeMirror-measure");
  123. // When lines outside of the viewport are measured, they are drawn in this.
  124. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  125. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  126. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  127. null, "position: relative; outline: none");
  128. // Moved around its parent to cover visible view.
  129. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  130. // Set to the height of the document, allowing scrolling.
  131. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  132. d.sizerWidth = null;
  133. // Behavior of elts with overflow: auto and padding is
  134. // inconsistent across browsers. This is used to ensure the
  135. // scrollable area is big enough.
  136. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  137. // Will contain the gutters, if any.
  138. d.gutters = elt("div", null, "CodeMirror-gutters");
  139. d.lineGutter = null;
  140. // Actual scrollable element.
  141. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  142. d.scroller.setAttribute("tabIndex", "-1");
  143. // The element in which the editor lives.
  144. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  145. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  146. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  147. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  148. if (place) {
  149. if (place.appendChild) place.appendChild(d.wrapper);
  150. else place(d.wrapper);
  151. }
  152. // Current rendered range (may be bigger than the view window).
  153. d.viewFrom = d.viewTo = doc.first;
  154. d.reportedViewFrom = d.reportedViewTo = doc.first;
  155. // Information about the rendered lines.
  156. d.view = [];
  157. d.renderedView = null;
  158. // Holds info about a single rendered line when it was rendered
  159. // for measurement, while not in view.
  160. d.externalMeasured = null;
  161. // Empty space (in pixels) above the view
  162. d.viewOffset = 0;
  163. d.lastWrapHeight = d.lastWrapWidth = 0;
  164. d.updateLineNumbers = null;
  165. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  166. d.scrollbarsClipped = false;
  167. // Used to only resize the line number gutter when necessary (when
  168. // the amount of lines crosses a boundary that makes its width change)
  169. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  170. // Set to true when a non-horizontal-scrolling line widget is
  171. // added. As an optimization, line widget aligning is skipped when
  172. // this is false.
  173. d.alignWidgets = false;
  174. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  175. // Tracks the maximum line length so that the horizontal scrollbar
  176. // can be kept static when scrolling.
  177. d.maxLine = null;
  178. d.maxLineLength = 0;
  179. d.maxLineChanged = false;
  180. // Used for measuring wheel scrolling granularity
  181. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  182. // True when shift is held down.
  183. d.shift = false;
  184. // Used to track whether anything happened since the context menu
  185. // was opened.
  186. d.selForContextMenu = null;
  187. d.activeTouch = null;
  188. input.init(d);
  189. }
  190. // STATE UPDATES
  191. // Used to get the editor into a consistent state again when options change.
  192. function loadMode(cm) {
  193. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  194. resetModeState(cm);
  195. }
  196. function resetModeState(cm) {
  197. cm.doc.iter(function(line) {
  198. if (line.stateAfter) line.stateAfter = null;
  199. if (line.styles) line.styles = null;
  200. });
  201. cm.doc.frontier = cm.doc.first;
  202. startWorker(cm, 100);
  203. cm.state.modeGen++;
  204. if (cm.curOp) regChange(cm);
  205. }
  206. function wrappingChanged(cm) {
  207. if (cm.options.lineWrapping) {
  208. addClass(cm.display.wrapper, "CodeMirror-wrap");
  209. cm.display.sizer.style.minWidth = "";
  210. cm.display.sizerWidth = null;
  211. } else {
  212. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  213. findMaxLine(cm);
  214. }
  215. estimateLineHeights(cm);
  216. regChange(cm);
  217. clearCaches(cm);
  218. setTimeout(function(){updateScrollbars(cm);}, 100);
  219. }
  220. // Returns a function that estimates the height of a line, to use as
  221. // first approximation until the line becomes visible (and is thus
  222. // properly measurable).
  223. function estimateHeight(cm) {
  224. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  225. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  226. return function(line) {
  227. if (lineIsHidden(cm.doc, line)) return 0;
  228. var widgetsHeight = 0;
  229. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  230. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  231. }
  232. if (wrapping)
  233. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  234. else
  235. return widgetsHeight + th;
  236. };
  237. }
  238. function estimateLineHeights(cm) {
  239. var doc = cm.doc, est = estimateHeight(cm);
  240. doc.iter(function(line) {
  241. var estHeight = est(line);
  242. if (estHeight != line.height) updateLineHeight(line, estHeight);
  243. });
  244. }
  245. function themeChanged(cm) {
  246. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  247. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  248. clearCaches(cm);
  249. }
  250. function guttersChanged(cm) {
  251. updateGutters(cm);
  252. regChange(cm);
  253. setTimeout(function(){alignHorizontally(cm);}, 20);
  254. }
  255. // Rebuild the gutter elements, ensure the margin to the left of the
  256. // code matches their width.
  257. function updateGutters(cm) {
  258. var gutters = cm.display.gutters, specs = cm.options.gutters;
  259. removeChildren(gutters);
  260. for (var i = 0; i < specs.length; ++i) {
  261. var gutterClass = specs[i];
  262. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  263. if (gutterClass == "CodeMirror-linenumbers") {
  264. cm.display.lineGutter = gElt;
  265. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  266. }
  267. }
  268. gutters.style.display = i ? "" : "none";
  269. updateGutterSpace(cm);
  270. }
  271. function updateGutterSpace(cm) {
  272. var width = cm.display.gutters.offsetWidth;
  273. cm.display.sizer.style.marginLeft = width + "px";
  274. }
  275. // Compute the character length of a line, taking into account
  276. // collapsed ranges (see markText) that might hide parts, and join
  277. // other lines onto it.
  278. function lineLength(line) {
  279. if (line.height == 0) return 0;
  280. var len = line.text.length, merged, cur = line;
  281. while (merged = collapsedSpanAtStart(cur)) {
  282. var found = merged.find(0, true);
  283. cur = found.from.line;
  284. len += found.from.ch - found.to.ch;
  285. }
  286. cur = line;
  287. while (merged = collapsedSpanAtEnd(cur)) {
  288. var found = merged.find(0, true);
  289. len -= cur.text.length - found.from.ch;
  290. cur = found.to.line;
  291. len += cur.text.length - found.to.ch;
  292. }
  293. return len;
  294. }
  295. // Find the longest line in the document.
  296. function findMaxLine(cm) {
  297. var d = cm.display, doc = cm.doc;
  298. d.maxLine = getLine(doc, doc.first);
  299. d.maxLineLength = lineLength(d.maxLine);
  300. d.maxLineChanged = true;
  301. doc.iter(function(line) {
  302. var len = lineLength(line);
  303. if (len > d.maxLineLength) {
  304. d.maxLineLength = len;
  305. d.maxLine = line;
  306. }
  307. });
  308. }
  309. // Make sure the gutters options contains the element
  310. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  311. function setGuttersForLineNumbers(options) {
  312. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  313. if (found == -1 && options.lineNumbers) {
  314. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  315. } else if (found > -1 && !options.lineNumbers) {
  316. options.gutters = options.gutters.slice(0);
  317. options.gutters.splice(found, 1);
  318. }
  319. }
  320. // SCROLLBARS
  321. // Prepare DOM reads needed to update the scrollbars. Done in one
  322. // shot to minimize update/measure roundtrips.
  323. function measureForScrollbars(cm) {
  324. var d = cm.display, gutterW = d.gutters.offsetWidth;
  325. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  326. return {
  327. clientHeight: d.scroller.clientHeight,
  328. viewHeight: d.wrapper.clientHeight,
  329. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  330. viewWidth: d.wrapper.clientWidth,
  331. barLeft: cm.options.fixedGutter ? gutterW : 0,
  332. docHeight: docH,
  333. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  334. nativeBarWidth: d.nativeBarWidth,
  335. gutterWidth: gutterW
  336. };
  337. }
  338. function NativeScrollbars(place, scroll, cm) {
  339. this.cm = cm;
  340. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  341. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  342. place(vert); place(horiz);
  343. on(vert, "scroll", function() {
  344. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  345. });
  346. on(horiz, "scroll", function() {
  347. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  348. });
  349. this.checkedOverlay = false;
  350. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  351. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  352. }
  353. NativeScrollbars.prototype = copyObj({
  354. update: function(measure) {
  355. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  356. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  357. var sWidth = measure.nativeBarWidth;
  358. if (needsV) {
  359. this.vert.style.display = "block";
  360. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  361. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  362. // A bug in IE8 can cause this value to be negative, so guard it.
  363. this.vert.firstChild.style.height =
  364. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  365. } else {
  366. this.vert.style.display = "";
  367. this.vert.firstChild.style.height = "0";
  368. }
  369. if (needsH) {
  370. this.horiz.style.display = "block";
  371. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  372. this.horiz.style.left = measure.barLeft + "px";
  373. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  374. this.horiz.firstChild.style.width =
  375. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  376. } else {
  377. this.horiz.style.display = "";
  378. this.horiz.firstChild.style.width = "0";
  379. }
  380. if (!this.checkedOverlay && measure.clientHeight > 0) {
  381. if (sWidth == 0) this.overlayHack();
  382. this.checkedOverlay = true;
  383. }
  384. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  385. },
  386. setScrollLeft: function(pos) {
  387. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  388. },
  389. setScrollTop: function(pos) {
  390. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  391. },
  392. overlayHack: function() {
  393. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  394. this.horiz.style.minHeight = this.vert.style.minWidth = w;
  395. var self = this;
  396. var barMouseDown = function(e) {
  397. if (e_target(e) != self.vert && e_target(e) != self.horiz)
  398. operation(self.cm, onMouseDown)(e);
  399. };
  400. on(this.vert, "mousedown", barMouseDown);
  401. on(this.horiz, "mousedown", barMouseDown);
  402. },
  403. clear: function() {
  404. var parent = this.horiz.parentNode;
  405. parent.removeChild(this.horiz);
  406. parent.removeChild(this.vert);
  407. }
  408. }, NativeScrollbars.prototype);
  409. function NullScrollbars() {}
  410. NullScrollbars.prototype = copyObj({
  411. update: function() { return {bottom: 0, right: 0}; },
  412. setScrollLeft: function() {},
  413. setScrollTop: function() {},
  414. clear: function() {}
  415. }, NullScrollbars.prototype);
  416. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  417. function initScrollbars(cm) {
  418. if (cm.display.scrollbars) {
  419. cm.display.scrollbars.clear();
  420. if (cm.display.scrollbars.addClass)
  421. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  422. }
  423. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  424. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  425. // Prevent clicks in the scrollbars from killing focus
  426. on(node, "mousedown", function() {
  427. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  428. });
  429. node.setAttribute("cm-not-content", "true");
  430. }, function(pos, axis) {
  431. if (axis == "horizontal") setScrollLeft(cm, pos);
  432. else setScrollTop(cm, pos);
  433. }, cm);
  434. if (cm.display.scrollbars.addClass)
  435. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  436. }
  437. function updateScrollbars(cm, measure) {
  438. if (!measure) measure = measureForScrollbars(cm);
  439. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  440. updateScrollbarsInner(cm, measure);
  441. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  442. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  443. updateHeightsInViewport(cm);
  444. updateScrollbarsInner(cm, measureForScrollbars(cm));
  445. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  446. }
  447. }
  448. // Re-synchronize the fake scrollbars with the actual size of the
  449. // content.
  450. function updateScrollbarsInner(cm, measure) {
  451. var d = cm.display;
  452. var sizes = d.scrollbars.update(measure);
  453. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  454. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  455. if (sizes.right && sizes.bottom) {
  456. d.scrollbarFiller.style.display = "block";
  457. d.scrollbarFiller.style.height = sizes.bottom + "px";
  458. d.scrollbarFiller.style.width = sizes.right + "px";
  459. } else d.scrollbarFiller.style.display = "";
  460. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  461. d.gutterFiller.style.display = "block";
  462. d.gutterFiller.style.height = sizes.bottom + "px";
  463. d.gutterFiller.style.width = measure.gutterWidth + "px";
  464. } else d.gutterFiller.style.display = "";
  465. }
  466. // Compute the lines that are visible in a given viewport (defaults
  467. // the the current scroll position). viewport may contain top,
  468. // height, and ensure (see op.scrollToPos) properties.
  469. function visibleLines(display, doc, viewport) {
  470. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  471. top = Math.floor(top - paddingTop(display));
  472. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  473. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  474. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  475. // forces those lines into the viewport (if possible).
  476. if (viewport && viewport.ensure) {
  477. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  478. if (ensureFrom < from) {
  479. from = ensureFrom;
  480. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  481. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  482. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  483. to = ensureTo;
  484. }
  485. }
  486. return {from: from, to: Math.max(to, from + 1)};
  487. }
  488. // LINE NUMBERS
  489. // Re-align line numbers and gutter marks to compensate for
  490. // horizontal scrolling.
  491. function alignHorizontally(cm) {
  492. var display = cm.display, view = display.view;
  493. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  494. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  495. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  496. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  497. if (cm.options.fixedGutter && view[i].gutter)
  498. view[i].gutter.style.left = left;
  499. var align = view[i].alignable;
  500. if (align) for (var j = 0; j < align.length; j++)
  501. align[j].style.left = left;
  502. }
  503. if (cm.options.fixedGutter)
  504. display.gutters.style.left = (comp + gutterW) + "px";
  505. }
  506. // Used to ensure that the line number gutter is still the right
  507. // size for the current document size. Returns true when an update
  508. // is needed.
  509. function maybeUpdateLineNumberWidth(cm) {
  510. if (!cm.options.lineNumbers) return false;
  511. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  512. if (last.length != display.lineNumChars) {
  513. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  514. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  515. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  516. display.lineGutter.style.width = "";
  517. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  518. display.lineNumWidth = display.lineNumInnerWidth + padding;
  519. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  520. display.lineGutter.style.width = display.lineNumWidth + "px";
  521. updateGutterSpace(cm);
  522. return true;
  523. }
  524. return false;
  525. }
  526. function lineNumberFor(options, i) {
  527. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  528. }
  529. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  530. // but using getBoundingClientRect to get a sub-pixel-accurate
  531. // result.
  532. function compensateForHScroll(display) {
  533. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  534. }
  535. // DISPLAY DRAWING
  536. function DisplayUpdate(cm, viewport, force) {
  537. var display = cm.display;
  538. this.viewport = viewport;
  539. // Store some values that we'll need later (but don't want to force a relayout for)
  540. this.visible = visibleLines(display, cm.doc, viewport);
  541. this.editorIsHidden = !display.wrapper.offsetWidth;
  542. this.wrapperHeight = display.wrapper.clientHeight;
  543. this.wrapperWidth = display.wrapper.clientWidth;
  544. this.oldDisplayWidth = displayWidth(cm);
  545. this.force = force;
  546. this.dims = getDimensions(cm);
  547. this.events = [];
  548. }
  549. DisplayUpdate.prototype.signal = function(emitter, type) {
  550. if (hasHandler(emitter, type))
  551. this.events.push(arguments);
  552. };
  553. DisplayUpdate.prototype.finish = function() {
  554. for (var i = 0; i < this.events.length; i++)
  555. signal.apply(null, this.events[i]);
  556. };
  557. function maybeClipScrollbars(cm) {
  558. var display = cm.display;
  559. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  560. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  561. display.heightForcer.style.height = scrollGap(cm) + "px";
  562. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  563. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  564. display.scrollbarsClipped = true;
  565. }
  566. }
  567. // Does the actual updating of the line display. Bails out
  568. // (returning false) when there is nothing to be done and forced is
  569. // false.
  570. function updateDisplayIfNeeded(cm, update) {
  571. var display = cm.display, doc = cm.doc;
  572. if (update.editorIsHidden) {
  573. resetView(cm);
  574. return false;
  575. }
  576. // Bail out if the visible area is already rendered and nothing changed.
  577. if (!update.force &&
  578. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  579. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  580. display.renderedView == display.view && countDirtyView(cm) == 0)
  581. return false;
  582. if (maybeUpdateLineNumberWidth(cm)) {
  583. resetView(cm);
  584. update.dims = getDimensions(cm);
  585. }
  586. // Compute a suitable new viewport (from & to)
  587. var end = doc.first + doc.size;
  588. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  589. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  590. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  591. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  592. if (sawCollapsedSpans) {
  593. from = visualLineNo(cm.doc, from);
  594. to = visualLineEndNo(cm.doc, to);
  595. }
  596. var different = from != display.viewFrom || to != display.viewTo ||
  597. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  598. adjustView(cm, from, to);
  599. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  600. // Position the mover div to align with the current scroll position
  601. cm.display.mover.style.top = display.viewOffset + "px";
  602. var toUpdate = countDirtyView(cm);
  603. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  604. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  605. return false;
  606. // For big changes, we hide the enclosing element during the
  607. // update, since that speeds up the operations on most browsers.
  608. var focused = activeElt();
  609. if (toUpdate > 4) display.lineDiv.style.display = "none";
  610. patchDisplay(cm, display.updateLineNumbers, update.dims);
  611. if (toUpdate > 4) display.lineDiv.style.display = "";
  612. display.renderedView = display.view;
  613. // There might have been a widget with a focused element that got
  614. // hidden or updated, if so re-focus it.
  615. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  616. // Prevent selection and cursors from interfering with the scroll
  617. // width and height.
  618. removeChildren(display.cursorDiv);
  619. removeChildren(display.selectionDiv);
  620. display.gutters.style.height = 0;
  621. if (different) {
  622. display.lastWrapHeight = update.wrapperHeight;
  623. display.lastWrapWidth = update.wrapperWidth;
  624. startWorker(cm, 400);
  625. }
  626. display.updateLineNumbers = null;
  627. return true;
  628. }
  629. function postUpdateDisplay(cm, update) {
  630. var force = update.force, viewport = update.viewport;
  631. for (var first = true;; first = false) {
  632. if (first && cm.options.lineWrapping && update.oldDisplayWidth != displayWidth(cm)) {
  633. force = true;
  634. } else {
  635. force = false;
  636. // Clip forced viewport to actual scrollable area.
  637. if (viewport && viewport.top != null)
  638. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  639. // Updated line heights might result in the drawn area not
  640. // actually covering the viewport. Keep looping until it does.
  641. update.visible = visibleLines(cm.display, cm.doc, viewport);
  642. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  643. break;
  644. }
  645. if (!updateDisplayIfNeeded(cm, update)) break;
  646. updateHeightsInViewport(cm);
  647. var barMeasure = measureForScrollbars(cm);
  648. updateSelection(cm);
  649. setDocumentHeight(cm, barMeasure);
  650. updateScrollbars(cm, barMeasure);
  651. }
  652. update.signal(cm, "update", cm);
  653. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  654. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  655. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  656. }
  657. }
  658. function updateDisplaySimple(cm, viewport) {
  659. var update = new DisplayUpdate(cm, viewport);
  660. if (updateDisplayIfNeeded(cm, update)) {
  661. updateHeightsInViewport(cm);
  662. postUpdateDisplay(cm, update);
  663. var barMeasure = measureForScrollbars(cm);
  664. updateSelection(cm);
  665. setDocumentHeight(cm, barMeasure);
  666. updateScrollbars(cm, barMeasure);
  667. update.finish();
  668. }
  669. }
  670. function setDocumentHeight(cm, measure) {
  671. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  672. var total = measure.docHeight + cm.display.barHeight;
  673. cm.display.heightForcer.style.top = total + "px";
  674. cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
  675. }
  676. // Read the actual heights of the rendered lines, and update their
  677. // stored heights to match.
  678. function updateHeightsInViewport(cm) {
  679. var display = cm.display;
  680. var prevBottom = display.lineDiv.offsetTop;
  681. for (var i = 0; i < display.view.length; i++) {
  682. var cur = display.view[i], height;
  683. if (cur.hidden) continue;
  684. if (ie && ie_version < 8) {
  685. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  686. height = bot - prevBottom;
  687. prevBottom = bot;
  688. } else {
  689. var box = cur.node.getBoundingClientRect();
  690. height = box.bottom - box.top;
  691. }
  692. var diff = cur.line.height - height;
  693. if (height < 2) height = textHeight(display);
  694. if (diff > .001 || diff < -.001) {
  695. updateLineHeight(cur.line, height);
  696. updateWidgetHeight(cur.line);
  697. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  698. updateWidgetHeight(cur.rest[j]);
  699. }
  700. }
  701. }
  702. // Read and store the height of line widgets associated with the
  703. // given line.
  704. function updateWidgetHeight(line) {
  705. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  706. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  707. }
  708. // Do a bulk-read of the DOM positions and sizes needed to draw the
  709. // view, so that we don't interleave reading and writing to the DOM.
  710. function getDimensions(cm) {
  711. var d = cm.display, left = {}, width = {};
  712. var gutterLeft = d.gutters.clientLeft;
  713. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  714. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  715. width[cm.options.gutters[i]] = n.clientWidth;
  716. }
  717. return {fixedPos: compensateForHScroll(d),
  718. gutterTotalWidth: d.gutters.offsetWidth,
  719. gutterLeft: left,
  720. gutterWidth: width,
  721. wrapperWidth: d.wrapper.clientWidth};
  722. }
  723. // Sync the actual display DOM structure with display.view, removing
  724. // nodes for lines that are no longer in view, and creating the ones
  725. // that are not there yet, and updating the ones that are out of
  726. // date.
  727. function patchDisplay(cm, updateNumbersFrom, dims) {
  728. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  729. var container = display.lineDiv, cur = container.firstChild;
  730. function rm(node) {
  731. var next = node.nextSibling;
  732. // Works around a throw-scroll bug in OS X Webkit
  733. if (webkit && mac && cm.display.currentWheelTarget == node)
  734. node.style.display = "none";
  735. else
  736. node.parentNode.removeChild(node);
  737. return next;
  738. }
  739. var view = display.view, lineN = display.viewFrom;
  740. // Loop over the elements in the view, syncing cur (the DOM nodes
  741. // in display.lineDiv) with the view as we go.
  742. for (var i = 0; i < view.length; i++) {
  743. var lineView = view[i];
  744. if (lineView.hidden) {
  745. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  746. var node = buildLineElement(cm, lineView, lineN, dims);
  747. container.insertBefore(node, cur);
  748. } else { // Already drawn
  749. while (cur != lineView.node) cur = rm(cur);
  750. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  751. updateNumbersFrom <= lineN && lineView.lineNumber;
  752. if (lineView.changes) {
  753. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  754. updateLineForChanges(cm, lineView, lineN, dims);
  755. }
  756. if (updateNumber) {
  757. removeChildren(lineView.lineNumber);
  758. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  759. }
  760. cur = lineView.node.nextSibling;
  761. }
  762. lineN += lineView.size;
  763. }
  764. while (cur) cur = rm(cur);
  765. }
  766. // When an aspect of a line changes, a string is added to
  767. // lineView.changes. This updates the relevant part of the line's
  768. // DOM structure.
  769. function updateLineForChanges(cm, lineView, lineN, dims) {
  770. for (var j = 0; j < lineView.changes.length; j++) {
  771. var type = lineView.changes[j];
  772. if (type == "text") updateLineText(cm, lineView);
  773. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  774. else if (type == "class") updateLineClasses(lineView);
  775. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  776. }
  777. lineView.changes = null;
  778. }
  779. // Lines with gutter elements, widgets or a background class need to
  780. // be wrapped, and have the extra elements added to the wrapper div
  781. function ensureLineWrapped(lineView) {
  782. if (lineView.node == lineView.text) {
  783. lineView.node = elt("div", null, null, "position: relative");
  784. if (lineView.text.parentNode)
  785. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  786. lineView.node.appendChild(lineView.text);
  787. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  788. }
  789. return lineView.node;
  790. }
  791. function updateLineBackground(lineView) {
  792. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  793. if (cls) cls += " CodeMirror-linebackground";
  794. if (lineView.background) {
  795. if (cls) lineView.background.className = cls;
  796. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  797. } else if (cls) {
  798. var wrap = ensureLineWrapped(lineView);
  799. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  800. }
  801. }
  802. // Wrapper around buildLineContent which will reuse the structure
  803. // in display.externalMeasured when possible.
  804. function getLineContent(cm, lineView) {
  805. var ext = cm.display.externalMeasured;
  806. if (ext && ext.line == lineView.line) {
  807. cm.display.externalMeasured = null;
  808. lineView.measure = ext.measure;
  809. return ext.built;
  810. }
  811. return buildLineContent(cm, lineView);
  812. }
  813. // Redraw the line's text. Interacts with the background and text
  814. // classes because the mode may output tokens that influence these
  815. // classes.
  816. function updateLineText(cm, lineView) {
  817. var cls = lineView.text.className;
  818. var built = getLineContent(cm, lineView);
  819. if (lineView.text == lineView.node) lineView.node = built.pre;
  820. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  821. lineView.text = built.pre;
  822. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  823. lineView.bgClass = built.bgClass;
  824. lineView.textClass = built.textClass;
  825. updateLineClasses(lineView);
  826. } else if (cls) {
  827. lineView.text.className = cls;
  828. }
  829. }
  830. function updateLineClasses(lineView) {
  831. updateLineBackground(lineView);
  832. if (lineView.line.wrapClass)
  833. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  834. else if (lineView.node != lineView.text)
  835. lineView.node.className = "";
  836. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  837. lineView.text.className = textClass || "";
  838. }
  839. function updateLineGutter(cm, lineView, lineN, dims) {
  840. if (lineView.gutter) {
  841. lineView.node.removeChild(lineView.gutter);
  842. lineView.gutter = null;
  843. }
  844. var markers = lineView.line.gutterMarkers;
  845. if (cm.options.lineNumbers || markers) {
  846. var wrap = ensureLineWrapped(lineView);
  847. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  848. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  849. "px; width: " + dims.gutterTotalWidth + "px");
  850. cm.display.input.setUneditable(gutterWrap);
  851. wrap.insertBefore(gutterWrap, lineView.text);
  852. if (lineView.line.gutterClass)
  853. gutterWrap.className += " " + lineView.line.gutterClass;
  854. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  855. lineView.lineNumber = gutterWrap.appendChild(
  856. elt("div", lineNumberFor(cm.options, lineN),
  857. "CodeMirror-linenumber CodeMirror-gutter-elt",
  858. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  859. + cm.display.lineNumInnerWidth + "px"));
  860. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  861. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  862. if (found)
  863. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  864. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  865. }
  866. }
  867. }
  868. function updateLineWidgets(cm, lineView, dims) {
  869. if (lineView.alignable) lineView.alignable = null;
  870. for (var node = lineView.node.firstChild, next; node; node = next) {
  871. var next = node.nextSibling;
  872. if (node.className == "CodeMirror-linewidget")
  873. lineView.node.removeChild(node);
  874. }
  875. insertLineWidgets(cm, lineView, dims);
  876. }
  877. // Build a line's DOM representation from scratch
  878. function buildLineElement(cm, lineView, lineN, dims) {
  879. var built = getLineContent(cm, lineView);
  880. lineView.text = lineView.node = built.pre;
  881. if (built.bgClass) lineView.bgClass = built.bgClass;
  882. if (built.textClass) lineView.textClass = built.textClass;
  883. updateLineClasses(lineView);
  884. updateLineGutter(cm, lineView, lineN, dims);
  885. insertLineWidgets(cm, lineView, dims);
  886. return lineView.node;
  887. }
  888. // A lineView may contain multiple logical lines (when merged by
  889. // collapsed spans). The widgets for all of them need to be drawn.
  890. function insertLineWidgets(cm, lineView, dims) {
  891. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  892. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  893. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  894. }
  895. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  896. if (!line.widgets) return;
  897. var wrap = ensureLineWrapped(lineView);
  898. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  899. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  900. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  901. positionLineWidget(widget, node, lineView, dims);
  902. cm.display.input.setUneditable(node);
  903. if (allowAbove && widget.above)
  904. wrap.insertBefore(node, lineView.gutter || lineView.text);
  905. else
  906. wrap.appendChild(node);
  907. signalLater(widget, "redraw");
  908. }
  909. }
  910. function positionLineWidget(widget, node, lineView, dims) {
  911. if (widget.noHScroll) {
  912. (lineView.alignable || (lineView.alignable = [])).push(node);
  913. var width = dims.wrapperWidth;
  914. node.style.left = dims.fixedPos + "px";
  915. if (!widget.coverGutter) {
  916. width -= dims.gutterTotalWidth;
  917. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  918. }
  919. node.style.width = width + "px";
  920. }
  921. if (widget.coverGutter) {
  922. node.style.zIndex = 5;
  923. node.style.position = "relative";
  924. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  925. }
  926. }
  927. // POSITION OBJECT
  928. // A Pos instance represents a position within the text.
  929. var Pos = CodeMirror.Pos = function(line, ch) {
  930. if (!(this instanceof Pos)) return new Pos(line, ch);
  931. this.line = line; this.ch = ch;
  932. };
  933. // Compare two positions, return 0 if they are the same, a negative
  934. // number when a is less, and a positive number otherwise.
  935. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  936. function copyPos(x) {return Pos(x.line, x.ch);}
  937. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  938. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  939. // INPUT HANDLING
  940. function ensureFocus(cm) {
  941. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  942. }
  943. function isReadOnly(cm) {
  944. return cm.options.readOnly || cm.doc.cantEdit;
  945. }
  946. // This will be set to an array of strings when copying, so that,
  947. // when pasting, we know what kind of selections the copied text
  948. // was made out of.
  949. var lastCopied = null;
  950. function applyTextInput(cm, inserted, deleted, sel) {
  951. var doc = cm.doc;
  952. cm.display.shift = false;
  953. if (!sel) sel = doc.sel;
  954. var textLines = splitLines(inserted), multiPaste = null;
  955. // When pasing N lines into N selections, insert one line per selection
  956. if (cm.state.pasteIncoming && sel.ranges.length > 1) {
  957. if (lastCopied && lastCopied.join("\n") == inserted)
  958. multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
  959. else if (textLines.length == sel.ranges.length)
  960. multiPaste = map(textLines, function(l) { return [l]; });
  961. }
  962. // Normal behavior is to insert the new text into every selection
  963. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  964. var range = sel.ranges[i];
  965. var from = range.from(), to = range.to();
  966. if (range.empty()) {
  967. if (deleted && deleted > 0) // Handle deletion
  968. from = Pos(from.line, from.ch - deleted);
  969. else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
  970. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  971. }
  972. var updateInput = cm.curOp.updateInput;
  973. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  974. origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
  975. makeChange(cm.doc, changeEvent);
  976. signalLater(cm, "inputRead", cm, changeEvent);
  977. // When an 'electric' character is inserted, immediately trigger a reindent
  978. if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
  979. cm.options.smartIndent && range.head.ch < 100 &&
  980. (!i || sel.ranges[i - 1].head.line != range.head.line)) {
  981. var mode = cm.getModeAt(range.head);
  982. var end = changeEnd(changeEvent);
  983. if (mode.electricChars) {
  984. for (var j = 0; j < mode.electricChars.length; j++)
  985. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  986. indentLine(cm, end.line, "smart");
  987. break;
  988. }
  989. } else if (mode.electricInput) {
  990. if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
  991. indentLine(cm, end.line, "smart");
  992. }
  993. }
  994. }
  995. ensureCursorVisible(cm);
  996. cm.curOp.updateInput = updateInput;
  997. cm.curOp.typing = true;
  998. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  999. }
  1000. function copyableRanges(cm) {
  1001. var text = [], ranges = [];
  1002. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1003. var line = cm.doc.sel.ranges[i].head.line;
  1004. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1005. ranges.push(lineRange);
  1006. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1007. }
  1008. return {text: text, ranges: ranges};
  1009. }
  1010. function disableBrowserMagic(field) {
  1011. field.setAttribute("autocorrect", "off");
  1012. field.setAttribute("autocapitalize", "off");
  1013. field.setAttribute("spellcheck", "false");
  1014. }
  1015. // TEXTAREA INPUT STYLE
  1016. function TextareaInput(cm) {
  1017. this.cm = cm;
  1018. // See input.poll and input.reset
  1019. this.prevInput = "";
  1020. // Flag that indicates whether we expect input to appear real soon
  1021. // now (after some event like 'keypress' or 'input') and are
  1022. // polling intensively.
  1023. this.pollingFast = false;
  1024. // Self-resetting timeout for the poller
  1025. this.polling = new Delayed();
  1026. // Tracks when input.reset has punted to just putting a short
  1027. // string into the textarea instead of the full selection.
  1028. this.inaccurateSelection = false;
  1029. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1030. this.hasSelection = false;
  1031. };
  1032. function hiddenTextarea() {
  1033. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1034. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1035. // The textarea is kept positioned near the cursor to prevent the
  1036. // fact that it'll be scrolled into view on input from scrolling
  1037. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1038. // very slow. So make the area wide instead.
  1039. if (webkit) te.style.width = "1000px";
  1040. else te.setAttribute("wrap", "off");
  1041. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1042. if (ios) te.style.border = "1px solid black";
  1043. disableBrowserMagic(te);
  1044. return div;
  1045. }
  1046. TextareaInput.prototype = copyObj({
  1047. init: function(display) {
  1048. var input = this, cm = this.cm;
  1049. // Wraps and hides input textarea
  1050. var div = this.wrapper = hiddenTextarea();
  1051. // The semihidden textarea that is focused when the editor is
  1052. // focused, and receives input.
  1053. var te = this.textarea = div.firstChild;
  1054. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1055. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1056. if (ios) te.style.width = "0px";
  1057. on(te, "input", function() {
  1058. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1059. input.poll();
  1060. });
  1061. on(te, "paste", function() {
  1062. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  1063. // Add a char to the end of textarea before paste occur so that
  1064. // selection doesn't span to the end of textarea.
  1065. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  1066. var start = te.selectionStart, end = te.selectionEnd;
  1067. te.value += "$";
  1068. // The selection end needs to be set before the start, otherwise there
  1069. // can be an intermediate non-empty selection between the two, which
  1070. // can override the middle-click paste buffer on linux and cause the
  1071. // wrong thing to get pasted.
  1072. te.selectionEnd = end;
  1073. te.selectionStart = start;
  1074. cm.state.fakedLastChar = true;
  1075. }
  1076. cm.state.pasteIncoming = true;
  1077. input.fastPoll();
  1078. });
  1079. function prepareCopyCut(e) {
  1080. if (cm.somethingSelected()) {
  1081. lastCopied = cm.getSelections();
  1082. if (input.inaccurateSelection) {
  1083. input.prevInput = "";
  1084. input.inaccurateSelection = false;
  1085. te.value = lastCopied.join("\n");
  1086. selectInput(te);
  1087. }
  1088. } else {
  1089. var ranges = copyableRanges(cm);
  1090. lastCopied = ranges.text;
  1091. if (e.type == "cut") {
  1092. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1093. } else {
  1094. input.prevInput = "";
  1095. te.value = ranges.text.join("\n");
  1096. selectInput(te);
  1097. }
  1098. }
  1099. if (e.type == "cut") cm.state.cutIncoming = true;
  1100. }
  1101. on(te, "cut", prepareCopyCut);
  1102. on(te, "copy", prepareCopyCut);
  1103. on(display.scroller, "paste", function(e) {
  1104. if (eventInWidget(display, e)) return;
  1105. cm.state.pasteIncoming = true;
  1106. input.focus();
  1107. });
  1108. // Prevent normal selection in the editor (we handle our own)
  1109. on(display.lineSpace, "selectstart", function(e) {
  1110. if (!eventInWidget(display, e)) e_preventDefault(e);
  1111. });
  1112. },
  1113. prepareSelection: function() {
  1114. // Redraw the selection and/or cursor
  1115. var cm = this.cm, display = cm.display, doc = cm.doc;
  1116. var result = prepareSelection(cm);
  1117. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1118. if (cm.options.moveInputWithCursor) {
  1119. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1120. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1121. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1122. headPos.top + lineOff.top - wrapOff.top));
  1123. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1124. headPos.left + lineOff.left - wrapOff.left));
  1125. }
  1126. return result;
  1127. },
  1128. showSelection: function(drawn) {
  1129. var cm = this.cm, display = cm.display;
  1130. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1131. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1132. if (drawn.teTop != null) {
  1133. this.wrapper.style.top = drawn.teTop + "px";
  1134. this.wrapper.style.left = drawn.teLeft + "px";
  1135. }
  1136. },
  1137. // Reset the input to correspond to the selection (or to be empty,
  1138. // when not typing and nothing is selected)
  1139. reset: function(typing) {
  1140. if (this.contextMenuPending) return;
  1141. var minimal, selected, cm = this.cm, doc = cm.doc;
  1142. if (cm.somethingSelected()) {
  1143. this.prevInput = "";
  1144. var range = doc.sel.primary();
  1145. minimal = hasCopyEvent &&
  1146. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1147. var content = minimal ? "-" : selected || cm.getSelection();
  1148. this.textarea.value = content;
  1149. if (cm.state.focused) selectInput(this.textarea);
  1150. if (ie && ie_version >= 9) this.hasSelection = content;
  1151. } else if (!typing) {
  1152. this.prevInput = this.textarea.value = "";
  1153. if (ie && ie_version >= 9) this.hasSelection = null;
  1154. }
  1155. this.inaccurateSelection = minimal;
  1156. },
  1157. getField: function() { return this.textarea; },
  1158. supportsTouch: function() { return false; },
  1159. focus: function() {
  1160. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1161. try { this.textarea.focus(); }
  1162. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1163. }
  1164. },
  1165. blur: function() { this.textarea.blur(); },
  1166. resetPosition: function() {
  1167. this.wrapper.style.top = this.wrapper.style.left = 0;
  1168. },
  1169. receivedFocus: function() { this.slowPoll(); },
  1170. // Poll for input changes, using the normal rate of polling. This
  1171. // runs as long as the editor is focused.
  1172. slowPoll: function() {
  1173. var input = this;
  1174. if (input.pollingFast) return;
  1175. input.polling.set(this.cm.options.pollInterval, function() {
  1176. input.poll();
  1177. if (input.cm.state.focused) input.slowPoll();
  1178. });
  1179. },
  1180. // When an event has just come in that is likely to add or change
  1181. // something in the input textarea, we poll faster, to ensure that
  1182. // the change appears on the screen quickly.
  1183. fastPoll: function() {
  1184. var missed = false, input = this;
  1185. input.pollingFast = true;
  1186. function p() {
  1187. var changed = input.poll();
  1188. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1189. else {input.pollingFast = false; input.slowPoll();}
  1190. }
  1191. input.polling.set(20, p);
  1192. },
  1193. // Read input from the textarea, and update the document to match.
  1194. // When something is selected, it is present in the textarea, and
  1195. // selected (unless it is huge, in which case a placeholder is
  1196. // used). When nothing is selected, the cursor sits after previously
  1197. // seen text (can be empty), which is stored in prevInput (we must
  1198. // not reset the textarea when typing, because that breaks IME).
  1199. poll: function() {
  1200. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1201. // Since this is called a *lot*, try to bail out as cheaply as
  1202. // possible when it is clear that nothing happened. hasSelection
  1203. // will be the case when there is a lot of text in the textarea,
  1204. // in which case reading its value would be expensive.
  1205. if (!cm.state.focused || (hasSelection(input) && !prevInput) ||
  1206. isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
  1207. return false;
  1208. // See paste handler for more on the fakedLastChar kludge
  1209. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  1210. input.value = input.value.substring(0, input.value.length - 1);
  1211. cm.state.fakedLastChar = false;
  1212. }
  1213. var text = input.value;
  1214. // If nothing changed, bail.
  1215. if (text == prevInput && !cm.somethingSelected()) return false;
  1216. // Work around nonsensical selection resetting in IE9/10, and
  1217. // inexplicable appearance of private area unicode characters on
  1218. // some key combos in Mac (#2689).
  1219. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1220. mac && /[\uf700-\uf7ff]/.test(text)) {
  1221. cm.display.input.reset();
  1222. return false;
  1223. }
  1224. if (text.charCodeAt(0) == 0x200b && cm.doc.sel == cm.display.selForContextMenu && !prevInput)
  1225. prevInput = "\u200b";
  1226. // Find the part of the input that is actually new
  1227. var same = 0, l = Math.min(prevInput.length, text.length);
  1228. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1229. var self = this;
  1230. runInOp(cm, function() {
  1231. applyTextInput(cm, text.slice(same), prevInput.length - same);
  1232. // Don't leave long text in the textarea, since it makes further polling slow
  1233. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1234. else self.prevInput = text;
  1235. });
  1236. return true;
  1237. },
  1238. ensurePolled: function() {
  1239. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1240. },
  1241. onKeyPress: function() {
  1242. if (ie && ie_version >= 9) this.hasSelection = null;
  1243. this.fastPoll();
  1244. },
  1245. onContextMenu: function(e) {
  1246. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1247. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1248. if (!pos || presto) return; // Opera is difficult.
  1249. // Reset the current text selection only if the click is done outside of the selection
  1250. // and 'resetSelectionOnContextMenu' option is true.
  1251. var reset = cm.options.resetSelectionOnContextMenu;
  1252. if (reset && cm.doc.sel.contains(pos) == -1)
  1253. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1254. var oldCSS = te.style.cssText;
  1255. input.wrapper.style.position = "absolute";
  1256. te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1257. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  1258. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1259. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1260. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1261. display.input.focus();
  1262. if (webkit) window.scrollTo(null, oldScrollY);
  1263. display.input.reset();
  1264. // Adds "Select all" to context menu in FF
  1265. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1266. input.contextMenuPending = true;
  1267. display.selForContextMenu = cm.doc.sel;
  1268. clearTimeout(display.detectingSelectAll);
  1269. // Select-all will be greyed out if there's nothing to select, so
  1270. // this adds a zero-width space so that we can later check whether
  1271. // it got selected.
  1272. function prepareSelectAllHack() {
  1273. if (te.selectionStart != null) {
  1274. var selected = cm.somethingSelected();
  1275. var extval = te.value = "\u200b" + (selected ? te.value : "");
  1276. input.prevInput = selected ? "" : "\u200b";
  1277. te.selectionStart = 1; te.selectionEnd = extval.length;
  1278. // Re-set this, in case some other handler touched the
  1279. // selection in the meantime.
  1280. display.selForContextMenu = cm.doc.sel;
  1281. }
  1282. }
  1283. function rehide() {
  1284. input.contextMenuPending = false;
  1285. input.wrapper.style.position = "relative";
  1286. te.style.cssText = oldCSS;
  1287. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1288. // Try to detect the user choosing select-all
  1289. if (te.selectionStart != null) {
  1290. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1291. var i = 0, poll = function() {
  1292. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0)
  1293. operation(cm, commands.selectAll)(cm);
  1294. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1295. else display.input.reset();
  1296. };
  1297. display.detectingSelectAll = setTimeout(poll, 200);
  1298. }
  1299. }
  1300. if (ie && ie_version >= 9) prepareSelectAllHack();
  1301. if (captureRightClick) {
  1302. e_stop(e);
  1303. var mouseup = function() {
  1304. off(window, "mouseup", mouseup);
  1305. setTimeout(rehide, 20);
  1306. };
  1307. on(window, "mouseup", mouseup);
  1308. } else {
  1309. setTimeout(rehide, 50);
  1310. }
  1311. },
  1312. setUneditable: nothing,
  1313. needsContentAttribute: false
  1314. }, TextareaInput.prototype);
  1315. // CONTENTEDITABLE INPUT STYLE
  1316. function ContentEditableInput(cm) {
  1317. this.cm = cm;
  1318. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1319. this.polling = new Delayed();
  1320. }
  1321. ContentEditableInput.prototype = copyObj({
  1322. init: function(display) {
  1323. var input = this, cm = input.cm;
  1324. var div = input.div = display.lineDiv;
  1325. div.contentEditable = "true";
  1326. disableBrowserMagic(div);
  1327. on(div, "paste", function(e) {
  1328. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1329. if (pasted) {
  1330. e.preventDefault();
  1331. cm.replaceSelection(pasted, null, "paste");
  1332. }
  1333. });
  1334. on(div, "compositionstart", function(e) {
  1335. var data = e.data;
  1336. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1337. if (!data) return;
  1338. var prim = cm.doc.sel.primary();
  1339. var line = cm.getLine(prim.head.line);
  1340. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1341. if (found > -1 && found <= prim.head.ch)
  1342. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1343. Pos(prim.head.line, found + data.length));
  1344. });
  1345. on(div, "compositionupdate", function(e) {
  1346. input.composing.data = e.data;
  1347. });
  1348. on(div, "compositionend", function(e) {
  1349. var ours = input.composing;
  1350. if (!ours) return;
  1351. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1352. ours.data = e.data;
  1353. // Need a small delay to prevent other code (input event,
  1354. // selection polling) from doing damage when fired right after
  1355. // compositionend.
  1356. setTimeout(function() {
  1357. if (!ours.handled)
  1358. input.applyComposition(ours);
  1359. if (input.composing == ours)
  1360. input.composing = null;
  1361. }, 50);
  1362. });
  1363. on(div, "touchstart", function() {
  1364. input.forceCompositionEnd();
  1365. });
  1366. on(div, "input", function() {
  1367. if (input.composing) return;
  1368. if (!input.pollContent())
  1369. runInOp(input.cm, function() {regChange(cm);});
  1370. });
  1371. function onCopyCut(e) {
  1372. if (cm.somethingSelected()) {
  1373. lastCopied = cm.getSelections();
  1374. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1375. } else {
  1376. var ranges = copyableRanges(cm);
  1377. lastCopied = ranges.text;
  1378. if (e.type == "cut") {
  1379. cm.operation(function() {
  1380. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1381. cm.replaceSelection("", null, "cut");
  1382. });
  1383. }
  1384. }
  1385. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1386. if (e.clipboardData && !ios) {
  1387. e.preventDefault();
  1388. e.clipboardData.clearData();
  1389. e.clipboardData.setData("text/plain", lastCopied.join("\n"));
  1390. } else {
  1391. // Old-fashioned briefly-focus-a-textarea hack
  1392. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1393. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1394. te.value = lastCopied.join("\n");
  1395. var hadFocus = document.activeElement;
  1396. selectInput(te);
  1397. setTimeout(function() {
  1398. cm.display.lineSpace.removeChild(kludge);
  1399. hadFocus.focus();
  1400. }, 50);
  1401. }
  1402. }
  1403. on(div, "copy", onCopyCut);
  1404. on(div, "cut", onCopyCut);
  1405. },
  1406. prepareSelection: function() {
  1407. var result = prepareSelection(this.cm, false);
  1408. result.focus = this.cm.state.focused;
  1409. return result;
  1410. },
  1411. showSelection: function(info) {
  1412. if (!info || !this.cm.display.view.length) return;
  1413. if (info.focus) this.showPrimarySelection();
  1414. this.showMultipleSelections(info);
  1415. },
  1416. showPrimarySelection: function() {
  1417. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1418. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1419. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1420. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1421. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1422. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1423. return;
  1424. var start = posToDOM(this.cm, prim.from());
  1425. var end = posToDOM(this.cm, prim.to());
  1426. if (!start && !end) return;
  1427. var view = this.cm.display.view;
  1428. var old = sel.rangeCount && sel.getRangeAt(0);
  1429. if (!start) {
  1430. start = {node: view[0].measure.map[2], offset: 0};
  1431. } else if (!end) { // FIXME dangerously hacky
  1432. var measure = view[view.length - 1].measure;
  1433. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1434. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1435. }
  1436. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1437. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1438. if (rng) {
  1439. sel.removeAllRanges();
  1440. sel.addRange(rng);
  1441. if (old && sel.anchorNode == null) sel.addRange(old);
  1442. }
  1443. this.rememberSelection();
  1444. },
  1445. showMultipleSelections: function(info) {
  1446. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1447. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1448. },
  1449. rememberSelection: function() {
  1450. var sel = window.getSelection();
  1451. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1452. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1453. },
  1454. selectionInEditor: function() {
  1455. var sel = window.getSelection();
  1456. if (!sel.rangeCount) return false;
  1457. var node = sel.getRangeAt(0).commonAncestorContainer;
  1458. return contains(this.div, node);
  1459. },
  1460. focus: function() {
  1461. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1462. },
  1463. blur: function() { this.div.blur(); },
  1464. getField: function() { return this.div; },
  1465. supportsTouch: function() { return true; },
  1466. receivedFocus: function() {
  1467. var input = this;
  1468. if (this.selectionInEditor())
  1469. this.pollSelection();
  1470. else
  1471. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1472. function poll() {
  1473. if (input.cm.state.focused) {
  1474. input.pollSelection();
  1475. input.polling.set(input.cm.options.pollInterval, poll);
  1476. }
  1477. }
  1478. this.polling.set(this.cm.options.pollInterval, poll);
  1479. },
  1480. pollSelection: function() {
  1481. if (this.composing) return;
  1482. var sel = window.getSelection(), cm = this.cm;
  1483. if (sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1484. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset) {
  1485. this.rememberSelection();
  1486. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1487. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1488. if (anchor && head) runInOp(cm, function() {
  1489. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1490. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1491. });
  1492. }
  1493. },
  1494. pollContent: function() {
  1495. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1496. var from = sel.from(), to = sel.to();
  1497. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1498. var fromIndex;
  1499. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1500. var fromLine = lineNo(display.view[0].line);
  1501. var fromNode = display.view[0].node;
  1502. } else {
  1503. var fromLine = lineNo(display.view[fromIndex].line);
  1504. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1505. }
  1506. var toIndex = findViewIndex(cm, to.line);
  1507. if (toIndex == display.view.length - 1) {
  1508. var toLine = display.viewTo - 1;
  1509. var toNode = display.view[toIndex].node;
  1510. } else {
  1511. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1512. var toNode = display.view[toIndex + 1].node.previousSibling;
  1513. }
  1514. var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1515. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1516. while (newText.length > 1 && oldText.length > 1) {
  1517. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1518. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1519. else break;
  1520. }
  1521. var cutFront = 0, cutEnd = 0;
  1522. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1523. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1524. ++cutFront;
  1525. var newBot = lst(newText), oldBot = lst(oldText);
  1526. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1527. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1528. while (cutEnd < maxCutEnd &&
  1529. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1530. ++cutEnd;
  1531. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1532. newText[0] = newText[0].slice(cutFront);
  1533. var chFrom = Pos(fromLine, cutFront);
  1534. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1535. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1536. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1537. return true;
  1538. }
  1539. },
  1540. ensurePolled: function() {
  1541. this.forceCompositionEnd();
  1542. },
  1543. reset: function() {
  1544. this.forceCompositionEnd();
  1545. },
  1546. forceCompositionEnd: function() {
  1547. if (!this.composing || this.composing.handled) return;
  1548. this.applyComposition(this.composing);
  1549. this.composing.handled = true;
  1550. this.div.blur();
  1551. this.div.focus();
  1552. },
  1553. applyComposition: function(composing) {
  1554. if (composing.data && composing.data != composing.startData)
  1555. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1556. },
  1557. setUneditable: function(node) {
  1558. node.setAttribute("contenteditable", "false");
  1559. },
  1560. onKeyPress: function(e) {
  1561. e.preventDefault();
  1562. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1563. },
  1564. onContextMenu: nothing,
  1565. resetPosition: nothing,
  1566. needsContentAttribute: true
  1567. }, ContentEditableInput.prototype);
  1568. function posToDOM(cm, pos) {
  1569. var view = findViewForLine(cm, pos.line);
  1570. if (!view || view.hidden) return null;
  1571. var line = getLine(cm.doc, pos.line);
  1572. var info = mapFromLineView(view, line, pos.line);
  1573. var order = getOrder(line), side = "left";
  1574. if (order) {
  1575. var partPos = getBidiPartAt(order, pos.ch);
  1576. side = partPos % 2 ? "right" : "left";
  1577. }
  1578. var result = nodeAndOffsetInLineMap(info.map, pos.ch, "left");
  1579. result.offset = result.collapse == "right" ? result.end : result.start;
  1580. return result;
  1581. }
  1582. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1583. function domToPos(cm, node, offset) {
  1584. var lineNode;
  1585. if (node == cm.display.lineDiv) {
  1586. lineNode = cm.display.lineDiv.childNodes[offset];
  1587. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1588. node = null; offset = 0;
  1589. } else {
  1590. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1591. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1592. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1593. }
  1594. }
  1595. for (var i = 0; i < cm.display.view.length; i++) {
  1596. var lineView = cm.display.view[i];
  1597. if (lineView.node == lineNode)
  1598. return locateNodeInLineView(lineView, node, offset);
  1599. }
  1600. }
  1601. function locateNodeInLineView(lineView, node, offset) {
  1602. var wrapper = lineView.text.firstChild, bad = false;
  1603. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1604. if (node == wrapper) {
  1605. bad = true;
  1606. node = wrapper.childNodes[offset];
  1607. offset = 0;
  1608. if (!node) {
  1609. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1610. return badPos(Pos(lineNo(line), line.text.length), bad);
  1611. }
  1612. }
  1613. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1614. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1615. textNode = node.firstChild;
  1616. if (offset) offset = textNode.nodeValue.length;
  1617. }
  1618. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1619. var measure = lineView.measure, maps = measure.maps;
  1620. function find(textNode, topNode, offset) {
  1621. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1622. var map = i < 0 ? measure.map : maps[i];
  1623. for (var j = 0; j < map.length; j += 3) {
  1624. var curNode = map[j + 2];
  1625. if (curNode == textNode || curNode == topNode) {
  1626. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1627. var ch = map[j] + offset;
  1628. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1629. return Pos(line, ch);
  1630. }
  1631. }
  1632. }
  1633. }
  1634. var found = find(textNode, topNode, offset);
  1635. if (found) return badPos(found, bad);
  1636. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1637. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1638. found = find(after, after.firstChild, 0);
  1639. if (found)
  1640. return badPos(Pos(found.line, found.ch - dist), bad);
  1641. else
  1642. dist += after.textContent.length;
  1643. }
  1644. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1645. found = find(before, before.firstChild, -1);
  1646. if (found)
  1647. return badPos(Pos(found.line, found.ch + dist), bad);
  1648. else
  1649. dist += after.textContent.length;
  1650. }
  1651. }
  1652. function domTextBetween(cm, from, to, fromLine, toLine) {
  1653. var text = "", closing = false;
  1654. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1655. function walk(node) {
  1656. if (node.nodeType == 1) {
  1657. var cmText = node.getAttribute("cm-text");
  1658. if (cmText != null) {
  1659. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1660. text += cmText;
  1661. return;
  1662. }
  1663. var markerID = node.getAttribute("cm-marker"), range;
  1664. if (markerID) {
  1665. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1666. if (found.length && (range = found[0].find()))
  1667. text += getBetween(cm.doc, range.from, range.to).join("\n");
  1668. return;
  1669. }
  1670. if (node.getAttribute("contenteditable") == "false") return;
  1671. for (var i = 0; i < node.childNodes.length; i++)
  1672. walk(node.childNodes[i]);
  1673. if (/^(pre|div|p)$/i.test(node.nodeName))
  1674. closing = true;
  1675. } else if (node.nodeType == 3) {
  1676. var val = node.nodeValue;
  1677. if (!val) return;
  1678. if (closing) {
  1679. text += "\n";
  1680. closing = false;
  1681. }
  1682. text += val;
  1683. }
  1684. }
  1685. for (;;) {
  1686. walk(from);
  1687. if (from == to) break;
  1688. from = from.nextSibling;
  1689. }
  1690. return text;
  1691. }
  1692. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1693. // SELECTION / CURSOR
  1694. // Selection objects are immutable. A new one is created every time
  1695. // the selection changes. A selection is one or more non-overlapping
  1696. // (and non-touching) ranges, sorted, and an integer that indicates
  1697. // which one is the primary selection (the one that's scrolled into
  1698. // view, that getCursor returns, etc).
  1699. function Selection(ranges, primIndex) {
  1700. this.ranges = ranges;
  1701. this.primIndex = primIndex;
  1702. }
  1703. Selection.prototype = {
  1704. primary: function() { return this.ranges[this.primIndex]; },
  1705. equals: function(other) {
  1706. if (other == this) return true;
  1707. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1708. for (var i = 0; i < this.ranges.length; i++) {
  1709. var here = this.ranges[i], there = other.ranges[i];
  1710. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1711. }
  1712. return true;
  1713. },
  1714. deepCopy: function() {
  1715. for (var out = [], i = 0; i < this.ranges.length; i++)
  1716. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1717. return new Selection(out, this.primIndex);
  1718. },
  1719. somethingSelected: function() {
  1720. for (var i = 0; i < this.ranges.length; i++)
  1721. if (!this.ranges[i].empty()) return true;
  1722. return false;
  1723. },
  1724. contains: function(pos, end) {
  1725. if (!end) end = pos;
  1726. for (var i = 0; i < this.ranges.length; i++) {
  1727. var range = this.ranges[i];
  1728. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1729. return i;
  1730. }
  1731. return -1;
  1732. }
  1733. };
  1734. function Range(anchor, head) {
  1735. this.anchor = anchor; this.head = head;
  1736. }
  1737. Range.prototype = {
  1738. from: function() { return minPos(this.anchor, this.head); },
  1739. to: function() { return maxPos(this.anchor, this.head); },
  1740. empty: function() {
  1741. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1742. }
  1743. };
  1744. // Take an unsorted, potentially overlapping set of ranges, and
  1745. // build a selection out of it. 'Consumes' ranges array (modifying
  1746. // it).
  1747. function normalizeSelection(ranges, primIndex) {
  1748. var prim = ranges[primIndex];
  1749. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1750. primIndex = indexOf(ranges, prim);
  1751. for (var i = 1; i < ranges.length; i++) {
  1752. var cur = ranges[i], prev = ranges[i - 1];
  1753. if (cmp(prev.to(), cur.from()) >= 0) {
  1754. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1755. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1756. if (i <= primIndex) --primIndex;
  1757. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1758. }
  1759. }
  1760. return new Selection(ranges, primIndex);
  1761. }
  1762. function simpleSelection(anchor, head) {
  1763. return new Selection([new Range(anchor, head || anchor)], 0);
  1764. }
  1765. // Most of the external API clips given positions to make sure they
  1766. // actually exist within the document.
  1767. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1768. function clipPos(doc, pos) {
  1769. if (pos.line < doc.first) return Pos(doc.first, 0);
  1770. var last = doc.first + doc.size - 1;
  1771. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1772. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1773. }
  1774. function clipToLen(pos, linelen) {
  1775. var ch = pos.ch;
  1776. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1777. else if (ch < 0) return Pos(pos.line, 0);
  1778. else return pos;
  1779. }
  1780. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1781. function clipPosArray(doc, array) {
  1782. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1783. return out;
  1784. }
  1785. // SELECTION UPDATES
  1786. // The 'scroll' parameter given to many of these indicated whether
  1787. // the new cursor position should be scrolled into view after
  1788. // modifying the selection.
  1789. // If shift is held or the extend flag is set, extends a range to
  1790. // include a given position (and optionally a second position).
  1791. // Otherwise, simply returns the range between the given positions.
  1792. // Used for cursor motion and such.
  1793. function extendRange(doc, range, head, other) {
  1794. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1795. var anchor = range.anchor;
  1796. if (other) {
  1797. var posBefore = cmp(head, anchor) < 0;
  1798. if (posBefore != (cmp(other, anchor) < 0)) {
  1799. anchor = head;
  1800. head = other;
  1801. } else if (posBefore != (cmp(head, other) < 0)) {
  1802. head = other;
  1803. }
  1804. }
  1805. return new Range(anchor, head);
  1806. } else {
  1807. return new Range(other || head, head);
  1808. }
  1809. }
  1810. // Extend the primary selection range, discard the rest.
  1811. function extendSelection(doc, head, other, options) {
  1812. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1813. }
  1814. // Extend all selections (pos is an array of selections with length
  1815. // equal the number of selections)
  1816. function extendSelections(doc, heads, options) {
  1817. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1818. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1819. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1820. setSelection(doc, newSel, options);
  1821. }
  1822. // Updates a single range in the selection.
  1823. function replaceOneSelection(doc, i, range, options) {
  1824. var ranges = doc.sel.ranges.slice(0);
  1825. ranges[i] = range;
  1826. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1827. }
  1828. // Reset the selection to a single range.
  1829. function setSimpleSelection(doc, anchor, head, options) {
  1830. setSelection(doc, simpleSelection(anchor, head), options);
  1831. }
  1832. // Give beforeSelectionChange handlers a change to influence a
  1833. // selection update.
  1834. function filterSelectionChange(doc, sel) {
  1835. var obj = {
  1836. ranges: sel.ranges,
  1837. update: function(ranges) {
  1838. this.ranges = [];
  1839. for (var i = 0; i < ranges.length; i++)
  1840. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1841. clipPos(doc, ranges[i].head));
  1842. }
  1843. };
  1844. signal(doc, "beforeSelectionChange", doc, obj);
  1845. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1846. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1847. else return sel;
  1848. }
  1849. function setSelectionReplaceHistory(doc, sel, options) {
  1850. var done = doc.history.done, last = lst(done);
  1851. if (last && last.ranges) {
  1852. done[done.length - 1] = sel;
  1853. setSelectionNoUndo(doc, sel, options);
  1854. } else {
  1855. setSelection(doc, sel, options);
  1856. }
  1857. }
  1858. // Set a new selection.
  1859. function setSelection(doc, sel, options) {
  1860. setSelectionNoUndo(doc, sel, options);
  1861. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1862. }
  1863. function setSelectionNoUndo(doc, sel, options) {
  1864. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1865. sel = filterSelectionChange(doc, sel);
  1866. var bias = options && options.bias ||
  1867. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1868. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1869. if (!(options && options.scroll === false) && doc.cm)
  1870. ensureCursorVisible(doc.cm);
  1871. }
  1872. function setSelectionInner(doc, sel) {
  1873. if (sel.equals(doc.sel)) return;
  1874. doc.sel = sel;
  1875. if (doc.cm) {
  1876. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1877. signalCursorActivity(doc.cm);
  1878. }
  1879. signalLater(doc, "cursorActivity", doc);
  1880. }
  1881. // Verify that the selection does not partially select any atomic
  1882. // marked ranges.
  1883. function reCheckSelection(doc) {
  1884. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1885. }
  1886. // Return a selection that does not partially select any atomic
  1887. // ranges.
  1888. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1889. var out;
  1890. for (var i = 0; i < sel.ranges.length; i++) {
  1891. var range = sel.ranges[i];
  1892. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1893. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1894. if (out || newAnchor != range.anchor || newHead != range.head) {
  1895. if (!out) out = sel.ranges.slice(0, i);
  1896. out[i] = new Range(newAnchor, newHead);
  1897. }
  1898. }
  1899. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1900. }
  1901. // Ensure a given position is not inside an atomic range.
  1902. function skipAtomic(doc, pos, bias, mayClear) {
  1903. var flipped = false, curPos = pos;
  1904. var dir = bias || 1;
  1905. doc.cantEdit = false;
  1906. search: for (;;) {
  1907. var line = getLine(doc, curPos.line);
  1908. if (line.markedSpans) {
  1909. for (var i = 0; i < line.markedSpans.length; ++i) {
  1910. var sp = line.markedSpans[i], m = sp.marker;
  1911. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1912. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1913. if (mayClear) {
  1914. signal(m, "beforeCursorEnter");
  1915. if (m.explicitlyCleared) {
  1916. if (!line.markedSpans) break;
  1917. else {--i; continue;}
  1918. }
  1919. }
  1920. if (!m.atomic) continue;
  1921. var newPos = m.find(dir < 0 ? -1 : 1);
  1922. if (cmp(newPos, curPos) == 0) {
  1923. newPos.ch += dir;
  1924. if (newPos.ch < 0) {
  1925. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1926. else newPos = null;
  1927. } else if (newPos.ch > line.text.length) {
  1928. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1929. else newPos = null;
  1930. }
  1931. if (!newPos) {
  1932. if (flipped) {
  1933. // Driven in a corner -- no valid cursor position found at all
  1934. // -- try again *with* clearing, if we didn't already
  1935. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1936. // Otherwise, turn off editing until further notice, and return the start of the doc
  1937. doc.cantEdit = true;
  1938. return Pos(doc.first, 0);
  1939. }
  1940. flipped = true; newPos = pos; dir = -dir;
  1941. }
  1942. }
  1943. curPos = newPos;
  1944. continue search;
  1945. }
  1946. }
  1947. }
  1948. return curPos;
  1949. }
  1950. }
  1951. // SELECTION DRAWING
  1952. function updateSelection(cm) {
  1953. cm.display.input.showSelection(cm.display.input.prepareSelection());
  1954. }
  1955. function prepareSelection(cm, primary) {
  1956. var doc = cm.doc, result = {};
  1957. var curFragment = result.cursors = document.createDocumentFragment();
  1958. var selFragment = result.selection = document.createDocumentFragment();
  1959. for (var i = 0; i < doc.sel.ranges.length; i++) {
  1960. if (primary === false && i == doc.sel.primIndex) continue;
  1961. var range = doc.sel.ranges[i];
  1962. var collapsed = range.empty();
  1963. if (collapsed || cm.options.showCursorWhenSelecting)
  1964. drawSelectionCursor(cm, range, curFragment);
  1965. if (!collapsed)
  1966. drawSelectionRange(cm, range, selFragment);
  1967. }
  1968. return result;
  1969. }
  1970. // Draws a cursor for the given range
  1971. function drawSelectionCursor(cm, range, output) {
  1972. var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  1973. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  1974. cursor.style.left = pos.left + "px";
  1975. cursor.style.top = pos.top + "px";
  1976. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  1977. if (pos.other) {
  1978. // Secondary cursor, shown when on a 'jump' in bi-directional text
  1979. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  1980. otherCursor.style.display = "";
  1981. otherCursor.style.left = pos.other.left + "px";
  1982. otherCursor.style.top = pos.other.top + "px";
  1983. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  1984. }
  1985. }
  1986. // Draws the given range as a highlighted selection
  1987. function drawSelectionRange(cm, range, output) {
  1988. var display = cm.display, doc = cm.doc;
  1989. var fragment = document.createDocumentFragment();
  1990. var padding = paddingH(cm.display), leftSide = padding.left;
  1991. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  1992. function add(left, top, width, bottom) {
  1993. if (top < 0) top = 0;
  1994. top = Math.round(top);
  1995. bottom = Math.round(bottom);
  1996. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  1997. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  1998. "px; height: " + (bottom - top) + "px"));
  1999. }
  2000. function drawForLine(line, fromArg, toArg) {
  2001. var lineObj = getLine(doc, line);
  2002. var lineLen = lineObj.text.length;
  2003. var start, end;
  2004. function coords(ch, bias) {
  2005. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2006. }
  2007. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2008. var leftPos = coords(from, "left"), rightPos, left, right;
  2009. if (from == to) {
  2010. rightPos = leftPos;
  2011. left = right = leftPos.left;
  2012. } else {
  2013. rightPos = coords(to - 1, "right");
  2014. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2015. left = leftPos.left;
  2016. right = rightPos.right;
  2017. }
  2018. if (fromArg == null && from == 0) left = leftSide;
  2019. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2020. add(left, leftPos.top, null, leftPos.bottom);
  2021. left = leftSide;
  2022. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2023. }
  2024. if (toArg == null && to == lineLen) right = rightSide;
  2025. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2026. start = leftPos;
  2027. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2028. end = rightPos;
  2029. if (left < leftSide + 1) left = leftSide;
  2030. add(left, rightPos.top, right - left, rightPos.bottom);
  2031. });
  2032. return {start: start, end: end};
  2033. }
  2034. var sFrom = range.from(), sTo = range.to();
  2035. if (sFrom.line == sTo.line) {
  2036. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2037. } else {
  2038. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2039. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2040. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2041. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2042. if (singleVLine) {
  2043. if (leftEnd.top < rightStart.top - 2) {
  2044. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2045. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2046. } else {
  2047. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2048. }
  2049. }
  2050. if (leftEnd.bottom < rightStart.top)
  2051. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2052. }
  2053. output.appendChild(fragment);
  2054. }
  2055. // Cursor-blinking
  2056. function restartBlink(cm) {
  2057. if (!cm.state.focused) return;
  2058. var display = cm.display;
  2059. clearInterval(display.blinker);
  2060. var on = true;
  2061. display.cursorDiv.style.visibility = "";
  2062. if (cm.options.cursorBlinkRate > 0)
  2063. display.blinker = setInterval(function() {
  2064. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2065. }, cm.options.cursorBlinkRate);
  2066. else if (cm.options.cursorBlinkRate < 0)
  2067. display.cursorDiv.style.visibility = "hidden";
  2068. }
  2069. // HIGHLIGHT WORKER
  2070. function startWorker(cm, time) {
  2071. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2072. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2073. }
  2074. function highlightWorker(cm) {
  2075. var doc = cm.doc;
  2076. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2077. if (doc.frontier >= cm.display.viewTo) return;
  2078. var end = +new Date + cm.options.workTime;
  2079. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2080. var changedLines = [];
  2081. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2082. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2083. var oldStyles = line.styles;
  2084. var highlighted = highlightLine(cm, line, state, true);
  2085. line.styles = highlighted.styles;
  2086. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2087. if (newCls) line.styleClasses = newCls;
  2088. else if (oldCls) line.styleClasses = null;
  2089. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2090. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2091. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2092. if (ischange) changedLines.push(doc.frontier);
  2093. line.stateAfter = copyState(doc.mode, state);
  2094. } else {
  2095. processLine(cm, line.text, state);
  2096. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2097. }
  2098. ++doc.frontier;
  2099. if (+new Date > end) {
  2100. startWorker(cm, cm.options.workDelay);
  2101. return true;
  2102. }
  2103. });
  2104. if (changedLines.length) runInOp(cm, function() {
  2105. for (var i = 0; i < changedLines.length; i++)
  2106. regLineChange(cm, changedLines[i], "text");
  2107. });
  2108. }
  2109. // Finds the line to start with when starting a parse. Tries to
  2110. // find a line with a stateAfter, so that it can start with a
  2111. // valid state. If that fails, it returns the line with the
  2112. // smallest indentation, which tends to need the least context to
  2113. // parse correctly.
  2114. function findStartLine(cm, n, precise) {
  2115. var minindent, minline, doc = cm.doc;
  2116. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2117. for (var search = n; search > lim; --search) {
  2118. if (search <= doc.first) return doc.first;
  2119. var line = getLine(doc, search - 1);
  2120. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2121. var indented = countColumn(line.text, null, cm.options.tabSize);
  2122. if (minline == null || minindent > indented) {
  2123. minline = search - 1;
  2124. minindent = indented;
  2125. }
  2126. }
  2127. return minline;
  2128. }
  2129. function getStateBefore(cm, n, precise) {
  2130. var doc = cm.doc, display = cm.display;
  2131. if (!doc.mode.startState) return true;
  2132. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2133. if (!state) state = startState(doc.mode);
  2134. else state = copyState(doc.mode, state);
  2135. doc.iter(pos, n, function(line) {
  2136. processLine(cm, line.text, state);
  2137. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2138. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2139. ++pos;
  2140. });
  2141. if (precise) doc.frontier = pos;
  2142. return state;
  2143. }
  2144. // POSITION MEASUREMENT
  2145. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2146. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2147. function paddingH(display) {
  2148. if (display.cachedPaddingH) return display.cachedPaddingH;
  2149. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2150. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2151. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2152. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2153. return data;
  2154. }
  2155. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2156. function displayWidth(cm) {
  2157. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2158. }
  2159. function displayHeight(cm) {
  2160. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2161. }
  2162. // Ensure the lineView.wrapping.heights array is populated. This is
  2163. // an array of bottom offsets for the lines that make up a drawn
  2164. // line. When lineWrapping is on, there might be more than one
  2165. // height.
  2166. function ensureLineHeights(cm, lineView, rect) {
  2167. var wrapping = cm.options.lineWrapping;
  2168. var curWidth = wrapping && displayWidth(cm);
  2169. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2170. var heights = lineView.measure.heights = [];
  2171. if (wrapping) {
  2172. lineView.measure.width = curWidth;
  2173. var rects = lineView.text.firstChild.getClientRects();
  2174. for (var i = 0; i < rects.length - 1; i++) {
  2175. var cur = rects[i], next = rects[i + 1];
  2176. if (Math.abs(cur.bottom - next.bottom) > 2)
  2177. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2178. }
  2179. }
  2180. heights.push(rect.bottom - rect.top);
  2181. }
  2182. }
  2183. // Find a line map (mapping character offsets to text nodes) and a
  2184. // measurement cache for the given line number. (A line view might
  2185. // contain multiple lines when collapsed ranges are present.)
  2186. function mapFromLineView(lineView, line, lineN) {
  2187. if (lineView.line == line)
  2188. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2189. for (var i = 0; i < lineView.rest.length; i++)
  2190. if (lineView.rest[i] == line)
  2191. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2192. for (var i = 0; i < lineView.rest.length; i++)
  2193. if (lineNo(lineView.rest[i]) > lineN)
  2194. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2195. }
  2196. // Render a line into the hidden node display.externalMeasured. Used
  2197. // when measurement is needed for a line that's not in the viewport.
  2198. function updateExternalMeasurement(cm, line) {
  2199. line = visualLine(line);
  2200. var lineN = lineNo(line);
  2201. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2202. view.lineN = lineN;
  2203. var built = view.built = buildLineContent(cm, view);
  2204. view.text = built.pre;
  2205. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2206. return view;
  2207. }
  2208. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2209. // for a given character.
  2210. function measureChar(cm, line, ch, bias) {
  2211. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2212. }
  2213. // Find a line view that corresponds to the given line number.
  2214. function findViewForLine(cm, lineN) {
  2215. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2216. return cm.display.view[findViewIndex(cm, lineN)];
  2217. var ext = cm.display.externalMeasured;
  2218. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2219. return ext;
  2220. }
  2221. // Measurement can be split in two steps, the set-up work that
  2222. // applies to the whole line, and the measurement of the actual
  2223. // character. Functions like coordsChar, that need to do a lot of
  2224. // measurements in a row, can thus ensure that the set-up work is
  2225. // only done once.
  2226. function prepareMeasureForLine(cm, line) {
  2227. var lineN = lineNo(line);
  2228. var view = findViewForLine(cm, lineN);
  2229. if (view && !view.text)
  2230. view = null;
  2231. else if (view && view.changes)
  2232. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2233. if (!view)
  2234. view = updateExternalMeasurement(cm, line);
  2235. var info = mapFromLineView(view, line, lineN);
  2236. return {
  2237. line: line, view: view, rect: null,
  2238. map: info.map, cache: info.cache, before: info.before,
  2239. hasHeights: false
  2240. };
  2241. }
  2242. // Given a prepared measurement object, measures the position of an
  2243. // actual character (or fetches it from the cache).
  2244. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2245. if (prepared.before) ch = -1;
  2246. var key = ch + (bias || ""), found;
  2247. if (prepared.cache.hasOwnProperty(key)) {
  2248. found = prepared.cache[key];
  2249. } else {
  2250. if (!prepared.rect)
  2251. prepared.rect = prepared.view.text.getBoundingClientRect();
  2252. if (!prepared.hasHeights) {
  2253. ensureLineHeights(cm, prepared.view, prepared.rect);
  2254. prepared.hasHeights = true;
  2255. }
  2256. found = measureCharInner(cm, prepared, ch, bias);
  2257. if (!found.bogus) prepared.cache[key] = found;
  2258. }
  2259. return {left: found.left, right: found.right,
  2260. top: varHeight ? found.rtop : found.top,
  2261. bottom: varHeight ? found.rbottom : found.bottom};
  2262. }
  2263. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2264. function nodeAndOffsetInLineMap(map, ch, bias) {
  2265. var node, start, end, collapse;
  2266. // First, search the line map for the text node corresponding to,
  2267. // or closest to, the target character.
  2268. for (var i = 0; i < map.length; i += 3) {
  2269. var mStart = map[i], mEnd = map[i + 1];
  2270. if (ch < mStart) {
  2271. start = 0; end = 1;
  2272. collapse = "left";
  2273. } else if (ch < mEnd) {
  2274. start = ch - mStart;
  2275. end = start + 1;
  2276. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2277. end = mEnd - mStart;
  2278. start = end - 1;
  2279. if (ch >= mEnd) collapse = "right";
  2280. }
  2281. if (start != null) {
  2282. node = map[i + 2];
  2283. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2284. collapse = bias;
  2285. if (bias == "left" && start == 0)
  2286. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2287. node = map[(i -= 3) + 2];
  2288. collapse = "left";
  2289. }
  2290. if (bias == "right" && start == mEnd - mStart)
  2291. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2292. node = map[(i += 3) + 2];
  2293. collapse = "right";
  2294. }
  2295. break;
  2296. }
  2297. }
  2298. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2299. }
  2300. function measureCharInner(cm, prepared, ch, bias) {
  2301. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2302. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2303. var rect;
  2304. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2305. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2306. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2307. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2308. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2309. rect = node.parentNode.getBoundingClientRect();
  2310. } else if (ie && cm.options.lineWrapping) {
  2311. var rects = range(node, start, end).getClientRects();
  2312. if (rects.length)
  2313. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2314. else
  2315. rect = nullRect;
  2316. } else {
  2317. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2318. }
  2319. if (rect.left || rect.right || start == 0) break;
  2320. end = start;
  2321. start = start - 1;
  2322. collapse = "right";
  2323. }
  2324. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2325. } else { // If it is a widget, simply get the box for the whole widget.
  2326. if (start > 0) collapse = bias = "right";
  2327. var rects;
  2328. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2329. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2330. else
  2331. rect = node.getBoundingClientRect();
  2332. }
  2333. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2334. var rSpan = node.parentNode.getClientRects()[0];
  2335. if (rSpan)
  2336. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2337. else
  2338. rect = nullRect;
  2339. }
  2340. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2341. var mid = (rtop + rbot) / 2;
  2342. var heights = prepared.view.measure.heights;
  2343. for (var i = 0; i < heights.length - 1; i++)
  2344. if (mid < heights[i]) break;
  2345. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2346. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2347. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2348. top: top, bottom: bot};
  2349. if (!rect.left && !rect.right) result.bogus = true;
  2350. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2351. return result;
  2352. }
  2353. // Work around problem with bounding client rects on ranges being
  2354. // returned incorrectly when zoomed on IE10 and below.
  2355. function maybeUpdateRectForZooming(measure, rect) {
  2356. if (!window.screen || screen.logicalXDPI == null ||
  2357. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2358. return rect;
  2359. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2360. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2361. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2362. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2363. }
  2364. function clearLineMeasurementCacheFor(lineView) {
  2365. if (lineView.measure) {
  2366. lineView.measure.cache = {};
  2367. lineView.measure.heights = null;
  2368. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2369. lineView.measure.caches[i] = {};
  2370. }
  2371. }
  2372. function clearLineMeasurementCache(cm) {
  2373. cm.display.externalMeasure = null;
  2374. removeChildren(cm.display.lineMeasure);
  2375. for (var i = 0; i < cm.display.view.length; i++)
  2376. clearLineMeasurementCacheFor(cm.display.view[i]);
  2377. }
  2378. function clearCaches(cm) {
  2379. clearLineMeasurementCache(cm);
  2380. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2381. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2382. cm.display.lineNumChars = null;
  2383. }
  2384. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2385. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2386. // Converts a {top, bottom, left, right} box from line-local
  2387. // coordinates into another coordinate system. Context may be one of
  2388. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2389. // or "page".
  2390. function intoCoordSystem(cm, lineObj, rect, context) {
  2391. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2392. var size = widgetHeight(lineObj.widgets[i]);
  2393. rect.top += size; rect.bottom += size;
  2394. }
  2395. if (context == "line") return rect;
  2396. if (!context) context = "local";
  2397. var yOff = heightAtLine(lineObj);
  2398. if (context == "local") yOff += paddingTop(cm.display);
  2399. else yOff -= cm.display.viewOffset;
  2400. if (context == "page" || context == "window") {
  2401. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2402. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2403. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2404. rect.left += xOff; rect.right += xOff;
  2405. }
  2406. rect.top += yOff; rect.bottom += yOff;
  2407. return rect;
  2408. }
  2409. // Coverts a box from "div" coords to another coordinate system.
  2410. // Context may be "window", "page", "div", or "local"/null.
  2411. function fromCoordSystem(cm, coords, context) {
  2412. if (context == "div") return coords;
  2413. var left = coords.left, top = coords.top;
  2414. // First move into "page" coordinate system
  2415. if (context == "page") {
  2416. left -= pageScrollX();
  2417. top -= pageScrollY();
  2418. } else if (context == "local" || !context) {
  2419. var localBox = cm.display.sizer.getBoundingClientRect();
  2420. left += localBox.left;
  2421. top += localBox.top;
  2422. }
  2423. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2424. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2425. }
  2426. function charCoords(cm, pos, context, lineObj, bias) {
  2427. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2428. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2429. }
  2430. // Returns a box for a given cursor position, which may have an
  2431. // 'other' property containing the position of the secondary cursor
  2432. // on a bidi boundary.
  2433. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2434. lineObj = lineObj || getLine(cm.doc, pos.line);
  2435. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2436. function get(ch, right) {
  2437. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2438. if (right) m.left = m.right; else m.right = m.left;
  2439. return intoCoordSystem(cm, lineObj, m, context);
  2440. }
  2441. function getBidi(ch, partPos) {
  2442. var part = order[partPos], right = part.level % 2;
  2443. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2444. part = order[--partPos];
  2445. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2446. right = true;
  2447. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2448. part = order[++partPos];
  2449. ch = bidiLeft(part) - part.level % 2;
  2450. right = false;
  2451. }
  2452. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2453. return get(ch, right);
  2454. }
  2455. var order = getOrder(lineObj), ch = pos.ch;
  2456. if (!order) return get(ch);
  2457. var partPos = getBidiPartAt(order, ch);
  2458. var val = getBidi(ch, partPos);
  2459. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2460. return val;
  2461. }
  2462. // Used to cheaply estimate the coordinates for a position. Used for
  2463. // intermediate scroll updates.
  2464. function estimateCoords(cm, pos) {
  2465. var left = 0, pos = clipPos(cm.doc, pos);
  2466. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2467. var lineObj = getLine(cm.doc, pos.line);
  2468. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2469. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2470. }
  2471. // Positions returned by coordsChar contain some extra information.
  2472. // xRel is the relative x position of the input coordinates compared
  2473. // to the found position (so xRel > 0 means the coordinates are to
  2474. // the right of the character position, for example). When outside
  2475. // is true, that means the coordinates lie outside the line's
  2476. // vertical range.
  2477. function PosWithInfo(line, ch, outside, xRel) {
  2478. var pos = Pos(line, ch);
  2479. pos.xRel = xRel;
  2480. if (outside) pos.outside = true;
  2481. return pos;
  2482. }
  2483. // Compute the character position closest to the given coordinates.
  2484. // Input must be lineSpace-local ("div" coordinate system).
  2485. function coordsChar(cm, x, y) {
  2486. var doc = cm.doc;
  2487. y += cm.display.viewOffset;
  2488. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2489. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2490. if (lineN > last)
  2491. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2492. if (x < 0) x = 0;
  2493. var lineObj = getLine(doc, lineN);
  2494. for (;;) {
  2495. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2496. var merged = collapsedSpanAtEnd(lineObj);
  2497. var mergedPos = merged && merged.find(0, true);
  2498. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2499. lineN = lineNo(lineObj = mergedPos.to.line);
  2500. else
  2501. return found;
  2502. }
  2503. }
  2504. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2505. var innerOff = y - heightAtLine(lineObj);
  2506. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2507. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2508. function getX(ch) {
  2509. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2510. wrongLine = true;
  2511. if (innerOff > sp.bottom) return sp.left - adjust;
  2512. else if (innerOff < sp.top) return sp.left + adjust;
  2513. else wrongLine = false;
  2514. return sp.left;
  2515. }
  2516. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2517. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2518. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2519. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2520. // Do a binary search between these bounds.
  2521. for (;;) {
  2522. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2523. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2524. var xDiff = x - (ch == from ? fromX : toX);
  2525. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2526. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2527. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2528. return pos;
  2529. }
  2530. var step = Math.ceil(dist / 2), middle = from + step;
  2531. if (bidi) {
  2532. middle = from;
  2533. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2534. }
  2535. var middleX = getX(middle);
  2536. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2537. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2538. }
  2539. }
  2540. var measureText;
  2541. // Compute the default text height.
  2542. function textHeight(display) {
  2543. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2544. if (measureText == null) {
  2545. measureText = elt("pre");
  2546. // Measure a bunch of lines, for browsers that compute
  2547. // fractional heights.
  2548. for (var i = 0; i < 49; ++i) {
  2549. measureText.appendChild(document.createTextNode("x"));
  2550. measureText.appendChild(elt("br"));
  2551. }
  2552. measureText.appendChild(document.createTextNode("x"));
  2553. }
  2554. removeChildrenAndAdd(display.measure, measureText);
  2555. var height = measureText.offsetHeight / 50;
  2556. if (height > 3) display.cachedTextHeight = height;
  2557. removeChildren(display.measure);
  2558. return height || 1;
  2559. }
  2560. // Compute the default character width.
  2561. function charWidth(display) {
  2562. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2563. var anchor = elt("span", "xxxxxxxxxx");
  2564. var pre = elt("pre", [anchor]);
  2565. removeChildrenAndAdd(display.measure, pre);
  2566. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2567. if (width > 2) display.cachedCharWidth = width;
  2568. return width || 10;
  2569. }
  2570. // OPERATIONS
  2571. // Operations are used to wrap a series of changes to the editor
  2572. // state in such a way that each change won't have to update the
  2573. // cursor and display (which would be awkward, slow, and
  2574. // error-prone). Instead, display updates are batched and then all
  2575. // combined and executed at once.
  2576. var operationGroup = null;
  2577. var nextOpId = 0;
  2578. // Start a new operation.
  2579. function startOperation(cm) {
  2580. cm.curOp = {
  2581. cm: cm,
  2582. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2583. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2584. forceUpdate: false, // Used to force a redraw
  2585. updateInput: null, // Whether to reset the input textarea
  2586. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2587. changeObjs: null, // Accumulated changes, for firing change events
  2588. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2589. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2590. selectionChanged: false, // Whether the selection needs to be redrawn
  2591. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2592. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2593. scrollToPos: null, // Used to scroll to a specific position
  2594. id: ++nextOpId // Unique ID
  2595. };
  2596. if (operationGroup) {
  2597. operationGroup.ops.push(cm.curOp);
  2598. } else {
  2599. cm.curOp.ownsGroup = operationGroup = {
  2600. ops: [cm.curOp],
  2601. delayedCallbacks: []
  2602. };
  2603. }
  2604. }
  2605. function fireCallbacksForOps(group) {
  2606. // Calls delayed callbacks and cursorActivity handlers until no
  2607. // new ones appear
  2608. var callbacks = group.delayedCallbacks, i = 0;
  2609. do {
  2610. for (; i < callbacks.length; i++)
  2611. callbacks[i]();
  2612. for (var j = 0; j < group.ops.length; j++) {
  2613. var op = group.ops[j];
  2614. if (op.cursorActivityHandlers)
  2615. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2616. op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);
  2617. }
  2618. } while (i < callbacks.length);
  2619. }
  2620. // Finish an operation, updating the display and signalling delayed events
  2621. function endOperation(cm) {
  2622. var op = cm.curOp, group = op.ownsGroup;
  2623. if (!group) return;
  2624. try { fireCallbacksForOps(group); }
  2625. finally {
  2626. operationGroup = null;
  2627. for (var i = 0; i < group.ops.length; i++)
  2628. group.ops[i].cm.curOp = null;
  2629. endOperations(group);
  2630. }
  2631. }
  2632. // The DOM updates done when an operation finishes are batched so
  2633. // that the minimum number of relayouts are required.
  2634. function endOperations(group) {
  2635. var ops = group.ops;
  2636. for (var i = 0; i < ops.length; i++) // Read DOM
  2637. endOperation_R1(ops[i]);
  2638. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2639. endOperation_W1(ops[i]);
  2640. for (var i = 0; i < ops.length; i++) // Read DOM
  2641. endOperation_R2(ops[i]);
  2642. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2643. endOperation_W2(ops[i]);
  2644. for (var i = 0; i < ops.length; i++) // Read DOM
  2645. endOperation_finish(ops[i]);
  2646. }
  2647. function endOperation_R1(op) {
  2648. var cm = op.cm, display = cm.display;
  2649. maybeClipScrollbars(cm);
  2650. if (op.updateMaxLine) findMaxLine(cm);
  2651. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2652. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2653. op.scrollToPos.to.line >= display.viewTo) ||
  2654. display.maxLineChanged && cm.options.lineWrapping;
  2655. op.update = op.mustUpdate &&
  2656. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2657. }
  2658. function endOperation_W1(op) {
  2659. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2660. }
  2661. function endOperation_R2(op) {
  2662. var cm = op.cm, display = cm.display;
  2663. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2664. op.barMeasure = measureForScrollbars(cm);
  2665. // If the max line changed since it was last measured, measure it,
  2666. // and ensure the document's width matches it.
  2667. // updateDisplay_W2 will use these properties to do the actual resizing
  2668. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2669. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2670. cm.display.sizerWidth = op.adjustWidthTo;
  2671. op.barMeasure.scrollWidth =
  2672. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2673. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2674. }
  2675. if (op.updatedDisplay || op.selectionChanged)
  2676. op.preparedSelection = display.input.prepareSelection();
  2677. }
  2678. function endOperation_W2(op) {
  2679. var cm = op.cm;
  2680. if (op.adjustWidthTo != null) {
  2681. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2682. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2683. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2684. cm.display.maxLineChanged = false;
  2685. }
  2686. if (op.preparedSelection)
  2687. cm.display.input.showSelection(op.preparedSelection);
  2688. if (op.updatedDisplay)
  2689. setDocumentHeight(cm, op.barMeasure);
  2690. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2691. updateScrollbars(cm, op.barMeasure);
  2692. if (op.selectionChanged) restartBlink(cm);
  2693. if (cm.state.focused && op.updateInput)
  2694. cm.display.input.reset(op.typing);
  2695. }
  2696. function endOperation_finish(op) {
  2697. var cm = op.cm, display = cm.display, doc = cm.doc;
  2698. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2699. // Abort mouse wheel delta measurement, when scrolling explicitly
  2700. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2701. display.wheelStartX = display.wheelStartY = null;
  2702. // Propagate the scroll position to the actual DOM scroller
  2703. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2704. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2705. display.scrollbars.setScrollTop(doc.scrollTop);
  2706. display.scroller.scrollTop = doc.scrollTop;
  2707. }
  2708. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2709. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
  2710. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2711. display.scroller.scrollLeft = doc.scrollLeft;
  2712. alignHorizontally(cm);
  2713. }
  2714. // If we need to scroll a specific position into view, do so.
  2715. if (op.scrollToPos) {
  2716. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2717. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2718. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2719. }
  2720. // Fire events for markers that are hidden/unidden by editing or
  2721. // undoing
  2722. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2723. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2724. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2725. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2726. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2727. if (display.wrapper.offsetHeight)
  2728. doc.scrollTop = cm.display.scroller.scrollTop;
  2729. // Fire change events, and delayed event handlers
  2730. if (op.changeObjs)
  2731. signal(cm, "changes", cm, op.changeObjs);
  2732. if (op.update)
  2733. op.update.finish();
  2734. }
  2735. // Run the given function in an operation
  2736. function runInOp(cm, f) {
  2737. if (cm.curOp) return f();
  2738. startOperation(cm);
  2739. try { return f(); }
  2740. finally { endOperation(cm); }
  2741. }
  2742. // Wraps a function in an operation. Returns the wrapped function.
  2743. function operation(cm, f) {
  2744. return function() {
  2745. if (cm.curOp) return f.apply(cm, arguments);
  2746. startOperation(cm);
  2747. try { return f.apply(cm, arguments); }
  2748. finally { endOperation(cm); }
  2749. };
  2750. }
  2751. // Used to add methods to editor and doc instances, wrapping them in
  2752. // operations.
  2753. function methodOp(f) {
  2754. return function() {
  2755. if (this.curOp) return f.apply(this, arguments);
  2756. startOperation(this);
  2757. try { return f.apply(this, arguments); }
  2758. finally { endOperation(this); }
  2759. };
  2760. }
  2761. function docMethodOp(f) {
  2762. return function() {
  2763. var cm = this.cm;
  2764. if (!cm || cm.curOp) return f.apply(this, arguments);
  2765. startOperation(cm);
  2766. try { return f.apply(this, arguments); }
  2767. finally { endOperation(cm); }
  2768. };
  2769. }
  2770. // VIEW TRACKING
  2771. // These objects are used to represent the visible (currently drawn)
  2772. // part of the document. A LineView may correspond to multiple
  2773. // logical lines, if those are connected by collapsed ranges.
  2774. function LineView(doc, line, lineN) {
  2775. // The starting line
  2776. this.line = line;
  2777. // Continuing lines, if any
  2778. this.rest = visualLineContinued(line);
  2779. // Number of logical lines in this visual line
  2780. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2781. this.node = this.text = null;
  2782. this.hidden = lineIsHidden(doc, line);
  2783. }
  2784. // Create a range of LineView objects for the given lines.
  2785. function buildViewArray(cm, from, to) {
  2786. var array = [], nextPos;
  2787. for (var pos = from; pos < to; pos = nextPos) {
  2788. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2789. nextPos = pos + view.size;
  2790. array.push(view);
  2791. }
  2792. return array;
  2793. }
  2794. // Updates the display.view data structure for a given change to the
  2795. // document. From and to are in pre-change coordinates. Lendiff is
  2796. // the amount of lines added or subtracted by the change. This is
  2797. // used for changes that span multiple lines, or change the way
  2798. // lines are divided into visual lines. regLineChange (below)
  2799. // registers single-line changes.
  2800. function regChange(cm, from, to, lendiff) {
  2801. if (from == null) from = cm.doc.first;
  2802. if (to == null) to = cm.doc.first + cm.doc.size;
  2803. if (!lendiff) lendiff = 0;
  2804. var display = cm.display;
  2805. if (lendiff && to < display.viewTo &&
  2806. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2807. display.updateLineNumbers = from;
  2808. cm.curOp.viewChanged = true;
  2809. if (from >= display.viewTo) { // Change after
  2810. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2811. resetView(cm);
  2812. } else if (to <= display.viewFrom) { // Change before
  2813. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2814. resetView(cm);
  2815. } else {
  2816. display.viewFrom += lendiff;
  2817. display.viewTo += lendiff;
  2818. }
  2819. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2820. resetView(cm);
  2821. } else if (from <= display.viewFrom) { // Top overlap
  2822. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2823. if (cut) {
  2824. display.view = display.view.slice(cut.index);
  2825. display.viewFrom = cut.lineN;
  2826. display.viewTo += lendiff;
  2827. } else {
  2828. resetView(cm);
  2829. }
  2830. } else if (to >= display.viewTo) { // Bottom overlap
  2831. var cut = viewCuttingPoint(cm, from, from, -1);
  2832. if (cut) {
  2833. display.view = display.view.slice(0, cut.index);
  2834. display.viewTo = cut.lineN;
  2835. } else {
  2836. resetView(cm);
  2837. }
  2838. } else { // Gap in the middle
  2839. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2840. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2841. if (cutTop && cutBot) {
  2842. display.view = display.view.slice(0, cutTop.index)
  2843. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2844. .concat(display.view.slice(cutBot.index));
  2845. display.viewTo += lendiff;
  2846. } else {
  2847. resetView(cm);
  2848. }
  2849. }
  2850. var ext = display.externalMeasured;
  2851. if (ext) {
  2852. if (to < ext.lineN)
  2853. ext.lineN += lendiff;
  2854. else if (from < ext.lineN + ext.size)
  2855. display.externalMeasured = null;
  2856. }
  2857. }
  2858. // Register a change to a single line. Type must be one of "text",
  2859. // "gutter", "class", "widget"
  2860. function regLineChange(cm, line, type) {
  2861. cm.curOp.viewChanged = true;
  2862. var display = cm.display, ext = cm.display.externalMeasured;
  2863. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2864. display.externalMeasured = null;
  2865. if (line < display.viewFrom || line >= display.viewTo) return;
  2866. var lineView = display.view[findViewIndex(cm, line)];
  2867. if (lineView.node == null) return;
  2868. var arr = lineView.changes || (lineView.changes = []);
  2869. if (indexOf(arr, type) == -1) arr.push(type);
  2870. }
  2871. // Clear the view.
  2872. function resetView(cm) {
  2873. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2874. cm.display.view = [];
  2875. cm.display.viewOffset = 0;
  2876. }
  2877. // Find the view element corresponding to a given line. Return null
  2878. // when the line isn't visible.
  2879. function findViewIndex(cm, n) {
  2880. if (n >= cm.display.viewTo) return null;
  2881. n -= cm.display.viewFrom;
  2882. if (n < 0) return null;
  2883. var view = cm.display.view;
  2884. for (var i = 0; i < view.length; i++) {
  2885. n -= view[i].size;
  2886. if (n < 0) return i;
  2887. }
  2888. }
  2889. function viewCuttingPoint(cm, oldN, newN, dir) {
  2890. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2891. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2892. return {index: index, lineN: newN};
  2893. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2894. n += view[i].size;
  2895. if (n != oldN) {
  2896. if (dir > 0) {
  2897. if (index == view.length - 1) return null;
  2898. diff = (n + view[index].size) - oldN;
  2899. index++;
  2900. } else {
  2901. diff = n - oldN;
  2902. }
  2903. oldN += diff; newN += diff;
  2904. }
  2905. while (visualLineNo(cm.doc, newN) != newN) {
  2906. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  2907. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2908. index += dir;
  2909. }
  2910. return {index: index, lineN: newN};
  2911. }
  2912. // Force the view to cover a given range, adding empty view element
  2913. // or clipping off existing ones as needed.
  2914. function adjustView(cm, from, to) {
  2915. var display = cm.display, view = display.view;
  2916. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2917. display.view = buildViewArray(cm, from, to);
  2918. display.viewFrom = from;
  2919. } else {
  2920. if (display.viewFrom > from)
  2921. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  2922. else if (display.viewFrom < from)
  2923. display.view = display.view.slice(findViewIndex(cm, from));
  2924. display.viewFrom = from;
  2925. if (display.viewTo < to)
  2926. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  2927. else if (display.viewTo > to)
  2928. display.view = display.view.slice(0, findViewIndex(cm, to));
  2929. }
  2930. display.viewTo = to;
  2931. }
  2932. // Count the number of lines in the view whose DOM representation is
  2933. // out of date (or nonexistent).
  2934. function countDirtyView(cm) {
  2935. var view = cm.display.view, dirty = 0;
  2936. for (var i = 0; i < view.length; i++) {
  2937. var lineView = view[i];
  2938. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  2939. }
  2940. return dirty;
  2941. }
  2942. // EVENT HANDLERS
  2943. // Attach the necessary event handlers when initializing the editor
  2944. function registerEventHandlers(cm) {
  2945. var d = cm.display;
  2946. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  2947. // Older IE's will not fire a second mousedown for a double click
  2948. if (ie && ie_version < 11)
  2949. on(d.scroller, "dblclick", operation(cm, function(e) {
  2950. if (signalDOMEvent(cm, e)) return;
  2951. var pos = posFromMouse(cm, e);
  2952. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  2953. e_preventDefault(e);
  2954. var word = cm.findWordAt(pos);
  2955. extendSelection(cm.doc, word.anchor, word.head);
  2956. }));
  2957. else
  2958. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  2959. // Some browsers fire contextmenu *after* opening the menu, at
  2960. // which point we can't mess with it anymore. Context menu is
  2961. // handled in onMouseDown for these browsers.
  2962. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  2963. // Used to suppress mouse event handling when a touch happens
  2964. var touchFinished, prevTouch = {end: 0};
  2965. function finishTouch() {
  2966. if (d.activeTouch) {
  2967. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  2968. prevTouch = d.activeTouch;
  2969. prevTouch.end = +new Date;
  2970. }
  2971. };
  2972. function isMouseLikeTouchEvent(e) {
  2973. if (e.touches.length != 1) return false;
  2974. var touch = e.touches[0];
  2975. return touch.radiusX <= 1 && touch.radiusY <= 1;
  2976. }
  2977. function farAway(touch, other) {
  2978. if (other.left == null) return true;
  2979. var dx = other.left - touch.left, dy = other.top - touch.top;
  2980. return dx * dx + dy * dy > 20 * 20;
  2981. }
  2982. on(d.scroller, "touchstart", function(e) {
  2983. if (!isMouseLikeTouchEvent(e)) {
  2984. clearTimeout(touchFinished);
  2985. var now = +new Date;
  2986. d.activeTouch = {start: now, moved: false,
  2987. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  2988. if (e.touches.length == 1) {
  2989. d.activeTouch.left = e.touches[0].pageX;
  2990. d.activeTouch.top = e.touches[0].pageY;
  2991. }
  2992. }
  2993. });
  2994. on(d.scroller, "touchmove", function() {
  2995. if (d.activeTouch) d.activeTouch.moved = true;
  2996. });
  2997. on(d.scroller, "touchend", function(e) {
  2998. var touch = d.activeTouch;
  2999. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3000. !touch.moved && new Date - touch.start < 300) {
  3001. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3002. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3003. range = new Range(pos, pos);
  3004. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3005. range = cm.findWordAt(pos);
  3006. else // Triple tap
  3007. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3008. cm.setSelection(range.anchor, range.head);
  3009. cm.focus();
  3010. e_preventDefault(e);
  3011. }
  3012. finishTouch();
  3013. });
  3014. on(d.scroller, "touchcancel", finishTouch);
  3015. // Sync scrolling between fake scrollbars and real scrollable
  3016. // area, ensure viewport is updated when scrolling.
  3017. on(d.scroller, "scroll", function() {
  3018. if (d.scroller.clientHeight) {
  3019. setScrollTop(cm, d.scroller.scrollTop);
  3020. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3021. signal(cm, "scroll", cm);
  3022. }
  3023. });
  3024. // Listen to wheel events in order to try and update the viewport on time.
  3025. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3026. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3027. // Prevent wrapper from ever scrolling
  3028. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3029. function drag_(e) {
  3030. if (!signalDOMEvent(cm, e)) e_stop(e);
  3031. }
  3032. if (cm.options.dragDrop) {
  3033. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  3034. on(d.scroller, "dragenter", drag_);
  3035. on(d.scroller, "dragover", drag_);
  3036. on(d.scroller, "drop", operation(cm, onDrop));
  3037. }
  3038. var inp = d.input.getField();
  3039. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3040. on(inp, "keydown", operation(cm, onKeyDown));
  3041. on(inp, "keypress", operation(cm, onKeyPress));
  3042. on(inp, "focus", bind(onFocus, cm));
  3043. on(inp, "blur", bind(onBlur, cm));
  3044. }
  3045. // Called when the window resizes
  3046. function onResize(cm) {
  3047. var d = cm.display;
  3048. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3049. return;
  3050. // Might be a text scaling operation, clear size caches.
  3051. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3052. d.scrollbarsClipped = false;
  3053. cm.setSize();
  3054. }
  3055. // MOUSE EVENTS
  3056. // Return true when the given mouse event happened in a widget
  3057. function eventInWidget(display, e) {
  3058. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3059. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3060. (n.parentNode == display.sizer && n != display.mover))
  3061. return true;
  3062. }
  3063. }
  3064. // Given a mouse event, find the corresponding position. If liberal
  3065. // is false, it checks whether a gutter or scrollbar was clicked,
  3066. // and returns null if it was. forRect is used by rectangular
  3067. // selections, and tries to estimate a character position even for
  3068. // coordinates beyond the right of the text.
  3069. function posFromMouse(cm, e, liberal, forRect) {
  3070. var display = cm.display;
  3071. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3072. var x, y, space = display.lineSpace.getBoundingClientRect();
  3073. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3074. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3075. catch (e) { return null; }
  3076. var coords = coordsChar(cm, x, y), line;
  3077. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3078. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3079. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3080. }
  3081. return coords;
  3082. }
  3083. // A mouse down can be a single click, double click, triple click,
  3084. // start of selection drag, start of text drag, new cursor
  3085. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3086. // middle-click-paste. Or it might be a click on something we should
  3087. // not interfere with, such as a scrollbar or widget.
  3088. function onMouseDown(e) {
  3089. var cm = this, display = cm.display;
  3090. if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
  3091. display.shift = e.shiftKey;
  3092. if (eventInWidget(display, e)) {
  3093. if (!webkit) {
  3094. // Briefly turn off draggability, to allow widgets to do
  3095. // normal dragging things.
  3096. display.scroller.draggable = false;
  3097. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3098. }
  3099. return;
  3100. }
  3101. if (clickInGutter(cm, e)) return;
  3102. var start = posFromMouse(cm, e);
  3103. window.focus();
  3104. switch (e_button(e)) {
  3105. case 1:
  3106. if (start)
  3107. leftButtonDown(cm, e, start);
  3108. else if (e_target(e) == display.scroller)
  3109. e_preventDefault(e);
  3110. break;
  3111. case 2:
  3112. if (webkit) cm.state.lastMiddleDown = +new Date;
  3113. if (start) extendSelection(cm.doc, start);
  3114. setTimeout(function() {display.input.focus();}, 20);
  3115. e_preventDefault(e);
  3116. break;
  3117. case 3:
  3118. if (captureRightClick) onContextMenu(cm, e);
  3119. break;
  3120. }
  3121. }
  3122. var lastClick, lastDoubleClick;
  3123. function leftButtonDown(cm, e, start) {
  3124. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3125. else ensureFocus(cm);
  3126. var now = +new Date, type;
  3127. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3128. type = "triple";
  3129. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3130. type = "double";
  3131. lastDoubleClick = {time: now, pos: start};
  3132. } else {
  3133. type = "single";
  3134. lastClick = {time: now, pos: start};
  3135. }
  3136. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3137. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
  3138. type == "single" && (contained = sel.contains(start)) > -1 &&
  3139. !sel.ranges[contained].empty())
  3140. leftButtonStartDrag(cm, e, start, modifier);
  3141. else
  3142. leftButtonSelect(cm, e, start, type, modifier);
  3143. }
  3144. // Start a text drag. When it ends, see if any dragging actually
  3145. // happen, and treat as a click if it didn't.
  3146. function leftButtonStartDrag(cm, e, start, modifier) {
  3147. var display = cm.display;
  3148. var dragEnd = operation(cm, function(e2) {
  3149. if (webkit) display.scroller.draggable = false;
  3150. cm.state.draggingText = false;
  3151. off(document, "mouseup", dragEnd);
  3152. off(display.scroller, "drop", dragEnd);
  3153. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3154. e_preventDefault(e2);
  3155. if (!modifier)
  3156. extendSelection(cm.doc, start);
  3157. display.input.focus();
  3158. // Work around unexplainable focus problem in IE9 (#2127)
  3159. if (ie && ie_version == 9)
  3160. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3161. }
  3162. });
  3163. // Let the drag handler handle this.
  3164. if (webkit) display.scroller.draggable = true;
  3165. cm.state.draggingText = dragEnd;
  3166. // IE's approach to draggable
  3167. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3168. on(document, "mouseup", dragEnd);
  3169. on(display.scroller, "drop", dragEnd);
  3170. }
  3171. // Normal selection, as opposed to text dragging.
  3172. function leftButtonSelect(cm, e, start, type, addNew) {
  3173. var display = cm.display, doc = cm.doc;
  3174. e_preventDefault(e);
  3175. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3176. if (addNew && !e.shiftKey) {
  3177. ourIndex = doc.sel.contains(start);
  3178. if (ourIndex > -1)
  3179. ourRange = ranges[ourIndex];
  3180. else
  3181. ourRange = new Range(start, start);
  3182. } else {
  3183. ourRange = doc.sel.primary();
  3184. }
  3185. if (e.altKey) {
  3186. type = "rect";
  3187. if (!addNew) ourRange = new Range(start, start);
  3188. start = posFromMouse(cm, e, true, true);
  3189. ourIndex = -1;
  3190. } else if (type == "double") {
  3191. var word = cm.findWordAt(start);
  3192. if (cm.display.shift || doc.extend)
  3193. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3194. else
  3195. ourRange = word;
  3196. } else if (type == "triple") {
  3197. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3198. if (cm.display.shift || doc.extend)
  3199. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3200. else
  3201. ourRange = line;
  3202. } else {
  3203. ourRange = extendRange(doc, ourRange, start);
  3204. }
  3205. if (!addNew) {
  3206. ourIndex = 0;
  3207. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3208. startSel = doc.sel;
  3209. } else if (ourIndex == -1) {
  3210. ourIndex = ranges.length;
  3211. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3212. {scroll: false, origin: "*mouse"});
  3213. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single") {
  3214. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
  3215. startSel = doc.sel;
  3216. } else {
  3217. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3218. }
  3219. var lastPos = start;
  3220. function extendTo(pos) {
  3221. if (cmp(lastPos, pos) == 0) return;
  3222. lastPos = pos;
  3223. if (type == "rect") {
  3224. var ranges = [], tabSize = cm.options.tabSize;
  3225. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3226. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3227. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3228. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3229. line <= end; line++) {
  3230. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3231. if (left == right)
  3232. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3233. else if (text.length > leftPos)
  3234. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3235. }
  3236. if (!ranges.length) ranges.push(new Range(start, start));
  3237. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3238. {origin: "*mouse", scroll: false});
  3239. cm.scrollIntoView(pos);
  3240. } else {
  3241. var oldRange = ourRange;
  3242. var anchor = oldRange.anchor, head = pos;
  3243. if (type != "single") {
  3244. if (type == "double")
  3245. var range = cm.findWordAt(pos);
  3246. else
  3247. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3248. if (cmp(range.anchor, anchor) > 0) {
  3249. head = range.head;
  3250. anchor = minPos(oldRange.from(), range.anchor);
  3251. } else {
  3252. head = range.anchor;
  3253. anchor = maxPos(oldRange.to(), range.head);
  3254. }
  3255. }
  3256. var ranges = startSel.ranges.slice(0);
  3257. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3258. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3259. }
  3260. }
  3261. var editorSize = display.wrapper.getBoundingClientRect();
  3262. // Used to ensure timeout re-tries don't fire when another extend
  3263. // happened in the meantime (clearTimeout isn't reliable -- at
  3264. // least on Chrome, the timeouts still happen even when cleared,
  3265. // if the clear happens after their scheduled firing time).
  3266. var counter = 0;
  3267. function extend(e) {
  3268. var curCount = ++counter;
  3269. var cur = posFromMouse(cm, e, true, type == "rect");
  3270. if (!cur) return;
  3271. if (cmp(cur, lastPos) != 0) {
  3272. ensureFocus(cm);
  3273. extendTo(cur);
  3274. var visible = visibleLines(display, doc);
  3275. if (cur.line >= visible.to || cur.line < visible.from)
  3276. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3277. } else {
  3278. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3279. if (outside) setTimeout(operation(cm, function() {
  3280. if (counter != curCount) return;
  3281. display.scroller.scrollTop += outside;
  3282. extend(e);
  3283. }), 50);
  3284. }
  3285. }
  3286. function done(e) {
  3287. counter = Infinity;
  3288. e_preventDefault(e);
  3289. display.input.focus();
  3290. off(document, "mousemove", move);
  3291. off(document, "mouseup", up);
  3292. doc.history.lastSelOrigin = null;
  3293. }
  3294. var move = operation(cm, function(e) {
  3295. if (!e_button(e)) done(e);
  3296. else extend(e);
  3297. });
  3298. var up = operation(cm, done);
  3299. on(document, "mousemove", move);
  3300. on(document, "mouseup", up);
  3301. }
  3302. // Determines whether an event happened in the gutter, and fires the
  3303. // handlers for the corresponding event.
  3304. function gutterEvent(cm, e, type, prevent, signalfn) {
  3305. try { var mX = e.clientX, mY = e.clientY; }
  3306. catch(e) { return false; }
  3307. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3308. if (prevent) e_preventDefault(e);
  3309. var display = cm.display;
  3310. var lineBox = display.lineDiv.getBoundingClientRect();
  3311. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3312. mY -= lineBox.top - display.viewOffset;
  3313. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3314. var g = display.gutters.childNodes[i];
  3315. if (g && g.getBoundingClientRect().right >= mX) {
  3316. var line = lineAtHeight(cm.doc, mY);
  3317. var gutter = cm.options.gutters[i];
  3318. signalfn(cm, type, cm, line, gutter, e);
  3319. return e_defaultPrevented(e);
  3320. }
  3321. }
  3322. }
  3323. function clickInGutter(cm, e) {
  3324. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  3325. }
  3326. // Kludge to work around strange IE behavior where it'll sometimes
  3327. // re-fire a series of drag-related events right after the drop (#1551)
  3328. var lastDrop = 0;
  3329. function onDrop(e) {
  3330. var cm = this;
  3331. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3332. return;
  3333. e_preventDefault(e);
  3334. if (ie) lastDrop = +new Date;
  3335. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3336. if (!pos || isReadOnly(cm)) return;
  3337. // Might be a file drop, in which case we simply extract the text
  3338. // and insert it.
  3339. if (files && files.length && window.FileReader && window.File) {
  3340. var n = files.length, text = Array(n), read = 0;
  3341. var loadFile = function(file, i) {
  3342. var reader = new FileReader;
  3343. reader.onload = operation(cm, function() {
  3344. text[i] = reader.result;
  3345. if (++read == n) {
  3346. pos = clipPos(cm.doc, pos);
  3347. var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
  3348. makeChange(cm.doc, change);
  3349. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3350. }
  3351. });
  3352. reader.readAsText(file);
  3353. };
  3354. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3355. } else { // Normal drop
  3356. // Don't do a replace if the drop happened inside of the selected text.
  3357. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3358. cm.state.draggingText(e);
  3359. // Ensure the editor is re-focused
  3360. setTimeout(function() {cm.display.input.focus();}, 20);
  3361. return;
  3362. }
  3363. try {
  3364. var text = e.dataTransfer.getData("Text");
  3365. if (text) {
  3366. if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))
  3367. var selected = cm.listSelections();
  3368. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3369. if (selected) for (var i = 0; i < selected.length; ++i)
  3370. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3371. cm.replaceSelection(text, "around", "paste");
  3372. cm.display.input.focus();
  3373. }
  3374. }
  3375. catch(e){}
  3376. }
  3377. }
  3378. function onDragStart(cm, e) {
  3379. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3380. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3381. e.dataTransfer.setData("Text", cm.getSelection());
  3382. // Use dummy image instead of default browsers image.
  3383. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3384. if (e.dataTransfer.setDragImage && !safari) {
  3385. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3386. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3387. if (presto) {
  3388. img.width = img.height = 1;
  3389. cm.display.wrapper.appendChild(img);
  3390. // Force a relayout, or Opera won't use our image for some obscure reason
  3391. img._top = img.offsetTop;
  3392. }
  3393. e.dataTransfer.setDragImage(img, 0, 0);
  3394. if (presto) img.parentNode.removeChild(img);
  3395. }
  3396. }
  3397. // SCROLL EVENTS
  3398. // Sync the scrollable area and scrollbars, ensure the viewport
  3399. // covers the visible area.
  3400. function setScrollTop(cm, val) {
  3401. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3402. cm.doc.scrollTop = val;
  3403. if (!gecko) updateDisplaySimple(cm, {top: val});
  3404. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3405. cm.display.scrollbars.setScrollTop(val);
  3406. if (gecko) updateDisplaySimple(cm);
  3407. startWorker(cm, 100);
  3408. }
  3409. // Sync scroller and scrollbar, ensure the gutter elements are
  3410. // aligned.
  3411. function setScrollLeft(cm, val, isScroller) {
  3412. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3413. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3414. cm.doc.scrollLeft = val;
  3415. alignHorizontally(cm);
  3416. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3417. cm.display.scrollbars.setScrollLeft(val);
  3418. }
  3419. // Since the delta values reported on mouse wheel events are
  3420. // unstandardized between browsers and even browser versions, and
  3421. // generally horribly unpredictable, this code starts by measuring
  3422. // the scroll effect that the first few mouse wheel events have,
  3423. // and, from that, detects the way it can convert deltas to pixel
  3424. // offsets afterwards.
  3425. //
  3426. // The reason we want to know the amount a wheel event will scroll
  3427. // is that it gives us a chance to update the display before the
  3428. // actual scrolling happens, reducing flickering.
  3429. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3430. // Fill in a browser-detected starting value on browsers where we
  3431. // know one. These don't have to be accurate -- the result of them
  3432. // being wrong would just be a slight flicker on the first wheel
  3433. // scroll (if it is large enough).
  3434. if (ie) wheelPixelsPerUnit = -.53;
  3435. else if (gecko) wheelPixelsPerUnit = 15;
  3436. else if (chrome) wheelPixelsPerUnit = -.7;
  3437. else if (safari) wheelPixelsPerUnit = -1/3;
  3438. var wheelEventDelta = function(e) {
  3439. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3440. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3441. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3442. else if (dy == null) dy = e.wheelDelta;
  3443. return {x: dx, y: dy};
  3444. };
  3445. CodeMirror.wheelEventPixels = function(e) {
  3446. var delta = wheelEventDelta(e);
  3447. delta.x *= wheelPixelsPerUnit;
  3448. delta.y *= wheelPixelsPerUnit;
  3449. return delta;
  3450. };
  3451. function onScrollWheel(cm, e) {
  3452. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3453. var display = cm.display, scroll = display.scroller;
  3454. // Quit if there's nothing to scroll here
  3455. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  3456. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  3457. // Webkit browsers on OS X abort momentum scrolls when the target
  3458. // of the scroll event is removed from the scrollable element.
  3459. // This hack (see related code in patchDisplay) makes sure the
  3460. // element is kept around.
  3461. if (dy && mac && webkit) {
  3462. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3463. for (var i = 0; i < view.length; i++) {
  3464. if (view[i].node == cur) {
  3465. cm.display.currentWheelTarget = cur;
  3466. break outer;
  3467. }
  3468. }
  3469. }
  3470. }
  3471. // On some browsers, horizontal scrolling will cause redraws to
  3472. // happen before the gutter has been realigned, causing it to
  3473. // wriggle around in a most unseemly way. When we have an
  3474. // estimated pixels/delta value, we just handle horizontal
  3475. // scrolling entirely here. It'll be slightly off from native, but
  3476. // better than glitching out.
  3477. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3478. if (dy)
  3479. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3480. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3481. e_preventDefault(e);
  3482. display.wheelStartX = null; // Abort measurement, if in progress
  3483. return;
  3484. }
  3485. // 'Project' the visible viewport to cover the area that is being
  3486. // scrolled into view (if we know enough to estimate it).
  3487. if (dy && wheelPixelsPerUnit != null) {
  3488. var pixels = dy * wheelPixelsPerUnit;
  3489. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3490. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3491. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3492. updateDisplaySimple(cm, {top: top, bottom: bot});
  3493. }
  3494. if (wheelSamples < 20) {
  3495. if (display.wheelStartX == null) {
  3496. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3497. display.wheelDX = dx; display.wheelDY = dy;
  3498. setTimeout(function() {
  3499. if (display.wheelStartX == null) return;
  3500. var movedX = scroll.scrollLeft - display.wheelStartX;
  3501. var movedY = scroll.scrollTop - display.wheelStartY;
  3502. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3503. (movedX && display.wheelDX && movedX / display.wheelDX);
  3504. display.wheelStartX = display.wheelStartY = null;
  3505. if (!sample) return;
  3506. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3507. ++wheelSamples;
  3508. }, 200);
  3509. } else {
  3510. display.wheelDX += dx; display.wheelDY += dy;
  3511. }
  3512. }
  3513. }
  3514. // KEY EVENTS
  3515. // Run a handler that was bound to a key.
  3516. function doHandleBinding(cm, bound, dropShift) {
  3517. if (typeof bound == "string") {
  3518. bound = commands[bound];
  3519. if (!bound) return false;
  3520. }
  3521. // Ensure previous input has been read, so that the handler sees a
  3522. // consistent view of the document
  3523. cm.display.input.ensurePolled();
  3524. var prevShift = cm.display.shift, done = false;
  3525. try {
  3526. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  3527. if (dropShift) cm.display.shift = false;
  3528. done = bound(cm) != Pass;
  3529. } finally {
  3530. cm.display.shift = prevShift;
  3531. cm.state.suppressEdits = false;
  3532. }
  3533. return done;
  3534. }
  3535. function lookupKeyForEditor(cm, name, handle) {
  3536. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3537. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3538. if (result) return result;
  3539. }
  3540. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3541. || lookupKey(name, cm.options.keyMap, handle, cm);
  3542. }
  3543. var stopSeq = new Delayed;
  3544. function dispatchKey(cm, name, e, handle) {
  3545. var seq = cm.state.keySeq;
  3546. if (seq) {
  3547. if (isModifierKey(name)) return "handled";
  3548. stopSeq.set(50, function() {
  3549. if (cm.state.keySeq == seq) {
  3550. cm.state.keySeq = null;
  3551. cm.display.input.reset();
  3552. }
  3553. });
  3554. name = seq + " " + name;
  3555. }
  3556. var result = lookupKeyForEditor(cm, name, handle);
  3557. if (result == "multi")
  3558. cm.state.keySeq = name;
  3559. if (result == "handled")
  3560. signalLater(cm, "keyHandled", cm, name, e);
  3561. if (result == "handled" || result == "multi") {
  3562. e_preventDefault(e);
  3563. restartBlink(cm);
  3564. }
  3565. if (seq && !result && /\'$/.test(name)) {
  3566. e_preventDefault(e);
  3567. return true;
  3568. }
  3569. return !!result;
  3570. }
  3571. // Handle a key from the keydown event.
  3572. function handleKeyBinding(cm, e) {
  3573. var name = keyName(e, true);
  3574. if (!name) return false;
  3575. if (e.shiftKey && !cm.state.keySeq) {
  3576. // First try to resolve full name (including 'Shift-'). Failing
  3577. // that, see if there is a cursor-motion command (starting with
  3578. // 'go') bound to the keyname without 'Shift-'.
  3579. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3580. || dispatchKey(cm, name, e, function(b) {
  3581. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3582. return doHandleBinding(cm, b);
  3583. });
  3584. } else {
  3585. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3586. }
  3587. }
  3588. // Handle a key from the keypress event
  3589. function handleCharBinding(cm, e, ch) {
  3590. return dispatchKey(cm, "'" + ch + "'", e,
  3591. function(b) { return doHandleBinding(cm, b, true); });
  3592. }
  3593. var lastStoppedKey = null;
  3594. function onKeyDown(e) {
  3595. var cm = this;
  3596. ensureFocus(cm);
  3597. if (signalDOMEvent(cm, e)) return;
  3598. // IE does strange things with escape.
  3599. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3600. var code = e.keyCode;
  3601. cm.display.shift = code == 16 || e.shiftKey;
  3602. var handled = handleKeyBinding(cm, e);
  3603. if (presto) {
  3604. lastStoppedKey = handled ? code : null;
  3605. // Opera has no cut event... we try to at least catch the key combo
  3606. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3607. cm.replaceSelection("", null, "cut");
  3608. }
  3609. // Turn mouse into crosshair when Alt is held on Mac.
  3610. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3611. showCrossHair(cm);
  3612. }
  3613. function showCrossHair(cm) {
  3614. var lineDiv = cm.display.lineDiv;
  3615. addClass(lineDiv, "CodeMirror-crosshair");
  3616. function up(e) {
  3617. if (e.keyCode == 18 || !e.altKey) {
  3618. rmClass(lineDiv, "CodeMirror-crosshair");
  3619. off(document, "keyup", up);
  3620. off(document, "mouseover", up);
  3621. }
  3622. }
  3623. on(document, "keyup", up);
  3624. on(document, "mouseover", up);
  3625. }
  3626. function onKeyUp(e) {
  3627. if (e.keyCode == 16) this.doc.sel.shift = false;
  3628. signalDOMEvent(this, e);
  3629. }
  3630. function onKeyPress(e) {
  3631. var cm = this;
  3632. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3633. var keyCode = e.keyCode, charCode = e.charCode;
  3634. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3635. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3636. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3637. if (handleCharBinding(cm, e, ch)) return;
  3638. cm.display.input.onKeyPress(e);
  3639. }
  3640. // FOCUS/BLUR EVENTS
  3641. function onFocus(cm) {
  3642. if (cm.options.readOnly == "nocursor") return;
  3643. if (!cm.state.focused) {
  3644. signal(cm, "focus", cm);
  3645. cm.state.focused = true;
  3646. addClass(cm.display.wrapper, "CodeMirror-focused");
  3647. // This test prevents this from firing when a context
  3648. // menu is closed (since the input reset would kill the
  3649. // select-all detection hack)
  3650. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3651. cm.display.input.reset();
  3652. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3653. }
  3654. cm.display.input.receivedFocus();
  3655. }
  3656. restartBlink(cm);
  3657. }
  3658. function onBlur(cm) {
  3659. if (cm.state.focused) {
  3660. signal(cm, "blur", cm);
  3661. cm.state.focused = false;
  3662. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3663. }
  3664. clearInterval(cm.display.blinker);
  3665. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3666. }
  3667. // CONTEXT MENU HANDLING
  3668. // To make the context menu work, we need to briefly unhide the
  3669. // textarea (making it as unobtrusive as possible) to let the
  3670. // right-click take effect on it.
  3671. function onContextMenu(cm, e) {
  3672. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3673. cm.display.input.onContextMenu(e);
  3674. }
  3675. function contextMenuInGutter(cm, e) {
  3676. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3677. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  3678. }
  3679. // UPDATING
  3680. // Compute the position of the end of a change (its 'to' property
  3681. // refers to the pre-change end).
  3682. var changeEnd = CodeMirror.changeEnd = function(change) {
  3683. if (!change.text) return change.to;
  3684. return Pos(change.from.line + change.text.length - 1,
  3685. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3686. };
  3687. // Adjust a position to refer to the post-change position of the
  3688. // same text, or the end of the change if the change covers it.
  3689. function adjustForChange(pos, change) {
  3690. if (cmp(pos, change.from) < 0) return pos;
  3691. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3692. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3693. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3694. return Pos(line, ch);
  3695. }
  3696. function computeSelAfterChange(doc, change) {
  3697. var out = [];
  3698. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3699. var range = doc.sel.ranges[i];
  3700. out.push(new Range(adjustForChange(range.anchor, change),
  3701. adjustForChange(range.head, change)));
  3702. }
  3703. return normalizeSelection(out, doc.sel.primIndex);
  3704. }
  3705. function offsetPos(pos, old, nw) {
  3706. if (pos.line == old.line)
  3707. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3708. else
  3709. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3710. }
  3711. // Used by replaceSelections to allow moving the selection to the
  3712. // start or around the replaced test. Hint may be "start" or "around".
  3713. function computeReplacedSel(doc, changes, hint) {
  3714. var out = [];
  3715. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3716. for (var i = 0; i < changes.length; i++) {
  3717. var change = changes[i];
  3718. var from = offsetPos(change.from, oldPrev, newPrev);
  3719. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3720. oldPrev = change.to;
  3721. newPrev = to;
  3722. if (hint == "around") {
  3723. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3724. out[i] = new Range(inv ? to : from, inv ? from : to);
  3725. } else {
  3726. out[i] = new Range(from, from);
  3727. }
  3728. }
  3729. return new Selection(out, doc.sel.primIndex);
  3730. }
  3731. // Allow "beforeChange" event handlers to influence a change
  3732. function filterChange(doc, change, update) {
  3733. var obj = {
  3734. canceled: false,
  3735. from: change.from,
  3736. to: change.to,
  3737. text: change.text,
  3738. origin: change.origin,
  3739. cancel: function() { this.canceled = true; }
  3740. };
  3741. if (update) obj.update = function(from, to, text, origin) {
  3742. if (from) this.from = clipPos(doc, from);
  3743. if (to) this.to = clipPos(doc, to);
  3744. if (text) this.text = text;
  3745. if (origin !== undefined) this.origin = origin;
  3746. };
  3747. signal(doc, "beforeChange", doc, obj);
  3748. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3749. if (obj.canceled) return null;
  3750. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3751. }
  3752. // Apply a change to a document, and add it to the document's
  3753. // history, and propagating it to all linked documents.
  3754. function makeChange(doc, change, ignoreReadOnly) {
  3755. if (doc.cm) {
  3756. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3757. if (doc.cm.state.suppressEdits) return;
  3758. }
  3759. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3760. change = filterChange(doc, change, true);
  3761. if (!change) return;
  3762. }
  3763. // Possibly split or suppress the update based on the presence
  3764. // of read-only spans in its range.
  3765. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3766. if (split) {
  3767. for (var i = split.length - 1; i >= 0; --i)
  3768. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3769. } else {
  3770. makeChangeInner(doc, change);
  3771. }
  3772. }
  3773. function makeChangeInner(doc, change) {
  3774. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3775. var selAfter = computeSelAfterChange(doc, change);
  3776. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3777. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3778. var rebased = [];
  3779. linkedDocs(doc, function(doc, sharedHist) {
  3780. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3781. rebaseHist(doc.history, change);
  3782. rebased.push(doc.history);
  3783. }
  3784. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3785. });
  3786. }
  3787. // Revert a change stored in a document's history.
  3788. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3789. if (doc.cm && doc.cm.state.suppressEdits) return;
  3790. var hist = doc.history, event, selAfter = doc.sel;
  3791. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3792. // Verify that there is a useable event (so that ctrl-z won't
  3793. // needlessly clear selection events)
  3794. for (var i = 0; i < source.length; i++) {
  3795. event = source[i];
  3796. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3797. break;
  3798. }
  3799. if (i == source.length) return;
  3800. hist.lastOrigin = hist.lastSelOrigin = null;
  3801. for (;;) {
  3802. event = source.pop();
  3803. if (event.ranges) {
  3804. pushSelectionToHistory(event, dest);
  3805. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3806. setSelection(doc, event, {clearRedo: false});
  3807. return;
  3808. }
  3809. selAfter = event;
  3810. }
  3811. else break;
  3812. }
  3813. // Build up a reverse change object to add to the opposite history
  3814. // stack (redo when undoing, and vice versa).
  3815. var antiChanges = [];
  3816. pushSelectionToHistory(selAfter, dest);
  3817. dest.push({changes: antiChanges, generation: hist.generation});
  3818. hist.generation = event.generation || ++hist.maxGeneration;
  3819. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3820. for (var i = event.changes.length - 1; i >= 0; --i) {
  3821. var change = event.changes[i];
  3822. change.origin = type;
  3823. if (filter && !filterChange(doc, change, false)) {
  3824. source.length = 0;
  3825. return;
  3826. }
  3827. antiChanges.push(historyChangeFromChange(doc, change));
  3828. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3829. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3830. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3831. var rebased = [];
  3832. // Propagate to the linked documents
  3833. linkedDocs(doc, function(doc, sharedHist) {
  3834. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3835. rebaseHist(doc.history, change);
  3836. rebased.push(doc.history);
  3837. }
  3838. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3839. });
  3840. }
  3841. }
  3842. // Sub-views need their line numbers shifted when text is added
  3843. // above or below them in the parent document.
  3844. function shiftDoc(doc, distance) {
  3845. if (distance == 0) return;
  3846. doc.first += distance;
  3847. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  3848. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3849. Pos(range.head.line + distance, range.head.ch));
  3850. }), doc.sel.primIndex);
  3851. if (doc.cm) {
  3852. regChange(doc.cm, doc.first, doc.first - distance, distance);
  3853. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  3854. regLineChange(doc.cm, l, "gutter");
  3855. }
  3856. }
  3857. // More lower-level change function, handling only a single document
  3858. // (not linked ones).
  3859. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3860. if (doc.cm && !doc.cm.curOp)
  3861. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3862. if (change.to.line < doc.first) {
  3863. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3864. return;
  3865. }
  3866. if (change.from.line > doc.lastLine()) return;
  3867. // Clip the change to the size of this doc
  3868. if (change.from.line < doc.first) {
  3869. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3870. shiftDoc(doc, shift);
  3871. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3872. text: [lst(change.text)], origin: change.origin};
  3873. }
  3874. var last = doc.lastLine();
  3875. if (change.to.line > last) {
  3876. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3877. text: [change.text[0]], origin: change.origin};
  3878. }
  3879. change.removed = getBetween(doc, change.from, change.to);
  3880. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  3881. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3882. else updateDoc(doc, change, spans);
  3883. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3884. }
  3885. // Handle the interaction of a change to a document with the editor
  3886. // that this document is part of.
  3887. function makeChangeSingleDocInEditor(cm, change, spans) {
  3888. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3889. var recomputeMaxLength = false, checkWidthStart = from.line;
  3890. if (!cm.options.lineWrapping) {
  3891. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3892. doc.iter(checkWidthStart, to.line + 1, function(line) {
  3893. if (line == display.maxLine) {
  3894. recomputeMaxLength = true;
  3895. return true;
  3896. }
  3897. });
  3898. }
  3899. if (doc.sel.contains(change.from, change.to) > -1)
  3900. signalCursorActivity(cm);
  3901. updateDoc(doc, change, spans, estimateHeight(cm));
  3902. if (!cm.options.lineWrapping) {
  3903. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  3904. var len = lineLength(line);
  3905. if (len > display.maxLineLength) {
  3906. display.maxLine = line;
  3907. display.maxLineLength = len;
  3908. display.maxLineChanged = true;
  3909. recomputeMaxLength = false;
  3910. }
  3911. });
  3912. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  3913. }
  3914. // Adjust frontier, schedule worker
  3915. doc.frontier = Math.min(doc.frontier, from.line);
  3916. startWorker(cm, 400);
  3917. var lendiff = change.text.length - (to.line - from.line) - 1;
  3918. // Remember that these lines changed, for updating the display
  3919. if (change.full)
  3920. regChange(cm);
  3921. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  3922. regLineChange(cm, from.line, "text");
  3923. else
  3924. regChange(cm, from.line, to.line + 1, lendiff);
  3925. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  3926. if (changeHandler || changesHandler) {
  3927. var obj = {
  3928. from: from, to: to,
  3929. text: change.text,
  3930. removed: change.removed,
  3931. origin: change.origin
  3932. };
  3933. if (changeHandler) signalLater(cm, "change", cm, obj);
  3934. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  3935. }
  3936. cm.display.selForContextMenu = null;
  3937. }
  3938. function replaceRange(doc, code, from, to, origin) {
  3939. if (!to) to = from;
  3940. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  3941. if (typeof code == "string") code = splitLines(code);
  3942. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  3943. }
  3944. // SCROLLING THINGS INTO VIEW
  3945. // If an editor sits on the top or bottom of the window, partially
  3946. // scrolled out of view, this ensures that the cursor is visible.
  3947. function maybeScrollWindow(cm, coords) {
  3948. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  3949. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3950. if (coords.top + box.top < 0) doScroll = true;
  3951. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  3952. if (doScroll != null && !phantom) {
  3953. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  3954. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  3955. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  3956. coords.left + "px; width: 2px;");
  3957. cm.display.lineSpace.appendChild(scrollNode);
  3958. scrollNode.scrollIntoView(doScroll);
  3959. cm.display.lineSpace.removeChild(scrollNode);
  3960. }
  3961. }
  3962. // Scroll a given position into view (immediately), verifying that
  3963. // it actually became visible (as line heights are accurately
  3964. // measured, the position of something may 'drift' during drawing).
  3965. function scrollPosIntoView(cm, pos, end, margin) {
  3966. if (margin == null) margin = 0;
  3967. for (var limit = 0; limit < 5; limit++) {
  3968. var changed = false, coords = cursorCoords(cm, pos);
  3969. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3970. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3971. Math.min(coords.top, endCoords.top) - margin,
  3972. Math.max(coords.left, endCoords.left),
  3973. Math.max(coords.bottom, endCoords.bottom) + margin);
  3974. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3975. if (scrollPos.scrollTop != null) {
  3976. setScrollTop(cm, scrollPos.scrollTop);
  3977. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  3978. }
  3979. if (scrollPos.scrollLeft != null) {
  3980. setScrollLeft(cm, scrollPos.scrollLeft);
  3981. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  3982. }
  3983. if (!changed) break;
  3984. }
  3985. return coords;
  3986. }
  3987. // Scroll a given set of coordinates into view (immediately).
  3988. function scrollIntoView(cm, x1, y1, x2, y2) {
  3989. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  3990. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  3991. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  3992. }
  3993. // Calculate a new scroll position needed to scroll the given
  3994. // rectangle into view. Returns an object with scrollTop and
  3995. // scrollLeft properties. When these are undefined, the
  3996. // vertical/horizontal position does not need to be adjusted.
  3997. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3998. var display = cm.display, snapMargin = textHeight(cm.display);
  3999. if (y1 < 0) y1 = 0;
  4000. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4001. var screen = displayHeight(cm), result = {};
  4002. if (y2 - y1 > screen) y2 = y1 + screen;
  4003. var docBottom = cm.doc.height + paddingVert(display);
  4004. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4005. if (y1 < screentop) {
  4006. result.scrollTop = atTop ? 0 : y1;
  4007. } else if (y2 > screentop + screen) {
  4008. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4009. if (newTop != screentop) result.scrollTop = newTop;
  4010. }
  4011. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4012. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4013. var tooWide = x2 - x1 > screenw;
  4014. if (tooWide) x2 = x1 + screenw;
  4015. if (x1 < 10)
  4016. result.scrollLeft = 0;
  4017. else if (x1 < screenleft)
  4018. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4019. else if (x2 > screenw + screenleft - 3)
  4020. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4021. return result;
  4022. }
  4023. // Store a relative adjustment to the scroll position in the current
  4024. // operation (to be applied when the operation finishes).
  4025. function addToScrollPos(cm, left, top) {
  4026. if (left != null || top != null) resolveScrollToPos(cm);
  4027. if (left != null)
  4028. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4029. if (top != null)
  4030. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4031. }
  4032. // Make sure that at the end of the operation the current cursor is
  4033. // shown.
  4034. function ensureCursorVisible(cm) {
  4035. resolveScrollToPos(cm);
  4036. var cur = cm.getCursor(), from = cur, to = cur;
  4037. if (!cm.options.lineWrapping) {
  4038. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4039. to = Pos(cur.line, cur.ch + 1);
  4040. }
  4041. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4042. }
  4043. // When an operation has its scrollToPos property set, and another
  4044. // scroll action is applied before the end of the operation, this
  4045. // 'simulates' scrolling that position into view in a cheap way, so
  4046. // that the effect of intermediate scroll commands is not ignored.
  4047. function resolveScrollToPos(cm) {
  4048. var range = cm.curOp.scrollToPos;
  4049. if (range) {
  4050. cm.curOp.scrollToPos = null;
  4051. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4052. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4053. Math.min(from.top, to.top) - range.margin,
  4054. Math.max(from.right, to.right),
  4055. Math.max(from.bottom, to.bottom) + range.margin);
  4056. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4057. }
  4058. }
  4059. // API UTILITIES
  4060. // Indent the given line. The how parameter can be "smart",
  4061. // "add"/null, "subtract", or "prev". When aggressive is false
  4062. // (typically set to true for forced single-line indents), empty
  4063. // lines are not indented, and places where the mode returns Pass
  4064. // are left alone.
  4065. function indentLine(cm, n, how, aggressive) {
  4066. var doc = cm.doc, state;
  4067. if (how == null) how = "add";
  4068. if (how == "smart") {
  4069. // Fall back to "prev" when the mode doesn't have an indentation
  4070. // method.
  4071. if (!doc.mode.indent) how = "prev";
  4072. else state = getStateBefore(cm, n);
  4073. }
  4074. var tabSize = cm.options.tabSize;
  4075. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4076. if (line.stateAfter) line.stateAfter = null;
  4077. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4078. if (!aggressive && !/\S/.test(line.text)) {
  4079. indentation = 0;
  4080. how = "not";
  4081. } else if (how == "smart") {
  4082. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4083. if (indentation == Pass || indentation > 150) {
  4084. if (!aggressive) return;
  4085. how = "prev";
  4086. }
  4087. }
  4088. if (how == "prev") {
  4089. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4090. else indentation = 0;
  4091. } else if (how == "add") {
  4092. indentation = curSpace + cm.options.indentUnit;
  4093. } else if (how == "subtract") {
  4094. indentation = curSpace - cm.options.indentUnit;
  4095. } else if (typeof how == "number") {
  4096. indentation = curSpace + how;
  4097. }
  4098. indentation = Math.max(0, indentation);
  4099. var indentString = "", pos = 0;
  4100. if (cm.options.indentWithTabs)
  4101. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4102. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4103. if (indentString != curSpaceString) {
  4104. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4105. } else {
  4106. // Ensure that, if the cursor was in the whitespace at the start
  4107. // of the line, it is moved to the end of that space.
  4108. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4109. var range = doc.sel.ranges[i];
  4110. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4111. var pos = Pos(n, curSpaceString.length);
  4112. replaceOneSelection(doc, i, new Range(pos, pos));
  4113. break;
  4114. }
  4115. }
  4116. }
  4117. line.stateAfter = null;
  4118. }
  4119. // Utility for applying a change to a line by handle or number,
  4120. // returning the number and optionally registering the line as
  4121. // changed.
  4122. function changeLine(doc, handle, changeType, op) {
  4123. var no = handle, line = handle;
  4124. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4125. else no = lineNo(handle);
  4126. if (no == null) return null;
  4127. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4128. return line;
  4129. }
  4130. // Helper for deleting text near the selection(s), used to implement
  4131. // backspace, delete, and similar functionality.
  4132. function deleteNearSelection(cm, compute) {
  4133. var ranges = cm.doc.sel.ranges, kill = [];
  4134. // Build up a set of ranges to kill first, merging overlapping
  4135. // ranges.
  4136. for (var i = 0; i < ranges.length; i++) {
  4137. var toKill = compute(ranges[i]);
  4138. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4139. var replaced = kill.pop();
  4140. if (cmp(replaced.from, toKill.from) < 0) {
  4141. toKill.from = replaced.from;
  4142. break;
  4143. }
  4144. }
  4145. kill.push(toKill);
  4146. }
  4147. // Next, remove those actual ranges.
  4148. runInOp(cm, function() {
  4149. for (var i = kill.length - 1; i >= 0; i--)
  4150. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4151. ensureCursorVisible(cm);
  4152. });
  4153. }
  4154. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4155. // right), unit can be "char", "column" (like char, but doesn't
  4156. // cross line boundaries), "word" (across next word), or "group" (to
  4157. // the start of next group of word or non-word-non-whitespace
  4158. // chars). The visually param controls whether, in right-to-left
  4159. // text, direction 1 means to move towards the next index in the
  4160. // string, or towards the character to the right of the current
  4161. // position. The resulting position will have a hitSide=true
  4162. // property if it reached the end of the document.
  4163. function findPosH(doc, pos, dir, unit, visually) {
  4164. var line = pos.line, ch = pos.ch, origDir = dir;
  4165. var lineObj = getLine(doc, line);
  4166. var possible = true;
  4167. function findNextLine() {
  4168. var l = line + dir;
  4169. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  4170. line = l;
  4171. return lineObj = getLine(doc, l);
  4172. }
  4173. function moveOnce(boundToLine) {
  4174. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4175. if (next == null) {
  4176. if (!boundToLine && findNextLine()) {
  4177. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4178. else ch = dir < 0 ? lineObj.text.length : 0;
  4179. } else return (possible = false);
  4180. } else ch = next;
  4181. return true;
  4182. }
  4183. if (unit == "char") moveOnce();
  4184. else if (unit == "column") moveOnce(true);
  4185. else if (unit == "word" || unit == "group") {
  4186. var sawType = null, group = unit == "group";
  4187. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4188. for (var first = true;; first = false) {
  4189. if (dir < 0 && !moveOnce(!first)) break;
  4190. var cur = lineObj.text.charAt(ch) || "\n";
  4191. var type = isWordChar(cur, helper) ? "w"
  4192. : group && cur == "\n" ? "n"
  4193. : !group || /\s/.test(cur) ? null
  4194. : "p";
  4195. if (group && !first && !type) type = "s";
  4196. if (sawType && sawType != type) {
  4197. if (dir < 0) {dir = 1; moveOnce();}
  4198. break;
  4199. }
  4200. if (type) sawType = type;
  4201. if (dir > 0 && !moveOnce(!first)) break;
  4202. }
  4203. }
  4204. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  4205. if (!possible) result.hitSide = true;
  4206. return result;
  4207. }
  4208. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4209. // "page" or "line". The resulting position will have a hitSide=true
  4210. // property if it reached the end of the document.
  4211. function findPosV(cm, pos, dir, unit) {
  4212. var doc = cm.doc, x = pos.left, y;
  4213. if (unit == "page") {
  4214. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4215. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4216. } else if (unit == "line") {
  4217. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4218. }
  4219. for (;;) {
  4220. var target = coordsChar(cm, x, y);
  4221. if (!target.outside) break;
  4222. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4223. y += dir * 5;
  4224. }
  4225. return target;
  4226. }
  4227. // EDITOR METHODS
  4228. // The publicly visible API. Note that methodOp(f) means
  4229. // 'wrap f in an operation, performed on its `this` parameter'.
  4230. // This is not the complete set of editor methods. Most of the
  4231. // methods defined on the Doc type are also injected into
  4232. // CodeMirror.prototype, for backwards compatibility and
  4233. // convenience.
  4234. CodeMirror.prototype = {
  4235. constructor: CodeMirror,
  4236. focus: function(){window.focus(); this.display.input.focus();},
  4237. setOption: function(option, value) {
  4238. var options = this.options, old = options[option];
  4239. if (options[option] == value && option != "mode") return;
  4240. options[option] = value;
  4241. if (optionHandlers.hasOwnProperty(option))
  4242. operation(this, optionHandlers[option])(this, value, old);
  4243. },
  4244. getOption: function(option) {return this.options[option];},
  4245. getDoc: function() {return this.doc;},
  4246. addKeyMap: function(map, bottom) {
  4247. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4248. },
  4249. removeKeyMap: function(map) {
  4250. var maps = this.state.keyMaps;
  4251. for (var i = 0; i < maps.length; ++i)
  4252. if (maps[i] == map || maps[i].name == map) {
  4253. maps.splice(i, 1);
  4254. return true;
  4255. }
  4256. },
  4257. addOverlay: methodOp(function(spec, options) {
  4258. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4259. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4260. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4261. this.state.modeGen++;
  4262. regChange(this);
  4263. }),
  4264. removeOverlay: methodOp(function(spec) {
  4265. var overlays = this.state.overlays;
  4266. for (var i = 0; i < overlays.length; ++i) {
  4267. var cur = overlays[i].modeSpec;
  4268. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4269. overlays.splice(i, 1);
  4270. this.state.modeGen++;
  4271. regChange(this);
  4272. return;
  4273. }
  4274. }
  4275. }),
  4276. indentLine: methodOp(function(n, dir, aggressive) {
  4277. if (typeof dir != "string" && typeof dir != "number") {
  4278. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4279. else dir = dir ? "add" : "subtract";
  4280. }
  4281. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4282. }),
  4283. indentSelection: methodOp(function(how) {
  4284. var ranges = this.doc.sel.ranges, end = -1;
  4285. for (var i = 0; i < ranges.length; i++) {
  4286. var range = ranges[i];
  4287. if (!range.empty()) {
  4288. var from = range.from(), to = range.to();
  4289. var start = Math.max(end, from.line);
  4290. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4291. for (var j = start; j < end; ++j)
  4292. indentLine(this, j, how);
  4293. var newRanges = this.doc.sel.ranges;
  4294. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4295. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4296. } else if (range.head.line > end) {
  4297. indentLine(this, range.head.line, how, true);
  4298. end = range.head.line;
  4299. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4300. }
  4301. }
  4302. }),
  4303. // Fetch the parser token for a given character. Useful for hacks
  4304. // that want to inspect the mode state (say, for completion).
  4305. getTokenAt: function(pos, precise) {
  4306. return takeToken(this, pos, precise);
  4307. },
  4308. getLineTokens: function(line, precise) {
  4309. return takeToken(this, Pos(line), precise, true);
  4310. },
  4311. getTokenTypeAt: function(pos) {
  4312. pos = clipPos(this.doc, pos);
  4313. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4314. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4315. var type;
  4316. if (ch == 0) type = styles[2];
  4317. else for (;;) {
  4318. var mid = (before + after) >> 1;
  4319. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4320. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4321. else { type = styles[mid * 2 + 2]; break; }
  4322. }
  4323. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4324. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4325. },
  4326. getModeAt: function(pos) {
  4327. var mode = this.doc.mode;
  4328. if (!mode.innerMode) return mode;
  4329. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4330. },
  4331. getHelper: function(pos, type) {
  4332. return this.getHelpers(pos, type)[0];
  4333. },
  4334. getHelpers: function(pos, type) {
  4335. var found = [];
  4336. if (!helpers.hasOwnProperty(type)) return helpers;
  4337. var help = helpers[type], mode = this.getModeAt(pos);
  4338. if (typeof mode[type] == "string") {
  4339. if (help[mode[type]]) found.push(help[mode[type]]);
  4340. } else if (mode[type]) {
  4341. for (var i = 0; i < mode[type].length; i++) {
  4342. var val = help[mode[type][i]];
  4343. if (val) found.push(val);
  4344. }
  4345. } else if (mode.helperType && help[mode.helperType]) {
  4346. found.push(help[mode.helperType]);
  4347. } else if (help[mode.name]) {
  4348. found.push(help[mode.name]);
  4349. }
  4350. for (var i = 0; i < help._global.length; i++) {
  4351. var cur = help._global[i];
  4352. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4353. found.push(cur.val);
  4354. }
  4355. return found;
  4356. },
  4357. getStateAfter: function(line, precise) {
  4358. var doc = this.doc;
  4359. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4360. return getStateBefore(this, line + 1, precise);
  4361. },
  4362. cursorCoords: function(start, mode) {
  4363. var pos, range = this.doc.sel.primary();
  4364. if (start == null) pos = range.head;
  4365. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4366. else pos = start ? range.from() : range.to();
  4367. return cursorCoords(this, pos, mode || "page");
  4368. },
  4369. charCoords: function(pos, mode) {
  4370. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4371. },
  4372. coordsChar: function(coords, mode) {
  4373. coords = fromCoordSystem(this, coords, mode || "page");
  4374. return coordsChar(this, coords.left, coords.top);
  4375. },
  4376. lineAtHeight: function(height, mode) {
  4377. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4378. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4379. },
  4380. heightAtLine: function(line, mode) {
  4381. var end = false, last = this.doc.first + this.doc.size - 1;
  4382. if (line < this.doc.first) line = this.doc.first;
  4383. else if (line > last) { line = last; end = true; }
  4384. var lineObj = getLine(this.doc, line);
  4385. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4386. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4387. },
  4388. defaultTextHeight: function() { return textHeight(this.display); },
  4389. defaultCharWidth: function() { return charWidth(this.display); },
  4390. setGutterMarker: methodOp(function(line, gutterID, value) {
  4391. return changeLine(this.doc, line, "gutter", function(line) {
  4392. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4393. markers[gutterID] = value;
  4394. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4395. return true;
  4396. });
  4397. }),
  4398. clearGutter: methodOp(function(gutterID) {
  4399. var cm = this, doc = cm.doc, i = doc.first;
  4400. doc.iter(function(line) {
  4401. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4402. line.gutterMarkers[gutterID] = null;
  4403. regLineChange(cm, i, "gutter");
  4404. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4405. }
  4406. ++i;
  4407. });
  4408. }),
  4409. addLineWidget: methodOp(function(handle, node, options) {
  4410. return addLineWidget(this, handle, node, options);
  4411. }),
  4412. removeLineWidget: function(widget) { widget.clear(); },
  4413. lineInfo: function(line) {
  4414. if (typeof line == "number") {
  4415. if (!isLine(this.doc, line)) return null;
  4416. var n = line;
  4417. line = getLine(this.doc, line);
  4418. if (!line) return null;
  4419. } else {
  4420. var n = lineNo(line);
  4421. if (n == null) return null;
  4422. }
  4423. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4424. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4425. widgets: line.widgets};
  4426. },
  4427. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4428. addWidget: function(pos, node, scroll, vert, horiz) {
  4429. var display = this.display;
  4430. pos = cursorCoords(this, clipPos(this.doc, pos));
  4431. var top = pos.bottom, left = pos.left;
  4432. node.style.position = "absolute";
  4433. node.setAttribute("cm-ignore-events", "true");
  4434. this.display.input.setUneditable(node);
  4435. display.sizer.appendChild(node);
  4436. if (vert == "over") {
  4437. top = pos.top;
  4438. } else if (vert == "above" || vert == "near") {
  4439. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4440. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4441. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4442. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4443. top = pos.top - node.offsetHeight;
  4444. else if (pos.bottom + node.offsetHeight <= vspace)
  4445. top = pos.bottom;
  4446. if (left + node.offsetWidth > hspace)
  4447. left = hspace - node.offsetWidth;
  4448. }
  4449. node.style.top = top + "px";
  4450. node.style.left = node.style.right = "";
  4451. if (horiz == "right") {
  4452. left = display.sizer.clientWidth - node.offsetWidth;
  4453. node.style.right = "0px";
  4454. } else {
  4455. if (horiz == "left") left = 0;
  4456. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4457. node.style.left = left + "px";
  4458. }
  4459. if (scroll)
  4460. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4461. },
  4462. triggerOnKeyDown: methodOp(onKeyDown),
  4463. triggerOnKeyPress: methodOp(onKeyPress),
  4464. triggerOnKeyUp: onKeyUp,
  4465. execCommand: function(cmd) {
  4466. if (commands.hasOwnProperty(cmd))
  4467. return commands[cmd](this);
  4468. },
  4469. findPosH: function(from, amount, unit, visually) {
  4470. var dir = 1;
  4471. if (amount < 0) { dir = -1; amount = -amount; }
  4472. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4473. cur = findPosH(this.doc, cur, dir, unit, visually);
  4474. if (cur.hitSide) break;
  4475. }
  4476. return cur;
  4477. },
  4478. moveH: methodOp(function(dir, unit) {
  4479. var cm = this;
  4480. cm.extendSelectionsBy(function(range) {
  4481. if (cm.display.shift || cm.doc.extend || range.empty())
  4482. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4483. else
  4484. return dir < 0 ? range.from() : range.to();
  4485. }, sel_move);
  4486. }),
  4487. deleteH: methodOp(function(dir, unit) {
  4488. var sel = this.doc.sel, doc = this.doc;
  4489. if (sel.somethingSelected())
  4490. doc.replaceSelection("", null, "+delete");
  4491. else
  4492. deleteNearSelection(this, function(range) {
  4493. var other = findPosH(doc, range.head, dir, unit, false);
  4494. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4495. });
  4496. }),
  4497. findPosV: function(from, amount, unit, goalColumn) {
  4498. var dir = 1, x = goalColumn;
  4499. if (amount < 0) { dir = -1; amount = -amount; }
  4500. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4501. var coords = cursorCoords(this, cur, "div");
  4502. if (x == null) x = coords.left;
  4503. else coords.left = x;
  4504. cur = findPosV(this, coords, dir, unit);
  4505. if (cur.hitSide) break;
  4506. }
  4507. return cur;
  4508. },
  4509. moveV: methodOp(function(dir, unit) {
  4510. var cm = this, doc = this.doc, goals = [];
  4511. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4512. doc.extendSelectionsBy(function(range) {
  4513. if (collapse)
  4514. return dir < 0 ? range.from() : range.to();
  4515. var headPos = cursorCoords(cm, range.head, "div");
  4516. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4517. goals.push(headPos.left);
  4518. var pos = findPosV(cm, headPos, dir, unit);
  4519. if (unit == "page" && range == doc.sel.primary())
  4520. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4521. return pos;
  4522. }, sel_move);
  4523. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4524. doc.sel.ranges[i].goalColumn = goals[i];
  4525. }),
  4526. // Find the word at the given position (as returned by coordsChar).
  4527. findWordAt: function(pos) {
  4528. var doc = this.doc, line = getLine(doc, pos.line).text;
  4529. var start = pos.ch, end = pos.ch;
  4530. if (line) {
  4531. var helper = this.getHelper(pos, "wordChars");
  4532. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4533. var startChar = line.charAt(start);
  4534. var check = isWordChar(startChar, helper)
  4535. ? function(ch) { return isWordChar(ch, helper); }
  4536. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4537. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4538. while (start > 0 && check(line.charAt(start - 1))) --start;
  4539. while (end < line.length && check(line.charAt(end))) ++end;
  4540. }
  4541. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4542. },
  4543. toggleOverwrite: function(value) {
  4544. if (value != null && value == this.state.overwrite) return;
  4545. if (this.state.overwrite = !this.state.overwrite)
  4546. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4547. else
  4548. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4549. signal(this, "overwriteToggle", this, this.state.overwrite);
  4550. },
  4551. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4552. scrollTo: methodOp(function(x, y) {
  4553. if (x != null || y != null) resolveScrollToPos(this);
  4554. if (x != null) this.curOp.scrollLeft = x;
  4555. if (y != null) this.curOp.scrollTop = y;
  4556. }),
  4557. getScrollInfo: function() {
  4558. var scroller = this.display.scroller;
  4559. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4560. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4561. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4562. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4563. },
  4564. scrollIntoView: methodOp(function(range, margin) {
  4565. if (range == null) {
  4566. range = {from: this.doc.sel.primary().head, to: null};
  4567. if (margin == null) margin = this.options.cursorScrollMargin;
  4568. } else if (typeof range == "number") {
  4569. range = {from: Pos(range, 0), to: null};
  4570. } else if (range.from == null) {
  4571. range = {from: range, to: null};
  4572. }
  4573. if (!range.to) range.to = range.from;
  4574. range.margin = margin || 0;
  4575. if (range.from.line != null) {
  4576. resolveScrollToPos(this);
  4577. this.curOp.scrollToPos = range;
  4578. } else {
  4579. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4580. Math.min(range.from.top, range.to.top) - range.margin,
  4581. Math.max(range.from.right, range.to.right),
  4582. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4583. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4584. }
  4585. }),
  4586. setSize: methodOp(function(width, height) {
  4587. var cm = this;
  4588. function interpret(val) {
  4589. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4590. }
  4591. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4592. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4593. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4594. var lineNo = cm.display.viewFrom;
  4595. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4596. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4597. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4598. ++lineNo;
  4599. });
  4600. cm.curOp.forceUpdate = true;
  4601. signal(cm, "refresh", this);
  4602. }),
  4603. operation: function(f){return runInOp(this, f);},
  4604. refresh: methodOp(function() {
  4605. var oldHeight = this.display.cachedTextHeight;
  4606. regChange(this);
  4607. this.curOp.forceUpdate = true;
  4608. clearCaches(this);
  4609. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4610. updateGutterSpace(this);
  4611. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4612. estimateLineHeights(this);
  4613. signal(this, "refresh", this);
  4614. }),
  4615. swapDoc: methodOp(function(doc) {
  4616. var old = this.doc;
  4617. old.cm = null;
  4618. attachDoc(this, doc);
  4619. clearCaches(this);
  4620. this.display.input.reset();
  4621. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4622. this.curOp.forceScroll = true;
  4623. signalLater(this, "swapDoc", this, old);
  4624. return old;
  4625. }),
  4626. getInputField: function(){return this.display.input.getField();},
  4627. getWrapperElement: function(){return this.display.wrapper;},
  4628. getScrollerElement: function(){return this.display.scroller;},
  4629. getGutterElement: function(){return this.display.gutters;}
  4630. };
  4631. eventMixin(CodeMirror);
  4632. // OPTION DEFAULTS
  4633. // The default configuration options.
  4634. var defaults = CodeMirror.defaults = {};
  4635. // Functions to run when options are changed.
  4636. var optionHandlers = CodeMirror.optionHandlers = {};
  4637. function option(name, deflt, handle, notOnInit) {
  4638. CodeMirror.defaults[name] = deflt;
  4639. if (handle) optionHandlers[name] =
  4640. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4641. }
  4642. // Passed to option handlers when there is no old value.
  4643. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4644. // These two are, on init, called from the constructor because they
  4645. // have to be initialized before the editor can start at all.
  4646. option("value", "", function(cm, val) {
  4647. cm.setValue(val);
  4648. }, true);
  4649. option("mode", null, function(cm, val) {
  4650. cm.doc.modeOption = val;
  4651. loadMode(cm);
  4652. }, true);
  4653. option("indentUnit", 2, loadMode, true);
  4654. option("indentWithTabs", false);
  4655. option("smartIndent", true);
  4656. option("tabSize", 4, function(cm) {
  4657. resetModeState(cm);
  4658. clearCaches(cm);
  4659. regChange(cm);
  4660. }, true);
  4661. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val) {
  4662. cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4663. cm.refresh();
  4664. }, true);
  4665. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4666. option("electricChars", true);
  4667. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4668. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4669. }, true);
  4670. option("rtlMoveVisually", !windows);
  4671. option("wholeLineUpdateBefore", true);
  4672. option("theme", "default", function(cm) {
  4673. themeChanged(cm);
  4674. guttersChanged(cm);
  4675. }, true);
  4676. option("keyMap", "default", function(cm, val, old) {
  4677. var next = getKeyMap(val);
  4678. var prev = old != CodeMirror.Init && getKeyMap(old);
  4679. if (prev && prev.detach) prev.detach(cm, next);
  4680. if (next.attach) next.attach(cm, prev || null);
  4681. });
  4682. option("extraKeys", null);
  4683. option("lineWrapping", false, wrappingChanged, true);
  4684. option("gutters", [], function(cm) {
  4685. setGuttersForLineNumbers(cm.options);
  4686. guttersChanged(cm);
  4687. }, true);
  4688. option("fixedGutter", true, function(cm, val) {
  4689. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4690. cm.refresh();
  4691. }, true);
  4692. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4693. option("scrollbarStyle", "native", function(cm) {
  4694. initScrollbars(cm);
  4695. updateScrollbars(cm);
  4696. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4697. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4698. }, true);
  4699. option("lineNumbers", false, function(cm) {
  4700. setGuttersForLineNumbers(cm.options);
  4701. guttersChanged(cm);
  4702. }, true);
  4703. option("firstLineNumber", 1, guttersChanged, true);
  4704. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4705. option("showCursorWhenSelecting", false, updateSelection, true);
  4706. option("resetSelectionOnContextMenu", true);
  4707. option("readOnly", false, function(cm, val) {
  4708. if (val == "nocursor") {
  4709. onBlur(cm);
  4710. cm.display.input.blur();
  4711. cm.display.disabled = true;
  4712. } else {
  4713. cm.display.disabled = false;
  4714. if (!val) cm.display.input.reset();
  4715. }
  4716. });
  4717. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4718. option("dragDrop", true);
  4719. option("cursorBlinkRate", 530);
  4720. option("cursorScrollMargin", 0);
  4721. option("cursorHeight", 1, updateSelection, true);
  4722. option("singleCursorHeightPerLine", true, updateSelection, true);
  4723. option("workTime", 100);
  4724. option("workDelay", 100);
  4725. option("flattenSpans", true, resetModeState, true);
  4726. option("addModeClass", false, resetModeState, true);
  4727. option("pollInterval", 100);
  4728. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4729. option("historyEventDelay", 1250);
  4730. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4731. option("maxHighlightLength", 10000, resetModeState, true);
  4732. option("moveInputWithCursor", true, function(cm, val) {
  4733. if (!val) cm.display.input.resetPosition();
  4734. });
  4735. option("tabindex", null, function(cm, val) {
  4736. cm.display.input.getField().tabIndex = val || "";
  4737. });
  4738. option("autofocus", null);
  4739. // MODE DEFINITION AND QUERYING
  4740. // Known modes, by name and by MIME
  4741. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4742. // Extra arguments are stored as the mode's dependencies, which is
  4743. // used by (legacy) mechanisms like loadmode.js to automatically
  4744. // load a mode. (Preferred mechanism is the require/define calls.)
  4745. CodeMirror.defineMode = function(name, mode) {
  4746. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4747. if (arguments.length > 2)
  4748. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4749. modes[name] = mode;
  4750. };
  4751. CodeMirror.defineMIME = function(mime, spec) {
  4752. mimeModes[mime] = spec;
  4753. };
  4754. // Given a MIME type, a {name, ...options} config object, or a name
  4755. // string, return a mode config object.
  4756. CodeMirror.resolveMode = function(spec) {
  4757. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4758. spec = mimeModes[spec];
  4759. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4760. var found = mimeModes[spec.name];
  4761. if (typeof found == "string") found = {name: found};
  4762. spec = createObj(found, spec);
  4763. spec.name = found.name;
  4764. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4765. return CodeMirror.resolveMode("application/xml");
  4766. }
  4767. if (typeof spec == "string") return {name: spec};
  4768. else return spec || {name: "null"};
  4769. };
  4770. // Given a mode spec (anything that resolveMode accepts), find and
  4771. // initialize an actual mode object.
  4772. CodeMirror.getMode = function(options, spec) {
  4773. var spec = CodeMirror.resolveMode(spec);
  4774. var mfactory = modes[spec.name];
  4775. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4776. var modeObj = mfactory(options, spec);
  4777. if (modeExtensions.hasOwnProperty(spec.name)) {
  4778. var exts = modeExtensions[spec.name];
  4779. for (var prop in exts) {
  4780. if (!exts.hasOwnProperty(prop)) continue;
  4781. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4782. modeObj[prop] = exts[prop];
  4783. }
  4784. }
  4785. modeObj.name = spec.name;
  4786. if (spec.helperType) modeObj.helperType = spec.helperType;
  4787. if (spec.modeProps) for (var prop in spec.modeProps)
  4788. modeObj[prop] = spec.modeProps[prop];
  4789. return modeObj;
  4790. };
  4791. // Minimal default mode.
  4792. CodeMirror.defineMode("null", function() {
  4793. return {token: function(stream) {stream.skipToEnd();}};
  4794. });
  4795. CodeMirror.defineMIME("text/plain", "null");
  4796. // This can be used to attach properties to mode objects from
  4797. // outside the actual mode definition.
  4798. var modeExtensions = CodeMirror.modeExtensions = {};
  4799. CodeMirror.extendMode = function(mode, properties) {
  4800. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4801. copyObj(properties, exts);
  4802. };
  4803. // EXTENSIONS
  4804. CodeMirror.defineExtension = function(name, func) {
  4805. CodeMirror.prototype[name] = func;
  4806. };
  4807. CodeMirror.defineDocExtension = function(name, func) {
  4808. Doc.prototype[name] = func;
  4809. };
  4810. CodeMirror.defineOption = option;
  4811. var initHooks = [];
  4812. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4813. var helpers = CodeMirror.helpers = {};
  4814. CodeMirror.registerHelper = function(type, name, value) {
  4815. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4816. helpers[type][name] = value;
  4817. };
  4818. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  4819. CodeMirror.registerHelper(type, name, value);
  4820. helpers[type]._global.push({pred: predicate, val: value});
  4821. };
  4822. // MODE STATE HANDLING
  4823. // Utility functions for working with state. Exported because nested
  4824. // modes need to do this for their inner modes.
  4825. var copyState = CodeMirror.copyState = function(mode, state) {
  4826. if (state === true) return state;
  4827. if (mode.copyState) return mode.copyState(state);
  4828. var nstate = {};
  4829. for (var n in state) {
  4830. var val = state[n];
  4831. if (val instanceof Array) val = val.concat([]);
  4832. nstate[n] = val;
  4833. }
  4834. return nstate;
  4835. };
  4836. var startState = CodeMirror.startState = function(mode, a1, a2) {
  4837. return mode.startState ? mode.startState(a1, a2) : true;
  4838. };
  4839. // Given a mode and a state (for that mode), find the inner mode and
  4840. // state at the position that the state refers to.
  4841. CodeMirror.innerMode = function(mode, state) {
  4842. while (mode.innerMode) {
  4843. var info = mode.innerMode(state);
  4844. if (!info || info.mode == mode) break;
  4845. state = info.state;
  4846. mode = info.mode;
  4847. }
  4848. return info || {mode: mode, state: state};
  4849. };
  4850. // STANDARD COMMANDS
  4851. // Commands are parameter-less actions that can be performed on an
  4852. // editor, mostly used for keybindings.
  4853. var commands = CodeMirror.commands = {
  4854. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  4855. singleSelection: function(cm) {
  4856. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4857. },
  4858. killLine: function(cm) {
  4859. deleteNearSelection(cm, function(range) {
  4860. if (range.empty()) {
  4861. var len = getLine(cm.doc, range.head.line).text.length;
  4862. if (range.head.ch == len && range.head.line < cm.lastLine())
  4863. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  4864. else
  4865. return {from: range.head, to: Pos(range.head.line, len)};
  4866. } else {
  4867. return {from: range.from(), to: range.to()};
  4868. }
  4869. });
  4870. },
  4871. deleteLine: function(cm) {
  4872. deleteNearSelection(cm, function(range) {
  4873. return {from: Pos(range.from().line, 0),
  4874. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  4875. });
  4876. },
  4877. delLineLeft: function(cm) {
  4878. deleteNearSelection(cm, function(range) {
  4879. return {from: Pos(range.from().line, 0), to: range.from()};
  4880. });
  4881. },
  4882. delWrappedLineLeft: function(cm) {
  4883. deleteNearSelection(cm, function(range) {
  4884. var top = cm.charCoords(range.head, "div").top + 5;
  4885. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  4886. return {from: leftPos, to: range.from()};
  4887. });
  4888. },
  4889. delWrappedLineRight: function(cm) {
  4890. deleteNearSelection(cm, function(range) {
  4891. var top = cm.charCoords(range.head, "div").top + 5;
  4892. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4893. return {from: range.from(), to: rightPos };
  4894. });
  4895. },
  4896. undo: function(cm) {cm.undo();},
  4897. redo: function(cm) {cm.redo();},
  4898. undoSelection: function(cm) {cm.undoSelection();},
  4899. redoSelection: function(cm) {cm.redoSelection();},
  4900. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  4901. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  4902. goLineStart: function(cm) {
  4903. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  4904. {origin: "+move", bias: 1});
  4905. },
  4906. goLineStartSmart: function(cm) {
  4907. cm.extendSelectionsBy(function(range) {
  4908. return lineStartSmart(cm, range.head);
  4909. }, {origin: "+move", bias: 1});
  4910. },
  4911. goLineEnd: function(cm) {
  4912. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  4913. {origin: "+move", bias: -1});
  4914. },
  4915. goLineRight: function(cm) {
  4916. cm.extendSelectionsBy(function(range) {
  4917. var top = cm.charCoords(range.head, "div").top + 5;
  4918. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4919. }, sel_move);
  4920. },
  4921. goLineLeft: function(cm) {
  4922. cm.extendSelectionsBy(function(range) {
  4923. var top = cm.charCoords(range.head, "div").top + 5;
  4924. return cm.coordsChar({left: 0, top: top}, "div");
  4925. }, sel_move);
  4926. },
  4927. goLineLeftSmart: function(cm) {
  4928. cm.extendSelectionsBy(function(range) {
  4929. var top = cm.charCoords(range.head, "div").top + 5;
  4930. var pos = cm.coordsChar({left: 0, top: top}, "div");
  4931. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  4932. return pos;
  4933. }, sel_move);
  4934. },
  4935. goLineUp: function(cm) {cm.moveV(-1, "line");},
  4936. goLineDown: function(cm) {cm.moveV(1, "line");},
  4937. goPageUp: function(cm) {cm.moveV(-1, "page");},
  4938. goPageDown: function(cm) {cm.moveV(1, "page");},
  4939. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  4940. goCharRight: function(cm) {cm.moveH(1, "char");},
  4941. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  4942. goColumnRight: function(cm) {cm.moveH(1, "column");},
  4943. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  4944. goGroupRight: function(cm) {cm.moveH(1, "group");},
  4945. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  4946. goWordRight: function(cm) {cm.moveH(1, "word");},
  4947. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  4948. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  4949. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  4950. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  4951. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  4952. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  4953. indentAuto: function(cm) {cm.indentSelection("smart");},
  4954. indentMore: function(cm) {cm.indentSelection("add");},
  4955. indentLess: function(cm) {cm.indentSelection("subtract");},
  4956. insertTab: function(cm) {cm.replaceSelection("\t");},
  4957. insertSoftTab: function(cm) {
  4958. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  4959. for (var i = 0; i < ranges.length; i++) {
  4960. var pos = ranges[i].from();
  4961. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  4962. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  4963. }
  4964. cm.replaceSelections(spaces);
  4965. },
  4966. defaultTab: function(cm) {
  4967. if (cm.somethingSelected()) cm.indentSelection("add");
  4968. else cm.execCommand("insertTab");
  4969. },
  4970. transposeChars: function(cm) {
  4971. runInOp(cm, function() {
  4972. var ranges = cm.listSelections(), newSel = [];
  4973. for (var i = 0; i < ranges.length; i++) {
  4974. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  4975. if (line) {
  4976. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  4977. if (cur.ch > 0) {
  4978. cur = new Pos(cur.line, cur.ch + 1);
  4979. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  4980. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  4981. } else if (cur.line > cm.doc.first) {
  4982. var prev = getLine(cm.doc, cur.line - 1).text;
  4983. if (prev)
  4984. cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1),
  4985. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  4986. }
  4987. }
  4988. newSel.push(new Range(cur, cur));
  4989. }
  4990. cm.setSelections(newSel);
  4991. });
  4992. },
  4993. newlineAndIndent: function(cm) {
  4994. runInOp(cm, function() {
  4995. var len = cm.listSelections().length;
  4996. for (var i = 0; i < len; i++) {
  4997. var range = cm.listSelections()[i];
  4998. cm.replaceRange("\n", range.anchor, range.head, "+input");
  4999. cm.indentLine(range.from().line + 1, null, true);
  5000. ensureCursorVisible(cm);
  5001. }
  5002. });
  5003. },
  5004. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5005. };
  5006. // STANDARD KEYMAPS
  5007. var keyMap = CodeMirror.keyMap = {};
  5008. keyMap.basic = {
  5009. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5010. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5011. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5012. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5013. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5014. "Esc": "singleSelection"
  5015. };
  5016. // Note that the save and find-related commands aren't defined by
  5017. // default. User code or addons can define them. Unknown commands
  5018. // are simply ignored.
  5019. keyMap.pcDefault = {
  5020. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5021. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5022. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5023. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5024. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5025. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5026. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5027. fallthrough: "basic"
  5028. };
  5029. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5030. keyMap.emacsy = {
  5031. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5032. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5033. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5034. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  5035. };
  5036. keyMap.macDefault = {
  5037. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5038. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5039. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5040. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5041. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5042. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5043. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5044. fallthrough: ["basic", "emacsy"]
  5045. };
  5046. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5047. // KEYMAP DISPATCH
  5048. function normalizeKeyName(name) {
  5049. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5050. var alt, ctrl, shift, cmd;
  5051. for (var i = 0; i < parts.length - 1; i++) {
  5052. var mod = parts[i];
  5053. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5054. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5055. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5056. else if (/^s(hift)$/i.test(mod)) shift = true;
  5057. else throw new Error("Unrecognized modifier name: " + mod);
  5058. }
  5059. if (alt) name = "Alt-" + name;
  5060. if (ctrl) name = "Ctrl-" + name;
  5061. if (cmd) name = "Cmd-" + name;
  5062. if (shift) name = "Shift-" + name;
  5063. return name;
  5064. }
  5065. // This is a kludge to keep keymaps mostly working as raw objects
  5066. // (backwards compatibility) while at the same time support features
  5067. // like normalization and multi-stroke key bindings. It compiles a
  5068. // new normalized keymap, and then updates the old object to reflect
  5069. // this.
  5070. CodeMirror.normalizeKeyMap = function(keymap) {
  5071. var copy = {};
  5072. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5073. var value = keymap[keyname];
  5074. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5075. if (value == "...") { delete keymap[keyname]; continue; }
  5076. var keys = map(keyname.split(" "), normalizeKeyName);
  5077. for (var i = 0; i < keys.length; i++) {
  5078. var val, name;
  5079. if (i == keys.length - 1) {
  5080. name = keyname;
  5081. val = value;
  5082. } else {
  5083. name = keys.slice(0, i + 1).join(" ");
  5084. val = "...";
  5085. }
  5086. var prev = copy[name];
  5087. if (!prev) copy[name] = val;
  5088. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5089. }
  5090. delete keymap[keyname];
  5091. }
  5092. for (var prop in copy) keymap[prop] = copy[prop];
  5093. return keymap;
  5094. };
  5095. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5096. map = getKeyMap(map);
  5097. var found = map.call ? map.call(key, context) : map[key];
  5098. if (found === false) return "nothing";
  5099. if (found === "...") return "multi";
  5100. if (found != null && handle(found)) return "handled";
  5101. if (map.fallthrough) {
  5102. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5103. return lookupKey(key, map.fallthrough, handle, context);
  5104. for (var i = 0; i < map.fallthrough.length; i++) {
  5105. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5106. if (result) return result;
  5107. }
  5108. }
  5109. };
  5110. // Modifier key presses don't count as 'real' key presses for the
  5111. // purpose of keymap fallthrough.
  5112. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5113. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5114. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5115. };
  5116. // Look up the name of a key as indicated by an event object.
  5117. var keyName = CodeMirror.keyName = function(event, noShift) {
  5118. if (presto && event.keyCode == 34 && event["char"]) return false;
  5119. var base = keyNames[event.keyCode], name = base;
  5120. if (name == null || event.altGraphKey) return false;
  5121. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5122. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5123. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5124. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5125. return name;
  5126. };
  5127. function getKeyMap(val) {
  5128. return typeof val == "string" ? keyMap[val] : val;
  5129. }
  5130. // FROMTEXTAREA
  5131. CodeMirror.fromTextArea = function(textarea, options) {
  5132. options = options ? copyObj(options) : {};
  5133. options.value = textarea.value;
  5134. if (!options.tabindex && textarea.tabIndex)
  5135. options.tabindex = textarea.tabIndex;
  5136. if (!options.placeholder && textarea.placeholder)
  5137. options.placeholder = textarea.placeholder;
  5138. // Set autofocus to true if this textarea is focused, or if it has
  5139. // autofocus and no other element is focused.
  5140. if (options.autofocus == null) {
  5141. var hasFocus = activeElt();
  5142. options.autofocus = hasFocus == textarea ||
  5143. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5144. }
  5145. function save() {textarea.value = cm.getValue();}
  5146. if (textarea.form) {
  5147. on(textarea.form, "submit", save);
  5148. // Deplorable hack to make the submit method do the right thing.
  5149. if (!options.leaveSubmitMethodAlone) {
  5150. var form = textarea.form, realSubmit = form.submit;
  5151. try {
  5152. var wrappedSubmit = form.submit = function() {
  5153. save();
  5154. form.submit = realSubmit;
  5155. form.submit();
  5156. form.submit = wrappedSubmit;
  5157. };
  5158. } catch(e) {}
  5159. }
  5160. }
  5161. options.finishInit = function(cm) {
  5162. cm.save = save;
  5163. cm.getTextArea = function() { return textarea; };
  5164. cm.toTextArea = function() {
  5165. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5166. save();
  5167. textarea.parentNode.removeChild(cm.getWrapperElement());
  5168. textarea.style.display = "";
  5169. if (textarea.form) {
  5170. off(textarea.form, "submit", save);
  5171. if (typeof textarea.form.submit == "function")
  5172. textarea.form.submit = realSubmit;
  5173. }
  5174. };
  5175. };
  5176. textarea.style.display = "none";
  5177. var cm = CodeMirror(function(node) {
  5178. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5179. }, options);
  5180. return cm;
  5181. };
  5182. // STRING STREAM
  5183. // Fed to the mode parsers, provides helper functions to make
  5184. // parsers more succinct.
  5185. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5186. this.pos = this.start = 0;
  5187. this.string = string;
  5188. this.tabSize = tabSize || 8;
  5189. this.lastColumnPos = this.lastColumnValue = 0;
  5190. this.lineStart = 0;
  5191. };
  5192. StringStream.prototype = {
  5193. eol: function() {return this.pos >= this.string.length;},
  5194. sol: function() {return this.pos == this.lineStart;},
  5195. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5196. next: function() {
  5197. if (this.pos < this.string.length)
  5198. return this.string.charAt(this.pos++);
  5199. },
  5200. eat: function(match) {
  5201. var ch = this.string.charAt(this.pos);
  5202. if (typeof match == "string") var ok = ch == match;
  5203. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5204. if (ok) {++this.pos; return ch;}
  5205. },
  5206. eatWhile: function(match) {
  5207. var start = this.pos;
  5208. while (this.eat(match)){}
  5209. return this.pos > start;
  5210. },
  5211. eatSpace: function() {
  5212. var start = this.pos;
  5213. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5214. return this.pos > start;
  5215. },
  5216. skipToEnd: function() {this.pos = this.string.length;},
  5217. skipTo: function(ch) {
  5218. var found = this.string.indexOf(ch, this.pos);
  5219. if (found > -1) {this.pos = found; return true;}
  5220. },
  5221. backUp: function(n) {this.pos -= n;},
  5222. column: function() {
  5223. if (this.lastColumnPos < this.start) {
  5224. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5225. this.lastColumnPos = this.start;
  5226. }
  5227. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5228. },
  5229. indentation: function() {
  5230. return countColumn(this.string, null, this.tabSize) -
  5231. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5232. },
  5233. match: function(pattern, consume, caseInsensitive) {
  5234. if (typeof pattern == "string") {
  5235. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5236. var substr = this.string.substr(this.pos, pattern.length);
  5237. if (cased(substr) == cased(pattern)) {
  5238. if (consume !== false) this.pos += pattern.length;
  5239. return true;
  5240. }
  5241. } else {
  5242. var match = this.string.slice(this.pos).match(pattern);
  5243. if (match && match.index > 0) return null;
  5244. if (match && consume !== false) this.pos += match[0].length;
  5245. return match;
  5246. }
  5247. },
  5248. current: function(){return this.string.slice(this.start, this.pos);},
  5249. hideFirstChars: function(n, inner) {
  5250. this.lineStart += n;
  5251. try { return inner(); }
  5252. finally { this.lineStart -= n; }
  5253. }
  5254. };
  5255. // TEXTMARKERS
  5256. // Created with markText and setBookmark methods. A TextMarker is a
  5257. // handle that can be used to clear or find a marked position in the
  5258. // document. Line objects hold arrays (markedSpans) containing
  5259. // {from, to, marker} object pointing to such marker objects, and
  5260. // indicating that such a marker is present on that line. Multiple
  5261. // lines may point to the same marker when it spans across lines.
  5262. // The spans will have null for their from/to properties when the
  5263. // marker continues beyond the start/end of the line. Markers have
  5264. // links back to the lines they currently touch.
  5265. var nextMarkerId = 0;
  5266. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5267. this.lines = [];
  5268. this.type = type;
  5269. this.doc = doc;
  5270. this.id = ++nextMarkerId;
  5271. };
  5272. eventMixin(TextMarker);
  5273. // Clear the marker.
  5274. TextMarker.prototype.clear = function() {
  5275. if (this.explicitlyCleared) return;
  5276. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5277. if (withOp) startOperation(cm);
  5278. if (hasHandler(this, "clear")) {
  5279. var found = this.find();
  5280. if (found) signalLater(this, "clear", found.from, found.to);
  5281. }
  5282. var min = null, max = null;
  5283. for (var i = 0; i < this.lines.length; ++i) {
  5284. var line = this.lines[i];
  5285. var span = getMarkedSpanFor(line.markedSpans, this);
  5286. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5287. else if (cm) {
  5288. if (span.to != null) max = lineNo(line);
  5289. if (span.from != null) min = lineNo(line);
  5290. }
  5291. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5292. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5293. updateLineHeight(line, textHeight(cm.display));
  5294. }
  5295. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5296. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5297. if (len > cm.display.maxLineLength) {
  5298. cm.display.maxLine = visual;
  5299. cm.display.maxLineLength = len;
  5300. cm.display.maxLineChanged = true;
  5301. }
  5302. }
  5303. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5304. this.lines.length = 0;
  5305. this.explicitlyCleared = true;
  5306. if (this.atomic && this.doc.cantEdit) {
  5307. this.doc.cantEdit = false;
  5308. if (cm) reCheckSelection(cm.doc);
  5309. }
  5310. if (cm) signalLater(cm, "markerCleared", cm, this);
  5311. if (withOp) endOperation(cm);
  5312. if (this.parent) this.parent.clear();
  5313. };
  5314. // Find the position of the marker in the document. Returns a {from,
  5315. // to} object by default. Side can be passed to get a specific side
  5316. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5317. // Pos objects returned contain a line object, rather than a line
  5318. // number (used to prevent looking up the same line twice).
  5319. TextMarker.prototype.find = function(side, lineObj) {
  5320. if (side == null && this.type == "bookmark") side = 1;
  5321. var from, to;
  5322. for (var i = 0; i < this.lines.length; ++i) {
  5323. var line = this.lines[i];
  5324. var span = getMarkedSpanFor(line.markedSpans, this);
  5325. if (span.from != null) {
  5326. from = Pos(lineObj ? line : lineNo(line), span.from);
  5327. if (side == -1) return from;
  5328. }
  5329. if (span.to != null) {
  5330. to = Pos(lineObj ? line : lineNo(line), span.to);
  5331. if (side == 1) return to;
  5332. }
  5333. }
  5334. return from && {from: from, to: to};
  5335. };
  5336. // Signals that the marker's widget changed, and surrounding layout
  5337. // should be recomputed.
  5338. TextMarker.prototype.changed = function() {
  5339. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5340. if (!pos || !cm) return;
  5341. runInOp(cm, function() {
  5342. var line = pos.line, lineN = lineNo(pos.line);
  5343. var view = findViewForLine(cm, lineN);
  5344. if (view) {
  5345. clearLineMeasurementCacheFor(view);
  5346. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5347. }
  5348. cm.curOp.updateMaxLine = true;
  5349. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5350. var oldHeight = widget.height;
  5351. widget.height = null;
  5352. var dHeight = widgetHeight(widget) - oldHeight;
  5353. if (dHeight)
  5354. updateLineHeight(line, line.height + dHeight);
  5355. }
  5356. });
  5357. };
  5358. TextMarker.prototype.attachLine = function(line) {
  5359. if (!this.lines.length && this.doc.cm) {
  5360. var op = this.doc.cm.curOp;
  5361. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5362. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5363. }
  5364. this.lines.push(line);
  5365. };
  5366. TextMarker.prototype.detachLine = function(line) {
  5367. this.lines.splice(indexOf(this.lines, line), 1);
  5368. if (!this.lines.length && this.doc.cm) {
  5369. var op = this.doc.cm.curOp;
  5370. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5371. }
  5372. };
  5373. // Collapsed markers have unique ids, in order to be able to order
  5374. // them, which is needed for uniquely determining an outer marker
  5375. // when they overlap (they may nest, but not partially overlap).
  5376. var nextMarkerId = 0;
  5377. // Create a marker, wire it up to the right lines, and
  5378. function markText(doc, from, to, options, type) {
  5379. // Shared markers (across linked documents) are handled separately
  5380. // (markTextShared will call out to this again, once per
  5381. // document).
  5382. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5383. // Ensure we are in an operation.
  5384. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5385. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5386. if (options) copyObj(options, marker, false);
  5387. // Don't connect empty markers unless clearWhenEmpty is false
  5388. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5389. return marker;
  5390. if (marker.replacedWith) {
  5391. // Showing up as a widget implies collapsed (widget replaces text)
  5392. marker.collapsed = true;
  5393. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5394. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5395. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5396. }
  5397. if (marker.collapsed) {
  5398. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5399. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5400. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5401. sawCollapsedSpans = true;
  5402. }
  5403. if (marker.addToHistory)
  5404. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5405. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5406. doc.iter(curLine, to.line + 1, function(line) {
  5407. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5408. updateMaxLine = true;
  5409. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5410. addMarkedSpan(line, new MarkedSpan(marker,
  5411. curLine == from.line ? from.ch : null,
  5412. curLine == to.line ? to.ch : null));
  5413. ++curLine;
  5414. });
  5415. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5416. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5417. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5418. });
  5419. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5420. if (marker.readOnly) {
  5421. sawReadOnlySpans = true;
  5422. if (doc.history.done.length || doc.history.undone.length)
  5423. doc.clearHistory();
  5424. }
  5425. if (marker.collapsed) {
  5426. marker.id = ++nextMarkerId;
  5427. marker.atomic = true;
  5428. }
  5429. if (cm) {
  5430. // Sync editor state
  5431. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5432. if (marker.collapsed)
  5433. regChange(cm, from.line, to.line + 1);
  5434. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5435. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5436. if (marker.atomic) reCheckSelection(cm.doc);
  5437. signalLater(cm, "markerAdded", cm, marker);
  5438. }
  5439. return marker;
  5440. }
  5441. // SHARED TEXTMARKERS
  5442. // A shared marker spans multiple linked documents. It is
  5443. // implemented as a meta-marker-object controlling multiple normal
  5444. // markers.
  5445. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5446. this.markers = markers;
  5447. this.primary = primary;
  5448. for (var i = 0; i < markers.length; ++i)
  5449. markers[i].parent = this;
  5450. };
  5451. eventMixin(SharedTextMarker);
  5452. SharedTextMarker.prototype.clear = function() {
  5453. if (this.explicitlyCleared) return;
  5454. this.explicitlyCleared = true;
  5455. for (var i = 0; i < this.markers.length; ++i)
  5456. this.markers[i].clear();
  5457. signalLater(this, "clear");
  5458. };
  5459. SharedTextMarker.prototype.find = function(side, lineObj) {
  5460. return this.primary.find(side, lineObj);
  5461. };
  5462. function markTextShared(doc, from, to, options, type) {
  5463. options = copyObj(options);
  5464. options.shared = false;
  5465. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5466. var widget = options.widgetNode;
  5467. linkedDocs(doc, function(doc) {
  5468. if (widget) options.widgetNode = widget.cloneNode(true);
  5469. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5470. for (var i = 0; i < doc.linked.length; ++i)
  5471. if (doc.linked[i].isParent) return;
  5472. primary = lst(markers);
  5473. });
  5474. return new SharedTextMarker(markers, primary);
  5475. }
  5476. function findSharedMarkers(doc) {
  5477. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5478. function(m) { return m.parent; });
  5479. }
  5480. function copySharedMarkers(doc, markers) {
  5481. for (var i = 0; i < markers.length; i++) {
  5482. var marker = markers[i], pos = marker.find();
  5483. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5484. if (cmp(mFrom, mTo)) {
  5485. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5486. marker.markers.push(subMark);
  5487. subMark.parent = marker;
  5488. }
  5489. }
  5490. }
  5491. function detachSharedMarkers(markers) {
  5492. for (var i = 0; i < markers.length; i++) {
  5493. var marker = markers[i], linked = [marker.primary.doc];;
  5494. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5495. for (var j = 0; j < marker.markers.length; j++) {
  5496. var subMarker = marker.markers[j];
  5497. if (indexOf(linked, subMarker.doc) == -1) {
  5498. subMarker.parent = null;
  5499. marker.markers.splice(j--, 1);
  5500. }
  5501. }
  5502. }
  5503. }
  5504. // TEXTMARKER SPANS
  5505. function MarkedSpan(marker, from, to) {
  5506. this.marker = marker;
  5507. this.from = from; this.to = to;
  5508. }
  5509. // Search an array of spans for a span matching the given marker.
  5510. function getMarkedSpanFor(spans, marker) {
  5511. if (spans) for (var i = 0; i < spans.length; ++i) {
  5512. var span = spans[i];
  5513. if (span.marker == marker) return span;
  5514. }
  5515. }
  5516. // Remove a span from an array, returning undefined if no spans are
  5517. // left (we don't store arrays for lines without spans).
  5518. function removeMarkedSpan(spans, span) {
  5519. for (var r, i = 0; i < spans.length; ++i)
  5520. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5521. return r;
  5522. }
  5523. // Add a span to a line.
  5524. function addMarkedSpan(line, span) {
  5525. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5526. span.marker.attachLine(line);
  5527. }
  5528. // Used for the algorithm that adjusts markers for a change in the
  5529. // document. These functions cut an array of spans at a given
  5530. // character position, returning an array of remaining chunks (or
  5531. // undefined if nothing remains).
  5532. function markedSpansBefore(old, startCh, isInsert) {
  5533. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5534. var span = old[i], marker = span.marker;
  5535. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5536. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5537. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5538. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5539. }
  5540. }
  5541. return nw;
  5542. }
  5543. function markedSpansAfter(old, endCh, isInsert) {
  5544. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5545. var span = old[i], marker = span.marker;
  5546. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5547. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5548. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5549. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5550. span.to == null ? null : span.to - endCh));
  5551. }
  5552. }
  5553. return nw;
  5554. }
  5555. // Given a change object, compute the new set of marker spans that
  5556. // cover the line in which the change took place. Removes spans
  5557. // entirely within the change, reconnects spans belonging to the
  5558. // same marker that appear on both sides of the change, and cuts off
  5559. // spans partially within the change. Returns an array of span
  5560. // arrays with one element for each line in (after) the change.
  5561. function stretchSpansOverChange(doc, change) {
  5562. if (change.full) return null;
  5563. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5564. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5565. if (!oldFirst && !oldLast) return null;
  5566. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5567. // Get the spans that 'stick out' on both sides
  5568. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5569. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5570. // Next, merge those two ends
  5571. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5572. if (first) {
  5573. // Fix up .to properties of first
  5574. for (var i = 0; i < first.length; ++i) {
  5575. var span = first[i];
  5576. if (span.to == null) {
  5577. var found = getMarkedSpanFor(last, span.marker);
  5578. if (!found) span.to = startCh;
  5579. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5580. }
  5581. }
  5582. }
  5583. if (last) {
  5584. // Fix up .from in last (or move them into first in case of sameLine)
  5585. for (var i = 0; i < last.length; ++i) {
  5586. var span = last[i];
  5587. if (span.to != null) span.to += offset;
  5588. if (span.from == null) {
  5589. var found = getMarkedSpanFor(first, span.marker);
  5590. if (!found) {
  5591. span.from = offset;
  5592. if (sameLine) (first || (first = [])).push(span);
  5593. }
  5594. } else {
  5595. span.from += offset;
  5596. if (sameLine) (first || (first = [])).push(span);
  5597. }
  5598. }
  5599. }
  5600. // Make sure we didn't create any zero-length spans
  5601. if (first) first = clearEmptySpans(first);
  5602. if (last && last != first) last = clearEmptySpans(last);
  5603. var newMarkers = [first];
  5604. if (!sameLine) {
  5605. // Fill gap with whole-line-spans
  5606. var gap = change.text.length - 2, gapMarkers;
  5607. if (gap > 0 && first)
  5608. for (var i = 0; i < first.length; ++i)
  5609. if (first[i].to == null)
  5610. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5611. for (var i = 0; i < gap; ++i)
  5612. newMarkers.push(gapMarkers);
  5613. newMarkers.push(last);
  5614. }
  5615. return newMarkers;
  5616. }
  5617. // Remove spans that are empty and don't have a clearWhenEmpty
  5618. // option of false.
  5619. function clearEmptySpans(spans) {
  5620. for (var i = 0; i < spans.length; ++i) {
  5621. var span = spans[i];
  5622. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5623. spans.splice(i--, 1);
  5624. }
  5625. if (!spans.length) return null;
  5626. return spans;
  5627. }
  5628. // Used for un/re-doing changes from the history. Combines the
  5629. // result of computing the existing spans with the set of spans that
  5630. // existed in the history (so that deleting around a span and then
  5631. // undoing brings back the span).
  5632. function mergeOldSpans(doc, change) {
  5633. var old = getOldSpans(doc, change);
  5634. var stretched = stretchSpansOverChange(doc, change);
  5635. if (!old) return stretched;
  5636. if (!stretched) return old;
  5637. for (var i = 0; i < old.length; ++i) {
  5638. var oldCur = old[i], stretchCur = stretched[i];
  5639. if (oldCur && stretchCur) {
  5640. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5641. var span = stretchCur[j];
  5642. for (var k = 0; k < oldCur.length; ++k)
  5643. if (oldCur[k].marker == span.marker) continue spans;
  5644. oldCur.push(span);
  5645. }
  5646. } else if (stretchCur) {
  5647. old[i] = stretchCur;
  5648. }
  5649. }
  5650. return old;
  5651. }
  5652. // Used to 'clip' out readOnly ranges when making a change.
  5653. function removeReadOnlyRanges(doc, from, to) {
  5654. var markers = null;
  5655. doc.iter(from.line, to.line + 1, function(line) {
  5656. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5657. var mark = line.markedSpans[i].marker;
  5658. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5659. (markers || (markers = [])).push(mark);
  5660. }
  5661. });
  5662. if (!markers) return null;
  5663. var parts = [{from: from, to: to}];
  5664. for (var i = 0; i < markers.length; ++i) {
  5665. var mk = markers[i], m = mk.find(0);
  5666. for (var j = 0; j < parts.length; ++j) {
  5667. var p = parts[j];
  5668. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5669. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5670. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5671. newParts.push({from: p.from, to: m.from});
  5672. if (dto > 0 || !mk.inclusiveRight && !dto)
  5673. newParts.push({from: m.to, to: p.to});
  5674. parts.splice.apply(parts, newParts);
  5675. j += newParts.length - 1;
  5676. }
  5677. }
  5678. return parts;
  5679. }
  5680. // Connect or disconnect spans from a line.
  5681. function detachMarkedSpans(line) {
  5682. var spans = line.markedSpans;
  5683. if (!spans) return;
  5684. for (var i = 0; i < spans.length; ++i)
  5685. spans[i].marker.detachLine(line);
  5686. line.markedSpans = null;
  5687. }
  5688. function attachMarkedSpans(line, spans) {
  5689. if (!spans) return;
  5690. for (var i = 0; i < spans.length; ++i)
  5691. spans[i].marker.attachLine(line);
  5692. line.markedSpans = spans;
  5693. }
  5694. // Helpers used when computing which overlapping collapsed span
  5695. // counts as the larger one.
  5696. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5697. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5698. // Returns a number indicating which of two overlapping collapsed
  5699. // spans is larger (and thus includes the other). Falls back to
  5700. // comparing ids when the spans cover exactly the same range.
  5701. function compareCollapsedMarkers(a, b) {
  5702. var lenDiff = a.lines.length - b.lines.length;
  5703. if (lenDiff != 0) return lenDiff;
  5704. var aPos = a.find(), bPos = b.find();
  5705. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5706. if (fromCmp) return -fromCmp;
  5707. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5708. if (toCmp) return toCmp;
  5709. return b.id - a.id;
  5710. }
  5711. // Find out whether a line ends or starts in a collapsed span. If
  5712. // so, return the marker for that span.
  5713. function collapsedSpanAtSide(line, start) {
  5714. var sps = sawCollapsedSpans && line.markedSpans, found;
  5715. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5716. sp = sps[i];
  5717. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5718. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5719. found = sp.marker;
  5720. }
  5721. return found;
  5722. }
  5723. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5724. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5725. // Test whether there exists a collapsed span that partially
  5726. // overlaps (covers the start or end, but not both) of a new span.
  5727. // Such overlap is not allowed.
  5728. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5729. var line = getLine(doc, lineNo);
  5730. var sps = sawCollapsedSpans && line.markedSpans;
  5731. if (sps) for (var i = 0; i < sps.length; ++i) {
  5732. var sp = sps[i];
  5733. if (!sp.marker.collapsed) continue;
  5734. var found = sp.marker.find(0);
  5735. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5736. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5737. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5738. if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
  5739. fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
  5740. return true;
  5741. }
  5742. }
  5743. // A visual line is a line as drawn on the screen. Folding, for
  5744. // example, can cause multiple logical lines to appear on the same
  5745. // visual line. This finds the start of the visual line that the
  5746. // given line is part of (usually that is the line itself).
  5747. function visualLine(line) {
  5748. var merged;
  5749. while (merged = collapsedSpanAtStart(line))
  5750. line = merged.find(-1, true).line;
  5751. return line;
  5752. }
  5753. // Returns an array of logical lines that continue the visual line
  5754. // started by the argument, or undefined if there are no such lines.
  5755. function visualLineContinued(line) {
  5756. var merged, lines;
  5757. while (merged = collapsedSpanAtEnd(line)) {
  5758. line = merged.find(1, true).line;
  5759. (lines || (lines = [])).push(line);
  5760. }
  5761. return lines;
  5762. }
  5763. // Get the line number of the start of the visual line that the
  5764. // given line number is part of.
  5765. function visualLineNo(doc, lineN) {
  5766. var line = getLine(doc, lineN), vis = visualLine(line);
  5767. if (line == vis) return lineN;
  5768. return lineNo(vis);
  5769. }
  5770. // Get the line number of the start of the next visual line after
  5771. // the given line.
  5772. function visualLineEndNo(doc, lineN) {
  5773. if (lineN > doc.lastLine()) return lineN;
  5774. var line = getLine(doc, lineN), merged;
  5775. if (!lineIsHidden(doc, line)) return lineN;
  5776. while (merged = collapsedSpanAtEnd(line))
  5777. line = merged.find(1, true).line;
  5778. return lineNo(line) + 1;
  5779. }
  5780. // Compute whether a line is hidden. Lines count as hidden when they
  5781. // are part of a visual line that starts with another line, or when
  5782. // they are entirely covered by collapsed, non-widget span.
  5783. function lineIsHidden(doc, line) {
  5784. var sps = sawCollapsedSpans && line.markedSpans;
  5785. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5786. sp = sps[i];
  5787. if (!sp.marker.collapsed) continue;
  5788. if (sp.from == null) return true;
  5789. if (sp.marker.widgetNode) continue;
  5790. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5791. return true;
  5792. }
  5793. }
  5794. function lineIsHiddenInner(doc, line, span) {
  5795. if (span.to == null) {
  5796. var end = span.marker.find(1, true);
  5797. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5798. }
  5799. if (span.marker.inclusiveRight && span.to == line.text.length)
  5800. return true;
  5801. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5802. sp = line.markedSpans[i];
  5803. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5804. (sp.to == null || sp.to != span.from) &&
  5805. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5806. lineIsHiddenInner(doc, line, sp)) return true;
  5807. }
  5808. }
  5809. // LINE WIDGETS
  5810. // Line widgets are block elements displayed above or below a line.
  5811. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
  5812. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  5813. this[opt] = options[opt];
  5814. this.cm = cm;
  5815. this.node = node;
  5816. };
  5817. eventMixin(LineWidget);
  5818. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5819. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5820. addToScrollPos(cm, null, diff);
  5821. }
  5822. LineWidget.prototype.clear = function() {
  5823. var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5824. if (no == null || !ws) return;
  5825. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  5826. if (!ws.length) line.widgets = null;
  5827. var height = widgetHeight(this);
  5828. runInOp(cm, function() {
  5829. adjustScrollWhenAboveVisible(cm, line, -height);
  5830. regLineChange(cm, no, "widget");
  5831. updateLineHeight(line, Math.max(0, line.height - height));
  5832. });
  5833. };
  5834. LineWidget.prototype.changed = function() {
  5835. var oldH = this.height, cm = this.cm, line = this.line;
  5836. this.height = null;
  5837. var diff = widgetHeight(this) - oldH;
  5838. if (!diff) return;
  5839. runInOp(cm, function() {
  5840. cm.curOp.forceUpdate = true;
  5841. adjustScrollWhenAboveVisible(cm, line, diff);
  5842. updateLineHeight(line, line.height + diff);
  5843. });
  5844. };
  5845. function widgetHeight(widget) {
  5846. if (widget.height != null) return widget.height;
  5847. if (!contains(document.body, widget.node)) {
  5848. var parentStyle = "position: relative;";
  5849. if (widget.coverGutter)
  5850. parentStyle += "margin-left: -" + widget.cm.display.gutters.offsetWidth + "px;";
  5851. if (widget.noHScroll)
  5852. parentStyle += "width: " + widget.cm.display.wrapper.clientWidth + "px;";
  5853. removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, parentStyle));
  5854. }
  5855. return widget.height = widget.node.offsetHeight;
  5856. }
  5857. function addLineWidget(cm, handle, node, options) {
  5858. var widget = new LineWidget(cm, node, options);
  5859. if (widget.noHScroll) cm.display.alignWidgets = true;
  5860. changeLine(cm.doc, handle, "widget", function(line) {
  5861. var widgets = line.widgets || (line.widgets = []);
  5862. if (widget.insertAt == null) widgets.push(widget);
  5863. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5864. widget.line = line;
  5865. if (!lineIsHidden(cm.doc, line)) {
  5866. var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
  5867. updateLineHeight(line, line.height + widgetHeight(widget));
  5868. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5869. cm.curOp.forceUpdate = true;
  5870. }
  5871. return true;
  5872. });
  5873. return widget;
  5874. }
  5875. // LINE DATA STRUCTURE
  5876. // Line objects. These hold state related to a line, including
  5877. // highlighting info (the styles array).
  5878. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  5879. this.text = text;
  5880. attachMarkedSpans(this, markedSpans);
  5881. this.height = estimateHeight ? estimateHeight(this) : 1;
  5882. };
  5883. eventMixin(Line);
  5884. Line.prototype.lineNo = function() { return lineNo(this); };
  5885. // Change the content (text, markers) of a line. Automatically
  5886. // invalidates cached information and tries to re-estimate the
  5887. // line's height.
  5888. function updateLine(line, text, markedSpans, estimateHeight) {
  5889. line.text = text;
  5890. if (line.stateAfter) line.stateAfter = null;
  5891. if (line.styles) line.styles = null;
  5892. if (line.order != null) line.order = null;
  5893. detachMarkedSpans(line);
  5894. attachMarkedSpans(line, markedSpans);
  5895. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  5896. if (estHeight != line.height) updateLineHeight(line, estHeight);
  5897. }
  5898. // Detach a line from the document tree and its markers.
  5899. function cleanUpLine(line) {
  5900. line.parent = null;
  5901. detachMarkedSpans(line);
  5902. }
  5903. function extractLineClasses(type, output) {
  5904. if (type) for (;;) {
  5905. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  5906. if (!lineClass) break;
  5907. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  5908. var prop = lineClass[1] ? "bgClass" : "textClass";
  5909. if (output[prop] == null)
  5910. output[prop] = lineClass[2];
  5911. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  5912. output[prop] += " " + lineClass[2];
  5913. }
  5914. return type;
  5915. }
  5916. function callBlankLine(mode, state) {
  5917. if (mode.blankLine) return mode.blankLine(state);
  5918. if (!mode.innerMode) return;
  5919. var inner = CodeMirror.innerMode(mode, state);
  5920. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  5921. }
  5922. function readToken(mode, stream, state, inner) {
  5923. for (var i = 0; i < 10; i++) {
  5924. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  5925. var style = mode.token(stream, state);
  5926. if (stream.pos > stream.start) return style;
  5927. }
  5928. throw new Error("Mode " + mode.name + " failed to advance stream.");
  5929. }
  5930. // Utility for getTokenAt and getLineTokens
  5931. function takeToken(cm, pos, precise, asArray) {
  5932. function getObj(copy) {
  5933. return {start: stream.start, end: stream.pos,
  5934. string: stream.current(),
  5935. type: style || null,
  5936. state: copy ? copyState(doc.mode, state) : state};
  5937. }
  5938. var doc = cm.doc, mode = doc.mode, style;
  5939. pos = clipPos(doc, pos);
  5940. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  5941. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  5942. if (asArray) tokens = [];
  5943. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  5944. stream.start = stream.pos;
  5945. style = readToken(mode, stream, state);
  5946. if (asArray) tokens.push(getObj(true));
  5947. }
  5948. return asArray ? tokens : getObj();
  5949. }
  5950. // Run the given mode's parser over a line, calling f for each token.
  5951. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  5952. var flattenSpans = mode.flattenSpans;
  5953. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  5954. var curStart = 0, curStyle = null;
  5955. var stream = new StringStream(text, cm.options.tabSize), style;
  5956. var inner = cm.options.addModeClass && [null];
  5957. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  5958. while (!stream.eol()) {
  5959. if (stream.pos > cm.options.maxHighlightLength) {
  5960. flattenSpans = false;
  5961. if (forceToEnd) processLine(cm, text, state, stream.pos);
  5962. stream.pos = text.length;
  5963. style = null;
  5964. } else {
  5965. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  5966. }
  5967. if (inner) {
  5968. var mName = inner[0].name;
  5969. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  5970. }
  5971. if (!flattenSpans || curStyle != style) {
  5972. while (curStart < stream.start) {
  5973. curStart = Math.min(stream.start, curStart + 50000);
  5974. f(curStart, curStyle);
  5975. }
  5976. curStyle = style;
  5977. }
  5978. stream.start = stream.pos;
  5979. }
  5980. while (curStart < stream.pos) {
  5981. // Webkit seems to refuse to render text nodes longer than 57444 characters
  5982. var pos = Math.min(stream.pos, curStart + 50000);
  5983. f(pos, curStyle);
  5984. curStart = pos;
  5985. }
  5986. }
  5987. // Compute a style array (an array starting with a mode generation
  5988. // -- for invalidation -- followed by pairs of end positions and
  5989. // style strings), which is used to highlight the tokens on the
  5990. // line.
  5991. function highlightLine(cm, line, state, forceToEnd) {
  5992. // A styles array always starts with a number identifying the
  5993. // mode/overlays that it is based on (for easy invalidation).
  5994. var st = [cm.state.modeGen], lineClasses = {};
  5995. // Compute the base array of styles
  5996. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  5997. st.push(end, style);
  5998. }, lineClasses, forceToEnd);
  5999. // Run overlays, adjust style array.
  6000. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6001. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6002. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6003. var start = i;
  6004. // Ensure there's a token end at the current position, and that i points at it
  6005. while (at < end) {
  6006. var i_end = st[i];
  6007. if (i_end > end)
  6008. st.splice(i, 1, end, st[i+1], i_end);
  6009. i += 2;
  6010. at = Math.min(end, i_end);
  6011. }
  6012. if (!style) return;
  6013. if (overlay.opaque) {
  6014. st.splice(start, i - start, end, "cm-overlay " + style);
  6015. i = start + 2;
  6016. } else {
  6017. for (; start < i; start += 2) {
  6018. var cur = st[start+1];
  6019. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6020. }
  6021. }
  6022. }, lineClasses);
  6023. }
  6024. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6025. }
  6026. function getLineStyles(cm, line, updateFrontier) {
  6027. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6028. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  6029. line.styles = result.styles;
  6030. if (result.classes) line.styleClasses = result.classes;
  6031. else if (line.styleClasses) line.styleClasses = null;
  6032. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6033. }
  6034. return line.styles;
  6035. }
  6036. // Lightweight form of highlight -- proceed over this line and
  6037. // update state, but don't save a style array. Used for lines that
  6038. // aren't currently visible.
  6039. function processLine(cm, text, state, startAt) {
  6040. var mode = cm.doc.mode;
  6041. var stream = new StringStream(text, cm.options.tabSize);
  6042. stream.start = stream.pos = startAt || 0;
  6043. if (text == "") callBlankLine(mode, state);
  6044. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  6045. readToken(mode, stream, state);
  6046. stream.start = stream.pos;
  6047. }
  6048. }
  6049. // Convert a style as returned by a mode (either null, or a string
  6050. // containing one or more styles) to a CSS style. This is cached,
  6051. // and also looks for line-wide styles.
  6052. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6053. function interpretTokenStyle(style, options) {
  6054. if (!style || /^\s*$/.test(style)) return null;
  6055. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6056. return cache[style] ||
  6057. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6058. }
  6059. // Render the DOM representation of the text of a line. Also builds
  6060. // up a 'line map', which points at the DOM nodes that represent
  6061. // specific stretches of text, and is used by the measuring code.
  6062. // The returned object contains the DOM node, this map, and
  6063. // information about line-wide styles that were set by the mode.
  6064. function buildLineContent(cm, lineView) {
  6065. // The padding-right forces the element to have a 'border', which
  6066. // is needed on Webkit to be able to get line-level bounding
  6067. // rectangles for it (in measureChar).
  6068. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6069. var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
  6070. lineView.measure = {};
  6071. // Iterate over the logical lines that make up this visual line.
  6072. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6073. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6074. builder.pos = 0;
  6075. builder.addToken = buildToken;
  6076. // Optionally wire in some hacks into the token-rendering
  6077. // algorithm, to deal with browser quirks.
  6078. if ((ie || webkit) && cm.getOption("lineWrapping"))
  6079. builder.addToken = buildTokenSplitSpaces(builder.addToken);
  6080. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6081. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6082. builder.map = [];
  6083. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6084. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6085. if (line.styleClasses) {
  6086. if (line.styleClasses.bgClass)
  6087. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6088. if (line.styleClasses.textClass)
  6089. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6090. }
  6091. // Ensure at least a single node is present, for measuring.
  6092. if (builder.map.length == 0)
  6093. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6094. // Store the map and a cache object for the current logical line
  6095. if (i == 0) {
  6096. lineView.measure.map = builder.map;
  6097. lineView.measure.cache = {};
  6098. } else {
  6099. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6100. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6101. }
  6102. }
  6103. // See issue #2901
  6104. if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
  6105. builder.content.className = "cm-tab-wrap-hack";
  6106. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6107. if (builder.pre.className)
  6108. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6109. return builder;
  6110. }
  6111. function defaultSpecialCharPlaceholder(ch) {
  6112. var token = elt("span", "\u2022", "cm-invalidchar");
  6113. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6114. token.setAttribute("aria-label", token.title);
  6115. return token;
  6116. }
  6117. // Build up the DOM representation for a single token, and add it to
  6118. // the line map. Takes care to render special characters separately.
  6119. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6120. if (!text) return;
  6121. var special = builder.cm.options.specialChars, mustWrap = false;
  6122. if (!special.test(text)) {
  6123. builder.col += text.length;
  6124. var content = document.createTextNode(text);
  6125. builder.map.push(builder.pos, builder.pos + text.length, content);
  6126. if (ie && ie_version < 9) mustWrap = true;
  6127. builder.pos += text.length;
  6128. } else {
  6129. var content = document.createDocumentFragment(), pos = 0;
  6130. while (true) {
  6131. special.lastIndex = pos;
  6132. var m = special.exec(text);
  6133. var skipped = m ? m.index - pos : text.length - pos;
  6134. if (skipped) {
  6135. var txt = document.createTextNode(text.slice(pos, pos + skipped));
  6136. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6137. else content.appendChild(txt);
  6138. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6139. builder.col += skipped;
  6140. builder.pos += skipped;
  6141. }
  6142. if (!m) break;
  6143. pos += skipped + 1;
  6144. if (m[0] == "\t") {
  6145. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6146. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6147. txt.setAttribute("role", "presentation");
  6148. txt.setAttribute("cm-text", "\t");
  6149. builder.col += tabWidth;
  6150. } else {
  6151. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6152. txt.setAttribute("cm-text", m[0]);
  6153. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6154. else content.appendChild(txt);
  6155. builder.col += 1;
  6156. }
  6157. builder.map.push(builder.pos, builder.pos + 1, txt);
  6158. builder.pos++;
  6159. }
  6160. }
  6161. if (style || startStyle || endStyle || mustWrap || css) {
  6162. var fullStyle = style || "";
  6163. if (startStyle) fullStyle += startStyle;
  6164. if (endStyle) fullStyle += endStyle;
  6165. var token = elt("span", [content], fullStyle, css);
  6166. if (title) token.title = title;
  6167. return builder.content.appendChild(token);
  6168. }
  6169. builder.content.appendChild(content);
  6170. }
  6171. function buildTokenSplitSpaces(inner) {
  6172. function split(old) {
  6173. var out = " ";
  6174. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6175. out += " ";
  6176. return out;
  6177. }
  6178. return function(builder, text, style, startStyle, endStyle, title) {
  6179. inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
  6180. };
  6181. }
  6182. // Work around nonsense dimensions being reported for stretches of
  6183. // right-to-left text.
  6184. function buildTokenBadBidi(inner, order) {
  6185. return function(builder, text, style, startStyle, endStyle, title) {
  6186. style = style ? style + " cm-force-border" : "cm-force-border";
  6187. var start = builder.pos, end = start + text.length;
  6188. for (;;) {
  6189. // Find the part that overlaps with the start of this text
  6190. for (var i = 0; i < order.length; i++) {
  6191. var part = order[i];
  6192. if (part.to > start && part.from <= start) break;
  6193. }
  6194. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
  6195. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
  6196. startStyle = null;
  6197. text = text.slice(part.to - start);
  6198. start = part.to;
  6199. }
  6200. };
  6201. }
  6202. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6203. var widget = !ignoreWidget && marker.widgetNode;
  6204. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6205. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6206. if (!widget)
  6207. widget = builder.content.appendChild(document.createElement("span"));
  6208. widget.setAttribute("cm-marker", marker.id);
  6209. }
  6210. if (widget) {
  6211. builder.cm.display.input.setUneditable(widget);
  6212. builder.content.appendChild(widget);
  6213. }
  6214. builder.pos += size;
  6215. }
  6216. // Outputs a number of spans to make up a line, taking highlighting
  6217. // and marked text into account.
  6218. function insertLineContent(line, builder, styles) {
  6219. var spans = line.markedSpans, allText = line.text, at = 0;
  6220. if (!spans) {
  6221. for (var i = 1; i < styles.length; i+=2)
  6222. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6223. return;
  6224. }
  6225. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6226. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6227. for (;;) {
  6228. if (nextChange == pos) { // Update current marker set
  6229. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6230. collapsed = null; nextChange = Infinity;
  6231. var foundBookmarks = [];
  6232. for (var j = 0; j < spans.length; ++j) {
  6233. var sp = spans[j], m = sp.marker;
  6234. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  6235. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  6236. if (m.className) spanStyle += " " + m.className;
  6237. if (m.css) css = m.css;
  6238. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6239. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  6240. if (m.title && !title) title = m.title;
  6241. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6242. collapsed = sp;
  6243. } else if (sp.from > pos && nextChange > sp.from) {
  6244. nextChange = sp.from;
  6245. }
  6246. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
  6247. }
  6248. if (collapsed && (collapsed.from || 0) == pos) {
  6249. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6250. collapsed.marker, collapsed.from == null);
  6251. if (collapsed.to == null) return;
  6252. }
  6253. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  6254. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6255. }
  6256. if (pos >= len) break;
  6257. var upto = Math.min(len, nextChange);
  6258. while (true) {
  6259. if (text) {
  6260. var end = pos + text.length;
  6261. if (!collapsed) {
  6262. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6263. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6264. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6265. }
  6266. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6267. pos = end;
  6268. spanStartStyle = "";
  6269. }
  6270. text = allText.slice(at, at = styles[i++]);
  6271. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6272. }
  6273. }
  6274. }
  6275. // DOCUMENT DATA STRUCTURE
  6276. // By default, updates that start and end at the beginning of a line
  6277. // are treated specially, in order to make the association of line
  6278. // widgets and marker elements with the text behave more intuitive.
  6279. function isWholeLineUpdate(doc, change) {
  6280. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6281. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6282. }
  6283. // Perform a change on the document data structure.
  6284. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6285. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6286. function update(line, text, spans) {
  6287. updateLine(line, text, spans, estimateHeight);
  6288. signalLater(line, "change", line, change);
  6289. }
  6290. function linesFor(start, end) {
  6291. for (var i = start, result = []; i < end; ++i)
  6292. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6293. return result;
  6294. }
  6295. var from = change.from, to = change.to, text = change.text;
  6296. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6297. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6298. // Adjust the line structure
  6299. if (change.full) {
  6300. doc.insert(0, linesFor(0, text.length));
  6301. doc.remove(text.length, doc.size - text.length);
  6302. } else if (isWholeLineUpdate(doc, change)) {
  6303. // This is a whole-line replace. Treated specially to make
  6304. // sure line objects move the way they are supposed to.
  6305. var added = linesFor(0, text.length - 1);
  6306. update(lastLine, lastLine.text, lastSpans);
  6307. if (nlines) doc.remove(from.line, nlines);
  6308. if (added.length) doc.insert(from.line, added);
  6309. } else if (firstLine == lastLine) {
  6310. if (text.length == 1) {
  6311. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6312. } else {
  6313. var added = linesFor(1, text.length - 1);
  6314. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6315. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6316. doc.insert(from.line + 1, added);
  6317. }
  6318. } else if (text.length == 1) {
  6319. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6320. doc.remove(from.line + 1, nlines);
  6321. } else {
  6322. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6323. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6324. var added = linesFor(1, text.length - 1);
  6325. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6326. doc.insert(from.line + 1, added);
  6327. }
  6328. signalLater(doc, "change", doc, change);
  6329. }
  6330. // The document is represented as a BTree consisting of leaves, with
  6331. // chunk of lines in them, and branches, with up to ten leaves or
  6332. // other branch nodes below them. The top node is always a branch
  6333. // node, and is the document object itself (meaning it has
  6334. // additional methods and properties).
  6335. //
  6336. // All nodes have parent links. The tree is used both to go from
  6337. // line numbers to line objects, and to go from objects to numbers.
  6338. // It also indexes by height, and is used to convert between height
  6339. // and line object, and to find the total height of the document.
  6340. //
  6341. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6342. function LeafChunk(lines) {
  6343. this.lines = lines;
  6344. this.parent = null;
  6345. for (var i = 0, height = 0; i < lines.length; ++i) {
  6346. lines[i].parent = this;
  6347. height += lines[i].height;
  6348. }
  6349. this.height = height;
  6350. }
  6351. LeafChunk.prototype = {
  6352. chunkSize: function() { return this.lines.length; },
  6353. // Remove the n lines at offset 'at'.
  6354. removeInner: function(at, n) {
  6355. for (var i = at, e = at + n; i < e; ++i) {
  6356. var line = this.lines[i];
  6357. this.height -= line.height;
  6358. cleanUpLine(line);
  6359. signalLater(line, "delete");
  6360. }
  6361. this.lines.splice(at, n);
  6362. },
  6363. // Helper used to collapse a small branch into a single leaf.
  6364. collapse: function(lines) {
  6365. lines.push.apply(lines, this.lines);
  6366. },
  6367. // Insert the given array of lines at offset 'at', count them as
  6368. // having the given height.
  6369. insertInner: function(at, lines, height) {
  6370. this.height += height;
  6371. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6372. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6373. },
  6374. // Used to iterate over a part of the tree.
  6375. iterN: function(at, n, op) {
  6376. for (var e = at + n; at < e; ++at)
  6377. if (op(this.lines[at])) return true;
  6378. }
  6379. };
  6380. function BranchChunk(children) {
  6381. this.children = children;
  6382. var size = 0, height = 0;
  6383. for (var i = 0; i < children.length; ++i) {
  6384. var ch = children[i];
  6385. size += ch.chunkSize(); height += ch.height;
  6386. ch.parent = this;
  6387. }
  6388. this.size = size;
  6389. this.height = height;
  6390. this.parent = null;
  6391. }
  6392. BranchChunk.prototype = {
  6393. chunkSize: function() { return this.size; },
  6394. removeInner: function(at, n) {
  6395. this.size -= n;
  6396. for (var i = 0; i < this.children.length; ++i) {
  6397. var child = this.children[i], sz = child.chunkSize();
  6398. if (at < sz) {
  6399. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6400. child.removeInner(at, rm);
  6401. this.height -= oldHeight - child.height;
  6402. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6403. if ((n -= rm) == 0) break;
  6404. at = 0;
  6405. } else at -= sz;
  6406. }
  6407. // If the result is smaller than 25 lines, ensure that it is a
  6408. // single leaf node.
  6409. if (this.size - n < 25 &&
  6410. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6411. var lines = [];
  6412. this.collapse(lines);
  6413. this.children = [new LeafChunk(lines)];
  6414. this.children[0].parent = this;
  6415. }
  6416. },
  6417. collapse: function(lines) {
  6418. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6419. },
  6420. insertInner: function(at, lines, height) {
  6421. this.size += lines.length;
  6422. this.height += height;
  6423. for (var i = 0; i < this.children.length; ++i) {
  6424. var child = this.children[i], sz = child.chunkSize();
  6425. if (at <= sz) {
  6426. child.insertInner(at, lines, height);
  6427. if (child.lines && child.lines.length > 50) {
  6428. while (child.lines.length > 50) {
  6429. var spilled = child.lines.splice(child.lines.length - 25, 25);
  6430. var newleaf = new LeafChunk(spilled);
  6431. child.height -= newleaf.height;
  6432. this.children.splice(i + 1, 0, newleaf);
  6433. newleaf.parent = this;
  6434. }
  6435. this.maybeSpill();
  6436. }
  6437. break;
  6438. }
  6439. at -= sz;
  6440. }
  6441. },
  6442. // When a node has grown, check whether it should be split.
  6443. maybeSpill: function() {
  6444. if (this.children.length <= 10) return;
  6445. var me = this;
  6446. do {
  6447. var spilled = me.children.splice(me.children.length - 5, 5);
  6448. var sibling = new BranchChunk(spilled);
  6449. if (!me.parent) { // Become the parent node
  6450. var copy = new BranchChunk(me.children);
  6451. copy.parent = me;
  6452. me.children = [copy, sibling];
  6453. me = copy;
  6454. } else {
  6455. me.size -= sibling.size;
  6456. me.height -= sibling.height;
  6457. var myIndex = indexOf(me.parent.children, me);
  6458. me.parent.children.splice(myIndex + 1, 0, sibling);
  6459. }
  6460. sibling.parent = me.parent;
  6461. } while (me.children.length > 10);
  6462. me.parent.maybeSpill();
  6463. },
  6464. iterN: function(at, n, op) {
  6465. for (var i = 0; i < this.children.length; ++i) {
  6466. var child = this.children[i], sz = child.chunkSize();
  6467. if (at < sz) {
  6468. var used = Math.min(n, sz - at);
  6469. if (child.iterN(at, used, op)) return true;
  6470. if ((n -= used) == 0) break;
  6471. at = 0;
  6472. } else at -= sz;
  6473. }
  6474. }
  6475. };
  6476. var nextDocId = 0;
  6477. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  6478. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  6479. if (firstLine == null) firstLine = 0;
  6480. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6481. this.first = firstLine;
  6482. this.scrollTop = this.scrollLeft = 0;
  6483. this.cantEdit = false;
  6484. this.cleanGeneration = 1;
  6485. this.frontier = firstLine;
  6486. var start = Pos(firstLine, 0);
  6487. this.sel = simpleSelection(start);
  6488. this.history = new History(null);
  6489. this.id = ++nextDocId;
  6490. this.modeOption = mode;
  6491. if (typeof text == "string") text = splitLines(text);
  6492. updateDoc(this, {from: start, to: start, text: text});
  6493. setSelection(this, simpleSelection(start), sel_dontScroll);
  6494. };
  6495. Doc.prototype = createObj(BranchChunk.prototype, {
  6496. constructor: Doc,
  6497. // Iterate over the document. Supports two forms -- with only one
  6498. // argument, it calls that for each line in the document. With
  6499. // three, it iterates over the range given by the first two (with
  6500. // the second being non-inclusive).
  6501. iter: function(from, to, op) {
  6502. if (op) this.iterN(from - this.first, to - from, op);
  6503. else this.iterN(this.first, this.first + this.size, from);
  6504. },
  6505. // Non-public interface for adding and removing lines.
  6506. insert: function(at, lines) {
  6507. var height = 0;
  6508. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6509. this.insertInner(at - this.first, lines, height);
  6510. },
  6511. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6512. // From here, the methods are part of the public interface. Most
  6513. // are also available from CodeMirror (editor) instances.
  6514. getValue: function(lineSep) {
  6515. var lines = getLines(this, this.first, this.first + this.size);
  6516. if (lineSep === false) return lines;
  6517. return lines.join(lineSep || "\n");
  6518. },
  6519. setValue: docMethodOp(function(code) {
  6520. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6521. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6522. text: splitLines(code), origin: "setValue", full: true}, true);
  6523. setSelection(this, simpleSelection(top));
  6524. }),
  6525. replaceRange: function(code, from, to, origin) {
  6526. from = clipPos(this, from);
  6527. to = to ? clipPos(this, to) : from;
  6528. replaceRange(this, code, from, to, origin);
  6529. },
  6530. getRange: function(from, to, lineSep) {
  6531. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6532. if (lineSep === false) return lines;
  6533. return lines.join(lineSep || "\n");
  6534. },
  6535. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6536. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6537. getLineNumber: function(line) {return lineNo(line);},
  6538. getLineHandleVisualStart: function(line) {
  6539. if (typeof line == "number") line = getLine(this, line);
  6540. return visualLine(line);
  6541. },
  6542. lineCount: function() {return this.size;},
  6543. firstLine: function() {return this.first;},
  6544. lastLine: function() {return this.first + this.size - 1;},
  6545. clipPos: function(pos) {return clipPos(this, pos);},
  6546. getCursor: function(start) {
  6547. var range = this.sel.primary(), pos;
  6548. if (start == null || start == "head") pos = range.head;
  6549. else if (start == "anchor") pos = range.anchor;
  6550. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6551. else pos = range.from();
  6552. return pos;
  6553. },
  6554. listSelections: function() { return this.sel.ranges; },
  6555. somethingSelected: function() {return this.sel.somethingSelected();},
  6556. setCursor: docMethodOp(function(line, ch, options) {
  6557. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6558. }),
  6559. setSelection: docMethodOp(function(anchor, head, options) {
  6560. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6561. }),
  6562. extendSelection: docMethodOp(function(head, other, options) {
  6563. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6564. }),
  6565. extendSelections: docMethodOp(function(heads, options) {
  6566. extendSelections(this, clipPosArray(this, heads, options));
  6567. }),
  6568. extendSelectionsBy: docMethodOp(function(f, options) {
  6569. extendSelections(this, map(this.sel.ranges, f), options);
  6570. }),
  6571. setSelections: docMethodOp(function(ranges, primary, options) {
  6572. if (!ranges.length) return;
  6573. for (var i = 0, out = []; i < ranges.length; i++)
  6574. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6575. clipPos(this, ranges[i].head));
  6576. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6577. setSelection(this, normalizeSelection(out, primary), options);
  6578. }),
  6579. addSelection: docMethodOp(function(anchor, head, options) {
  6580. var ranges = this.sel.ranges.slice(0);
  6581. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6582. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6583. }),
  6584. getSelection: function(lineSep) {
  6585. var ranges = this.sel.ranges, lines;
  6586. for (var i = 0; i < ranges.length; i++) {
  6587. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6588. lines = lines ? lines.concat(sel) : sel;
  6589. }
  6590. if (lineSep === false) return lines;
  6591. else return lines.join(lineSep || "\n");
  6592. },
  6593. getSelections: function(lineSep) {
  6594. var parts = [], ranges = this.sel.ranges;
  6595. for (var i = 0; i < ranges.length; i++) {
  6596. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6597. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  6598. parts[i] = sel;
  6599. }
  6600. return parts;
  6601. },
  6602. replaceSelection: function(code, collapse, origin) {
  6603. var dup = [];
  6604. for (var i = 0; i < this.sel.ranges.length; i++)
  6605. dup[i] = code;
  6606. this.replaceSelections(dup, collapse, origin || "+input");
  6607. },
  6608. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6609. var changes = [], sel = this.sel;
  6610. for (var i = 0; i < sel.ranges.length; i++) {
  6611. var range = sel.ranges[i];
  6612. changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
  6613. }
  6614. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6615. for (var i = changes.length - 1; i >= 0; i--)
  6616. makeChange(this, changes[i]);
  6617. if (newSel) setSelectionReplaceHistory(this, newSel);
  6618. else if (this.cm) ensureCursorVisible(this.cm);
  6619. }),
  6620. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6621. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6622. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6623. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6624. setExtending: function(val) {this.extend = val;},
  6625. getExtending: function() {return this.extend;},
  6626. historySize: function() {
  6627. var hist = this.history, done = 0, undone = 0;
  6628. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6629. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6630. return {undo: done, redo: undone};
  6631. },
  6632. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6633. markClean: function() {
  6634. this.cleanGeneration = this.changeGeneration(true);
  6635. },
  6636. changeGeneration: function(forceSplit) {
  6637. if (forceSplit)
  6638. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6639. return this.history.generation;
  6640. },
  6641. isClean: function (gen) {
  6642. return this.history.generation == (gen || this.cleanGeneration);
  6643. },
  6644. getHistory: function() {
  6645. return {done: copyHistoryArray(this.history.done),
  6646. undone: copyHistoryArray(this.history.undone)};
  6647. },
  6648. setHistory: function(histData) {
  6649. var hist = this.history = new History(this.history.maxGeneration);
  6650. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6651. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6652. },
  6653. addLineClass: docMethodOp(function(handle, where, cls) {
  6654. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6655. var prop = where == "text" ? "textClass"
  6656. : where == "background" ? "bgClass"
  6657. : where == "gutter" ? "gutterClass" : "wrapClass";
  6658. if (!line[prop]) line[prop] = cls;
  6659. else if (classTest(cls).test(line[prop])) return false;
  6660. else line[prop] += " " + cls;
  6661. return true;
  6662. });
  6663. }),
  6664. removeLineClass: docMethodOp(function(handle, where, cls) {
  6665. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6666. var prop = where == "text" ? "textClass"
  6667. : where == "background" ? "bgClass"
  6668. : where == "gutter" ? "gutterClass" : "wrapClass";
  6669. var cur = line[prop];
  6670. if (!cur) return false;
  6671. else if (cls == null) line[prop] = null;
  6672. else {
  6673. var found = cur.match(classTest(cls));
  6674. if (!found) return false;
  6675. var end = found.index + found[0].length;
  6676. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6677. }
  6678. return true;
  6679. });
  6680. }),
  6681. markText: function(from, to, options) {
  6682. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  6683. },
  6684. setBookmark: function(pos, options) {
  6685. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6686. insertLeft: options && options.insertLeft,
  6687. clearWhenEmpty: false, shared: options && options.shared};
  6688. pos = clipPos(this, pos);
  6689. return markText(this, pos, pos, realOpts, "bookmark");
  6690. },
  6691. findMarksAt: function(pos) {
  6692. pos = clipPos(this, pos);
  6693. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6694. if (spans) for (var i = 0; i < spans.length; ++i) {
  6695. var span = spans[i];
  6696. if ((span.from == null || span.from <= pos.ch) &&
  6697. (span.to == null || span.to >= pos.ch))
  6698. markers.push(span.marker.parent || span.marker);
  6699. }
  6700. return markers;
  6701. },
  6702. findMarks: function(from, to, filter) {
  6703. from = clipPos(this, from); to = clipPos(this, to);
  6704. var found = [], lineNo = from.line;
  6705. this.iter(from.line, to.line + 1, function(line) {
  6706. var spans = line.markedSpans;
  6707. if (spans) for (var i = 0; i < spans.length; i++) {
  6708. var span = spans[i];
  6709. if (!(lineNo == from.line && from.ch > span.to ||
  6710. span.from == null && lineNo != from.line||
  6711. lineNo == to.line && span.from > to.ch) &&
  6712. (!filter || filter(span.marker)))
  6713. found.push(span.marker.parent || span.marker);
  6714. }
  6715. ++lineNo;
  6716. });
  6717. return found;
  6718. },
  6719. getAllMarks: function() {
  6720. var markers = [];
  6721. this.iter(function(line) {
  6722. var sps = line.markedSpans;
  6723. if (sps) for (var i = 0; i < sps.length; ++i)
  6724. if (sps[i].from != null) markers.push(sps[i].marker);
  6725. });
  6726. return markers;
  6727. },
  6728. posFromIndex: function(off) {
  6729. var ch, lineNo = this.first;
  6730. this.iter(function(line) {
  6731. var sz = line.text.length + 1;
  6732. if (sz > off) { ch = off; return true; }
  6733. off -= sz;
  6734. ++lineNo;
  6735. });
  6736. return clipPos(this, Pos(lineNo, ch));
  6737. },
  6738. indexFromPos: function (coords) {
  6739. coords = clipPos(this, coords);
  6740. var index = coords.ch;
  6741. if (coords.line < this.first || coords.ch < 0) return 0;
  6742. this.iter(this.first, coords.line, function (line) {
  6743. index += line.text.length + 1;
  6744. });
  6745. return index;
  6746. },
  6747. copy: function(copyHistory) {
  6748. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  6749. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6750. doc.sel = this.sel;
  6751. doc.extend = false;
  6752. if (copyHistory) {
  6753. doc.history.undoDepth = this.history.undoDepth;
  6754. doc.setHistory(this.getHistory());
  6755. }
  6756. return doc;
  6757. },
  6758. linkedDoc: function(options) {
  6759. if (!options) options = {};
  6760. var from = this.first, to = this.first + this.size;
  6761. if (options.from != null && options.from > from) from = options.from;
  6762. if (options.to != null && options.to < to) to = options.to;
  6763. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  6764. if (options.sharedHist) copy.history = this.history;
  6765. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6766. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6767. copySharedMarkers(copy, findSharedMarkers(this));
  6768. return copy;
  6769. },
  6770. unlinkDoc: function(other) {
  6771. if (other instanceof CodeMirror) other = other.doc;
  6772. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6773. var link = this.linked[i];
  6774. if (link.doc != other) continue;
  6775. this.linked.splice(i, 1);
  6776. other.unlinkDoc(this);
  6777. detachSharedMarkers(findSharedMarkers(this));
  6778. break;
  6779. }
  6780. // If the histories were shared, split them again
  6781. if (other.history == this.history) {
  6782. var splitIds = [other.id];
  6783. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  6784. other.history = new History(null);
  6785. other.history.done = copyHistoryArray(this.history.done, splitIds);
  6786. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  6787. }
  6788. },
  6789. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  6790. getMode: function() {return this.mode;},
  6791. getEditor: function() {return this.cm;}
  6792. });
  6793. // Public alias.
  6794. Doc.prototype.eachLine = Doc.prototype.iter;
  6795. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  6796. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  6797. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  6798. CodeMirror.prototype[prop] = (function(method) {
  6799. return function() {return method.apply(this.doc, arguments);};
  6800. })(Doc.prototype[prop]);
  6801. eventMixin(Doc);
  6802. // Call f for all linked documents.
  6803. function linkedDocs(doc, f, sharedHistOnly) {
  6804. function propagate(doc, skip, sharedHist) {
  6805. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  6806. var rel = doc.linked[i];
  6807. if (rel.doc == skip) continue;
  6808. var shared = sharedHist && rel.sharedHist;
  6809. if (sharedHistOnly && !shared) continue;
  6810. f(rel.doc, shared);
  6811. propagate(rel.doc, doc, shared);
  6812. }
  6813. }
  6814. propagate(doc, null, true);
  6815. }
  6816. // Attach a document to an editor.
  6817. function attachDoc(cm, doc) {
  6818. if (doc.cm) throw new Error("This document is already in use.");
  6819. cm.doc = doc;
  6820. doc.cm = cm;
  6821. estimateLineHeights(cm);
  6822. loadMode(cm);
  6823. if (!cm.options.lineWrapping) findMaxLine(cm);
  6824. cm.options.mode = doc.modeOption;
  6825. regChange(cm);
  6826. }
  6827. // LINE UTILITIES
  6828. // Find the line object corresponding to the given line number.
  6829. function getLine(doc, n) {
  6830. n -= doc.first;
  6831. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  6832. for (var chunk = doc; !chunk.lines;) {
  6833. for (var i = 0;; ++i) {
  6834. var child = chunk.children[i], sz = child.chunkSize();
  6835. if (n < sz) { chunk = child; break; }
  6836. n -= sz;
  6837. }
  6838. }
  6839. return chunk.lines[n];
  6840. }
  6841. // Get the part of a document between two positions, as an array of
  6842. // strings.
  6843. function getBetween(doc, start, end) {
  6844. var out = [], n = start.line;
  6845. doc.iter(start.line, end.line + 1, function(line) {
  6846. var text = line.text;
  6847. if (n == end.line) text = text.slice(0, end.ch);
  6848. if (n == start.line) text = text.slice(start.ch);
  6849. out.push(text);
  6850. ++n;
  6851. });
  6852. return out;
  6853. }
  6854. // Get the lines between from and to, as array of strings.
  6855. function getLines(doc, from, to) {
  6856. var out = [];
  6857. doc.iter(from, to, function(line) { out.push(line.text); });
  6858. return out;
  6859. }
  6860. // Update the height of a line, propagating the height change
  6861. // upwards to parent nodes.
  6862. function updateLineHeight(line, height) {
  6863. var diff = height - line.height;
  6864. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  6865. }
  6866. // Given a line object, find its line number by walking up through
  6867. // its parent links.
  6868. function lineNo(line) {
  6869. if (line.parent == null) return null;
  6870. var cur = line.parent, no = indexOf(cur.lines, line);
  6871. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6872. for (var i = 0;; ++i) {
  6873. if (chunk.children[i] == cur) break;
  6874. no += chunk.children[i].chunkSize();
  6875. }
  6876. }
  6877. return no + cur.first;
  6878. }
  6879. // Find the line at the given vertical position, using the height
  6880. // information in the document tree.
  6881. function lineAtHeight(chunk, h) {
  6882. var n = chunk.first;
  6883. outer: do {
  6884. for (var i = 0; i < chunk.children.length; ++i) {
  6885. var child = chunk.children[i], ch = child.height;
  6886. if (h < ch) { chunk = child; continue outer; }
  6887. h -= ch;
  6888. n += child.chunkSize();
  6889. }
  6890. return n;
  6891. } while (!chunk.lines);
  6892. for (var i = 0; i < chunk.lines.length; ++i) {
  6893. var line = chunk.lines[i], lh = line.height;
  6894. if (h < lh) break;
  6895. h -= lh;
  6896. }
  6897. return n + i;
  6898. }
  6899. // Find the height above the given line.
  6900. function heightAtLine(lineObj) {
  6901. lineObj = visualLine(lineObj);
  6902. var h = 0, chunk = lineObj.parent;
  6903. for (var i = 0; i < chunk.lines.length; ++i) {
  6904. var line = chunk.lines[i];
  6905. if (line == lineObj) break;
  6906. else h += line.height;
  6907. }
  6908. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  6909. for (var i = 0; i < p.children.length; ++i) {
  6910. var cur = p.children[i];
  6911. if (cur == chunk) break;
  6912. else h += cur.height;
  6913. }
  6914. }
  6915. return h;
  6916. }
  6917. // Get the bidi ordering for the given line (and cache it). Returns
  6918. // false for lines that are fully left-to-right, and an array of
  6919. // BidiSpan objects otherwise.
  6920. function getOrder(line) {
  6921. var order = line.order;
  6922. if (order == null) order = line.order = bidiOrdering(line.text);
  6923. return order;
  6924. }
  6925. // HISTORY
  6926. function History(startGen) {
  6927. // Arrays of change events and selections. Doing something adds an
  6928. // event to done and clears undo. Undoing moves events from done
  6929. // to undone, redoing moves them in the other direction.
  6930. this.done = []; this.undone = [];
  6931. this.undoDepth = Infinity;
  6932. // Used to track when changes can be merged into a single undo
  6933. // event
  6934. this.lastModTime = this.lastSelTime = 0;
  6935. this.lastOp = this.lastSelOp = null;
  6936. this.lastOrigin = this.lastSelOrigin = null;
  6937. // Used by the isClean() method
  6938. this.generation = this.maxGeneration = startGen || 1;
  6939. }
  6940. // Create a history change event from an updateDoc-style change
  6941. // object.
  6942. function historyChangeFromChange(doc, change) {
  6943. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6944. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6945. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  6946. return histChange;
  6947. }
  6948. // Pop all selection events off the end of a history array. Stop at
  6949. // a change event.
  6950. function clearSelectionEvents(array) {
  6951. while (array.length) {
  6952. var last = lst(array);
  6953. if (last.ranges) array.pop();
  6954. else break;
  6955. }
  6956. }
  6957. // Find the top change event in the history. Pop off selection
  6958. // events that are in the way.
  6959. function lastChangeEvent(hist, force) {
  6960. if (force) {
  6961. clearSelectionEvents(hist.done);
  6962. return lst(hist.done);
  6963. } else if (hist.done.length && !lst(hist.done).ranges) {
  6964. return lst(hist.done);
  6965. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  6966. hist.done.pop();
  6967. return lst(hist.done);
  6968. }
  6969. }
  6970. // Register a change in the history. Merges changes that are within
  6971. // a single operation, ore are close together with an origin that
  6972. // allows merging (starting with "+") into a single event.
  6973. function addChangeToHistory(doc, change, selAfter, opId) {
  6974. var hist = doc.history;
  6975. hist.undone.length = 0;
  6976. var time = +new Date, cur;
  6977. if ((hist.lastOp == opId ||
  6978. hist.lastOrigin == change.origin && change.origin &&
  6979. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  6980. change.origin.charAt(0) == "*")) &&
  6981. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  6982. // Merge this change into the last event
  6983. var last = lst(cur.changes);
  6984. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  6985. // Optimized case for simple insertion -- don't want to add
  6986. // new changesets for every character typed
  6987. last.to = changeEnd(change);
  6988. } else {
  6989. // Add new sub-event
  6990. cur.changes.push(historyChangeFromChange(doc, change));
  6991. }
  6992. } else {
  6993. // Can not be merged, start a new event.
  6994. var before = lst(hist.done);
  6995. if (!before || !before.ranges)
  6996. pushSelectionToHistory(doc.sel, hist.done);
  6997. cur = {changes: [historyChangeFromChange(doc, change)],
  6998. generation: hist.generation};
  6999. hist.done.push(cur);
  7000. while (hist.done.length > hist.undoDepth) {
  7001. hist.done.shift();
  7002. if (!hist.done[0].ranges) hist.done.shift();
  7003. }
  7004. }
  7005. hist.done.push(selAfter);
  7006. hist.generation = ++hist.maxGeneration;
  7007. hist.lastModTime = hist.lastSelTime = time;
  7008. hist.lastOp = hist.lastSelOp = opId;
  7009. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7010. if (!last) signal(doc, "historyAdded");
  7011. }
  7012. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7013. var ch = origin.charAt(0);
  7014. return ch == "*" ||
  7015. ch == "+" &&
  7016. prev.ranges.length == sel.ranges.length &&
  7017. prev.somethingSelected() == sel.somethingSelected() &&
  7018. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7019. }
  7020. // Called whenever the selection changes, sets the new selection as
  7021. // the pending selection in the history, and pushes the old pending
  7022. // selection into the 'done' array when it was significantly
  7023. // different (in number of selected ranges, emptiness, or time).
  7024. function addSelectionToHistory(doc, sel, opId, options) {
  7025. var hist = doc.history, origin = options && options.origin;
  7026. // A new event is started when the previous origin does not match
  7027. // the current, or the origins don't allow matching. Origins
  7028. // starting with * are always merged, those starting with + are
  7029. // merged when similar and close together in time.
  7030. if (opId == hist.lastSelOp ||
  7031. (origin && hist.lastSelOrigin == origin &&
  7032. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7033. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7034. hist.done[hist.done.length - 1] = sel;
  7035. else
  7036. pushSelectionToHistory(sel, hist.done);
  7037. hist.lastSelTime = +new Date;
  7038. hist.lastSelOrigin = origin;
  7039. hist.lastSelOp = opId;
  7040. if (options && options.clearRedo !== false)
  7041. clearSelectionEvents(hist.undone);
  7042. }
  7043. function pushSelectionToHistory(sel, dest) {
  7044. var top = lst(dest);
  7045. if (!(top && top.ranges && top.equals(sel)))
  7046. dest.push(sel);
  7047. }
  7048. // Used to store marked span information in the history.
  7049. function attachLocalSpans(doc, change, from, to) {
  7050. var existing = change["spans_" + doc.id], n = 0;
  7051. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7052. if (line.markedSpans)
  7053. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7054. ++n;
  7055. });
  7056. }
  7057. // When un/re-doing restores text containing marked spans, those
  7058. // that have been explicitly cleared should not be restored.
  7059. function removeClearedSpans(spans) {
  7060. if (!spans) return null;
  7061. for (var i = 0, out; i < spans.length; ++i) {
  7062. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7063. else if (out) out.push(spans[i]);
  7064. }
  7065. return !out ? spans : out.length ? out : null;
  7066. }
  7067. // Retrieve and filter the old marked spans stored in a change event.
  7068. function getOldSpans(doc, change) {
  7069. var found = change["spans_" + doc.id];
  7070. if (!found) return null;
  7071. for (var i = 0, nw = []; i < change.text.length; ++i)
  7072. nw.push(removeClearedSpans(found[i]));
  7073. return nw;
  7074. }
  7075. // Used both to provide a JSON-safe object in .getHistory, and, when
  7076. // detaching a document, to split the history in two
  7077. function copyHistoryArray(events, newGroup, instantiateSel) {
  7078. for (var i = 0, copy = []; i < events.length; ++i) {
  7079. var event = events[i];
  7080. if (event.ranges) {
  7081. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7082. continue;
  7083. }
  7084. var changes = event.changes, newChanges = [];
  7085. copy.push({changes: newChanges});
  7086. for (var j = 0; j < changes.length; ++j) {
  7087. var change = changes[j], m;
  7088. newChanges.push({from: change.from, to: change.to, text: change.text});
  7089. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7090. if (indexOf(newGroup, Number(m[1])) > -1) {
  7091. lst(newChanges)[prop] = change[prop];
  7092. delete change[prop];
  7093. }
  7094. }
  7095. }
  7096. }
  7097. return copy;
  7098. }
  7099. // Rebasing/resetting history to deal with externally-sourced changes
  7100. function rebaseHistSelSingle(pos, from, to, diff) {
  7101. if (to < pos.line) {
  7102. pos.line += diff;
  7103. } else if (from < pos.line) {
  7104. pos.line = from;
  7105. pos.ch = 0;
  7106. }
  7107. }
  7108. // Tries to rebase an array of history events given a change in the
  7109. // document. If the change touches the same lines as the event, the
  7110. // event, and everything 'behind' it, is discarded. If the change is
  7111. // before the event, the event's positions are updated. Uses a
  7112. // copy-on-write scheme for the positions, to avoid having to
  7113. // reallocate them all on every rebase, but also avoid problems with
  7114. // shared position objects being unsafely updated.
  7115. function rebaseHistArray(array, from, to, diff) {
  7116. for (var i = 0; i < array.length; ++i) {
  7117. var sub = array[i], ok = true;
  7118. if (sub.ranges) {
  7119. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7120. for (var j = 0; j < sub.ranges.length; j++) {
  7121. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7122. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7123. }
  7124. continue;
  7125. }
  7126. for (var j = 0; j < sub.changes.length; ++j) {
  7127. var cur = sub.changes[j];
  7128. if (to < cur.from.line) {
  7129. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7130. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7131. } else if (from <= cur.to.line) {
  7132. ok = false;
  7133. break;
  7134. }
  7135. }
  7136. if (!ok) {
  7137. array.splice(0, i + 1);
  7138. i = 0;
  7139. }
  7140. }
  7141. }
  7142. function rebaseHist(hist, change) {
  7143. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7144. rebaseHistArray(hist.done, from, to, diff);
  7145. rebaseHistArray(hist.undone, from, to, diff);
  7146. }
  7147. // EVENT UTILITIES
  7148. // Due to the fact that we still support jurassic IE versions, some
  7149. // compatibility wrappers are needed.
  7150. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7151. if (e.preventDefault) e.preventDefault();
  7152. else e.returnValue = false;
  7153. };
  7154. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7155. if (e.stopPropagation) e.stopPropagation();
  7156. else e.cancelBubble = true;
  7157. };
  7158. function e_defaultPrevented(e) {
  7159. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7160. }
  7161. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7162. function e_target(e) {return e.target || e.srcElement;}
  7163. function e_button(e) {
  7164. var b = e.which;
  7165. if (b == null) {
  7166. if (e.button & 1) b = 1;
  7167. else if (e.button & 2) b = 3;
  7168. else if (e.button & 4) b = 2;
  7169. }
  7170. if (mac && e.ctrlKey && b == 1) b = 3;
  7171. return b;
  7172. }
  7173. // EVENT HANDLING
  7174. // Lightweight event framework. on/off also work on DOM nodes,
  7175. // registering native DOM handlers.
  7176. var on = CodeMirror.on = function(emitter, type, f) {
  7177. if (emitter.addEventListener)
  7178. emitter.addEventListener(type, f, false);
  7179. else if (emitter.attachEvent)
  7180. emitter.attachEvent("on" + type, f);
  7181. else {
  7182. var map = emitter._handlers || (emitter._handlers = {});
  7183. var arr = map[type] || (map[type] = []);
  7184. arr.push(f);
  7185. }
  7186. };
  7187. var off = CodeMirror.off = function(emitter, type, f) {
  7188. if (emitter.removeEventListener)
  7189. emitter.removeEventListener(type, f, false);
  7190. else if (emitter.detachEvent)
  7191. emitter.detachEvent("on" + type, f);
  7192. else {
  7193. var arr = emitter._handlers && emitter._handlers[type];
  7194. if (!arr) return;
  7195. for (var i = 0; i < arr.length; ++i)
  7196. if (arr[i] == f) { arr.splice(i, 1); break; }
  7197. }
  7198. };
  7199. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7200. var arr = emitter._handlers && emitter._handlers[type];
  7201. if (!arr) return;
  7202. var args = Array.prototype.slice.call(arguments, 2);
  7203. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  7204. };
  7205. var orphanDelayedCallbacks = null;
  7206. // Often, we want to signal events at a point where we are in the
  7207. // middle of some work, but don't want the handler to start calling
  7208. // other methods on the editor, which might be in an inconsistent
  7209. // state or simply not expect any other events to happen.
  7210. // signalLater looks whether there are any handlers, and schedules
  7211. // them to be executed when the last operation ends, or, if no
  7212. // operation is active, when a timeout fires.
  7213. function signalLater(emitter, type /*, values...*/) {
  7214. var arr = emitter._handlers && emitter._handlers[type];
  7215. if (!arr) return;
  7216. var args = Array.prototype.slice.call(arguments, 2), list;
  7217. if (operationGroup) {
  7218. list = operationGroup.delayedCallbacks;
  7219. } else if (orphanDelayedCallbacks) {
  7220. list = orphanDelayedCallbacks;
  7221. } else {
  7222. list = orphanDelayedCallbacks = [];
  7223. setTimeout(fireOrphanDelayed, 0);
  7224. }
  7225. function bnd(f) {return function(){f.apply(null, args);};};
  7226. for (var i = 0; i < arr.length; ++i)
  7227. list.push(bnd(arr[i]));
  7228. }
  7229. function fireOrphanDelayed() {
  7230. var delayed = orphanDelayedCallbacks;
  7231. orphanDelayedCallbacks = null;
  7232. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7233. }
  7234. // The DOM events that CodeMirror handles can be overridden by
  7235. // registering a (non-DOM) handler on the editor for the event name,
  7236. // and preventDefault-ing the event in that handler.
  7237. function signalDOMEvent(cm, e, override) {
  7238. if (typeof e == "string")
  7239. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7240. signal(cm, override || e.type, cm, e);
  7241. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7242. }
  7243. function signalCursorActivity(cm) {
  7244. var arr = cm._handlers && cm._handlers.cursorActivity;
  7245. if (!arr) return;
  7246. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7247. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7248. set.push(arr[i]);
  7249. }
  7250. function hasHandler(emitter, type) {
  7251. var arr = emitter._handlers && emitter._handlers[type];
  7252. return arr && arr.length > 0;
  7253. }
  7254. // Add on and off methods to a constructor's prototype, to make
  7255. // registering events on such objects more convenient.
  7256. function eventMixin(ctor) {
  7257. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7258. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7259. }
  7260. // MISC UTILITIES
  7261. // Number of pixels added to scroller and sizer to hide scrollbar
  7262. var scrollerGap = 30;
  7263. // Returned or thrown by various protocols to signal 'I'm not
  7264. // handling this'.
  7265. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7266. // Reused option objects for setSelection & friends
  7267. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7268. function Delayed() {this.id = null;}
  7269. Delayed.prototype.set = function(ms, f) {
  7270. clearTimeout(this.id);
  7271. this.id = setTimeout(f, ms);
  7272. };
  7273. // Counts the column offset in a string, taking tabs into account.
  7274. // Used mostly to find indentation.
  7275. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7276. if (end == null) {
  7277. end = string.search(/[^\s\u00a0]/);
  7278. if (end == -1) end = string.length;
  7279. }
  7280. for (var i = startIndex || 0, n = startValue || 0;;) {
  7281. var nextTab = string.indexOf("\t", i);
  7282. if (nextTab < 0 || nextTab >= end)
  7283. return n + (end - i);
  7284. n += nextTab - i;
  7285. n += tabSize - (n % tabSize);
  7286. i = nextTab + 1;
  7287. }
  7288. };
  7289. // The inverse of countColumn -- find the offset that corresponds to
  7290. // a particular column.
  7291. function findColumn(string, goal, tabSize) {
  7292. for (var pos = 0, col = 0;;) {
  7293. var nextTab = string.indexOf("\t", pos);
  7294. if (nextTab == -1) nextTab = string.length;
  7295. var skipped = nextTab - pos;
  7296. if (nextTab == string.length || col + skipped >= goal)
  7297. return pos + Math.min(skipped, goal - col);
  7298. col += nextTab - pos;
  7299. col += tabSize - (col % tabSize);
  7300. pos = nextTab + 1;
  7301. if (col >= goal) return pos;
  7302. }
  7303. }
  7304. var spaceStrs = [""];
  7305. function spaceStr(n) {
  7306. while (spaceStrs.length <= n)
  7307. spaceStrs.push(lst(spaceStrs) + " ");
  7308. return spaceStrs[n];
  7309. }
  7310. function lst(arr) { return arr[arr.length-1]; }
  7311. var selectInput = function(node) { node.select(); };
  7312. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7313. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7314. else if (ie) // Suppress mysterious IE10 errors
  7315. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7316. function indexOf(array, elt) {
  7317. for (var i = 0; i < array.length; ++i)
  7318. if (array[i] == elt) return i;
  7319. return -1;
  7320. }
  7321. function map(array, f) {
  7322. var out = [];
  7323. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7324. return out;
  7325. }
  7326. function nothing() {}
  7327. function createObj(base, props) {
  7328. var inst;
  7329. if (Object.create) {
  7330. inst = Object.create(base);
  7331. } else {
  7332. nothing.prototype = base;
  7333. inst = new nothing();
  7334. }
  7335. if (props) copyObj(props, inst);
  7336. return inst;
  7337. };
  7338. function copyObj(obj, target, overwrite) {
  7339. if (!target) target = {};
  7340. for (var prop in obj)
  7341. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7342. target[prop] = obj[prop];
  7343. return target;
  7344. }
  7345. function bind(f) {
  7346. var args = Array.prototype.slice.call(arguments, 1);
  7347. return function(){return f.apply(null, args);};
  7348. }
  7349. var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7350. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7351. return /\w/.test(ch) || ch > "\x80" &&
  7352. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7353. };
  7354. function isWordChar(ch, helper) {
  7355. if (!helper) return isWordCharBasic(ch);
  7356. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7357. return helper.test(ch);
  7358. }
  7359. function isEmpty(obj) {
  7360. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7361. return true;
  7362. }
  7363. // Extending unicode characters. A series of a non-extending char +
  7364. // any number of extending chars is treated as a single unit as far
  7365. // as editing and measuring is concerned. This is not fully correct,
  7366. // since some scripts/fonts/browsers also treat other configurations
  7367. // of code points as a group.
  7368. 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]/;
  7369. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7370. // DOM UTILITIES
  7371. function elt(tag, content, className, style) {
  7372. var e = document.createElement(tag);
  7373. if (className) e.className = className;
  7374. if (style) e.style.cssText = style;
  7375. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7376. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7377. return e;
  7378. }
  7379. var range;
  7380. if (document.createRange) range = function(node, start, end, endNode) {
  7381. var r = document.createRange();
  7382. r.setEnd(endNode || node, end);
  7383. r.setStart(node, start);
  7384. return r;
  7385. };
  7386. else range = function(node, start, end) {
  7387. var r = document.body.createTextRange();
  7388. try { r.moveToElementText(node.parentNode); }
  7389. catch(e) { return r; }
  7390. r.collapse(true);
  7391. r.moveEnd("character", end);
  7392. r.moveStart("character", start);
  7393. return r;
  7394. };
  7395. function removeChildren(e) {
  7396. for (var count = e.childNodes.length; count > 0; --count)
  7397. e.removeChild(e.firstChild);
  7398. return e;
  7399. }
  7400. function removeChildrenAndAdd(parent, e) {
  7401. return removeChildren(parent).appendChild(e);
  7402. }
  7403. var contains = CodeMirror.contains = function(parent, child) {
  7404. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7405. child = child.parentNode;
  7406. if (parent.contains)
  7407. return parent.contains(child);
  7408. do {
  7409. if (child.nodeType == 11) child = child.host;
  7410. if (child == parent) return true;
  7411. } while (child = child.parentNode);
  7412. };
  7413. function activeElt() { return document.activeElement; }
  7414. // Older versions of IE throws unspecified error when touching
  7415. // document.activeElement in some cases (during loading, in iframe)
  7416. if (ie && ie_version < 11) activeElt = function() {
  7417. try { return document.activeElement; }
  7418. catch(e) { return document.body; }
  7419. };
  7420. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7421. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7422. var current = node.className;
  7423. var match = classTest(cls).exec(current);
  7424. if (match) {
  7425. var after = current.slice(match.index + match[0].length);
  7426. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7427. }
  7428. };
  7429. var addClass = CodeMirror.addClass = function(node, cls) {
  7430. var current = node.className;
  7431. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7432. };
  7433. function joinClasses(a, b) {
  7434. var as = a.split(" ");
  7435. for (var i = 0; i < as.length; i++)
  7436. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7437. return b;
  7438. }
  7439. // WINDOW-WIDE EVENTS
  7440. // These must be handled carefully, because naively registering a
  7441. // handler for each editor will cause the editors to never be
  7442. // garbage collected.
  7443. function forEachCodeMirror(f) {
  7444. if (!document.body.getElementsByClassName) return;
  7445. var byClass = document.body.getElementsByClassName("CodeMirror");
  7446. for (var i = 0; i < byClass.length; i++) {
  7447. var cm = byClass[i].CodeMirror;
  7448. if (cm) f(cm);
  7449. }
  7450. }
  7451. var globalsRegistered = false;
  7452. function ensureGlobalHandlers() {
  7453. if (globalsRegistered) return;
  7454. registerGlobalHandlers();
  7455. globalsRegistered = true;
  7456. }
  7457. function registerGlobalHandlers() {
  7458. // When the window resizes, we need to refresh active editors.
  7459. var resizeTimer;
  7460. on(window, "resize", function() {
  7461. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7462. resizeTimer = null;
  7463. forEachCodeMirror(onResize);
  7464. }, 100);
  7465. });
  7466. // When the window loses focus, we want to show the editor as blurred
  7467. on(window, "blur", function() {
  7468. forEachCodeMirror(onBlur);
  7469. });
  7470. }
  7471. // FEATURE DETECTION
  7472. // Detect drag-and-drop
  7473. var dragAndDrop = function() {
  7474. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7475. // couldn't get it to work yet.
  7476. if (ie && ie_version < 9) return false;
  7477. var div = elt('div');
  7478. return "draggable" in div || "dragDrop" in div;
  7479. }();
  7480. var zwspSupported;
  7481. function zeroWidthElement(measure) {
  7482. if (zwspSupported == null) {
  7483. var test = elt("span", "\u200b");
  7484. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7485. if (measure.firstChild.offsetHeight != 0)
  7486. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7487. }
  7488. var node = zwspSupported ? elt("span", "\u200b") :
  7489. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7490. node.setAttribute("cm-text", "");
  7491. return node;
  7492. }
  7493. // Feature-detect IE's crummy client rect reporting for bidi text
  7494. var badBidiRects;
  7495. function hasBadBidiRects(measure) {
  7496. if (badBidiRects != null) return badBidiRects;
  7497. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7498. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7499. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7500. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7501. return badBidiRects = (r1.right - r0.right < 3);
  7502. }
  7503. // See if "".split is the broken IE version, if so, provide an
  7504. // alternative way to split lines.
  7505. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7506. var pos = 0, result = [], l = string.length;
  7507. while (pos <= l) {
  7508. var nl = string.indexOf("\n", pos);
  7509. if (nl == -1) nl = string.length;
  7510. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7511. var rt = line.indexOf("\r");
  7512. if (rt != -1) {
  7513. result.push(line.slice(0, rt));
  7514. pos += rt + 1;
  7515. } else {
  7516. result.push(line);
  7517. pos = nl + 1;
  7518. }
  7519. }
  7520. return result;
  7521. } : function(string){return string.split(/\r\n?|\n/);};
  7522. var hasSelection = window.getSelection ? function(te) {
  7523. try { return te.selectionStart != te.selectionEnd; }
  7524. catch(e) { return false; }
  7525. } : function(te) {
  7526. try {var range = te.ownerDocument.selection.createRange();}
  7527. catch(e) {}
  7528. if (!range || range.parentElement() != te) return false;
  7529. return range.compareEndPoints("StartToEnd", range) != 0;
  7530. };
  7531. var hasCopyEvent = (function() {
  7532. var e = elt("div");
  7533. if ("oncopy" in e) return true;
  7534. e.setAttribute("oncopy", "return;");
  7535. return typeof e.oncopy == "function";
  7536. })();
  7537. var badZoomedRects = null;
  7538. function hasBadZoomedRects(measure) {
  7539. if (badZoomedRects != null) return badZoomedRects;
  7540. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7541. var normal = node.getBoundingClientRect();
  7542. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7543. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7544. }
  7545. // KEY NAMES
  7546. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7547. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7548. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7549. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  7550. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7551. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7552. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
  7553. CodeMirror.keyNames = keyNames;
  7554. (function() {
  7555. // Number keys
  7556. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7557. // Alphabetic keys
  7558. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7559. // Function keys
  7560. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7561. })();
  7562. // BIDI HELPERS
  7563. function iterateBidiSections(order, from, to, f) {
  7564. if (!order) return f(from, to, "ltr");
  7565. var found = false;
  7566. for (var i = 0; i < order.length; ++i) {
  7567. var part = order[i];
  7568. if (part.from < to && part.to > from || from == to && part.to == from) {
  7569. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7570. found = true;
  7571. }
  7572. }
  7573. if (!found) f(from, to, "ltr");
  7574. }
  7575. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7576. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7577. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7578. function lineRight(line) {
  7579. var order = getOrder(line);
  7580. if (!order) return line.text.length;
  7581. return bidiRight(lst(order));
  7582. }
  7583. function lineStart(cm, lineN) {
  7584. var line = getLine(cm.doc, lineN);
  7585. var visual = visualLine(line);
  7586. if (visual != line) lineN = lineNo(visual);
  7587. var order = getOrder(visual);
  7588. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7589. return Pos(lineN, ch);
  7590. }
  7591. function lineEnd(cm, lineN) {
  7592. var merged, line = getLine(cm.doc, lineN);
  7593. while (merged = collapsedSpanAtEnd(line)) {
  7594. line = merged.find(1, true).line;
  7595. lineN = null;
  7596. }
  7597. var order = getOrder(line);
  7598. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7599. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7600. }
  7601. function lineStartSmart(cm, pos) {
  7602. var start = lineStart(cm, pos.line);
  7603. var line = getLine(cm.doc, start.line);
  7604. var order = getOrder(line);
  7605. if (!order || order[0].level == 0) {
  7606. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7607. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7608. return Pos(start.line, inWS ? 0 : firstNonWS);
  7609. }
  7610. return start;
  7611. }
  7612. function compareBidiLevel(order, a, b) {
  7613. var linedir = order[0].level;
  7614. if (a == linedir) return true;
  7615. if (b == linedir) return false;
  7616. return a < b;
  7617. }
  7618. var bidiOther;
  7619. function getBidiPartAt(order, pos) {
  7620. bidiOther = null;
  7621. for (var i = 0, found; i < order.length; ++i) {
  7622. var cur = order[i];
  7623. if (cur.from < pos && cur.to > pos) return i;
  7624. if ((cur.from == pos || cur.to == pos)) {
  7625. if (found == null) {
  7626. found = i;
  7627. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7628. if (cur.from != cur.to) bidiOther = found;
  7629. return i;
  7630. } else {
  7631. if (cur.from != cur.to) bidiOther = i;
  7632. return found;
  7633. }
  7634. }
  7635. }
  7636. return found;
  7637. }
  7638. function moveInLine(line, pos, dir, byUnit) {
  7639. if (!byUnit) return pos + dir;
  7640. do pos += dir;
  7641. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7642. return pos;
  7643. }
  7644. // This is needed in order to move 'visually' through bi-directional
  7645. // text -- i.e., pressing left should make the cursor go left, even
  7646. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7647. // LTR text touch each other. This often requires the cursor offset
  7648. // to move more than one unit, in order to visually move one unit.
  7649. function moveVisually(line, start, dir, byUnit) {
  7650. var bidi = getOrder(line);
  7651. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7652. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7653. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7654. for (;;) {
  7655. if (target > part.from && target < part.to) return target;
  7656. if (target == part.from || target == part.to) {
  7657. if (getBidiPartAt(bidi, target) == pos) return target;
  7658. part = bidi[pos += dir];
  7659. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7660. } else {
  7661. part = bidi[pos += dir];
  7662. if (!part) return null;
  7663. if ((dir > 0) == part.level % 2)
  7664. target = moveInLine(line, part.to, -1, byUnit);
  7665. else
  7666. target = moveInLine(line, part.from, 1, byUnit);
  7667. }
  7668. }
  7669. }
  7670. function moveLogically(line, start, dir, byUnit) {
  7671. var target = start + dir;
  7672. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7673. return target < 0 || target > line.text.length ? null : target;
  7674. }
  7675. // Bidirectional ordering algorithm
  7676. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7677. // that this (partially) implements.
  7678. // One-char codes used for character types:
  7679. // L (L): Left-to-Right
  7680. // R (R): Right-to-Left
  7681. // r (AL): Right-to-Left Arabic
  7682. // 1 (EN): European Number
  7683. // + (ES): European Number Separator
  7684. // % (ET): European Number Terminator
  7685. // n (AN): Arabic Number
  7686. // , (CS): Common Number Separator
  7687. // m (NSM): Non-Spacing Mark
  7688. // b (BN): Boundary Neutral
  7689. // s (B): Paragraph Separator
  7690. // t (S): Segment Separator
  7691. // w (WS): Whitespace
  7692. // N (ON): Other Neutrals
  7693. // Returns null if characters are ordered as they appear
  7694. // (left-to-right), or an array of sections ({from, to, level}
  7695. // objects) in the order in which they occur visually.
  7696. var bidiOrdering = (function() {
  7697. // Character types for codepoints 0 to 0xff
  7698. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7699. // Character types for codepoints 0x600 to 0x6ff
  7700. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7701. function charType(code) {
  7702. if (code <= 0xf7) return lowTypes.charAt(code);
  7703. else if (0x590 <= code && code <= 0x5f4) return "R";
  7704. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7705. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7706. else if (0x2000 <= code && code <= 0x200b) return "w";
  7707. else if (code == 0x200c) return "b";
  7708. else return "L";
  7709. }
  7710. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7711. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7712. // Browsers seem to always treat the boundaries of block elements as being L.
  7713. var outerType = "L";
  7714. function BidiSpan(level, from, to) {
  7715. this.level = level;
  7716. this.from = from; this.to = to;
  7717. }
  7718. return function(str) {
  7719. if (!bidiRE.test(str)) return false;
  7720. var len = str.length, types = [];
  7721. for (var i = 0, type; i < len; ++i)
  7722. types.push(type = charType(str.charCodeAt(i)));
  7723. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7724. // change the type of the NSM to the type of the previous
  7725. // character. If the NSM is at the start of the level run, it will
  7726. // get the type of sor.
  7727. for (var i = 0, prev = outerType; i < len; ++i) {
  7728. var type = types[i];
  7729. if (type == "m") types[i] = prev;
  7730. else prev = type;
  7731. }
  7732. // W2. Search backwards from each instance of a European number
  7733. // until the first strong type (R, L, AL, or sor) is found. If an
  7734. // AL is found, change the type of the European number to Arabic
  7735. // number.
  7736. // W3. Change all ALs to R.
  7737. for (var i = 0, cur = outerType; i < len; ++i) {
  7738. var type = types[i];
  7739. if (type == "1" && cur == "r") types[i] = "n";
  7740. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7741. }
  7742. // W4. A single European separator between two European numbers
  7743. // changes to a European number. A single common separator between
  7744. // two numbers of the same type changes to that type.
  7745. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7746. var type = types[i];
  7747. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7748. else if (type == "," && prev == types[i+1] &&
  7749. (prev == "1" || prev == "n")) types[i] = prev;
  7750. prev = type;
  7751. }
  7752. // W5. A sequence of European terminators adjacent to European
  7753. // numbers changes to all European numbers.
  7754. // W6. Otherwise, separators and terminators change to Other
  7755. // Neutral.
  7756. for (var i = 0; i < len; ++i) {
  7757. var type = types[i];
  7758. if (type == ",") types[i] = "N";
  7759. else if (type == "%") {
  7760. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7761. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7762. for (var j = i; j < end; ++j) types[j] = replace;
  7763. i = end - 1;
  7764. }
  7765. }
  7766. // W7. Search backwards from each instance of a European number
  7767. // until the first strong type (R, L, or sor) is found. If an L is
  7768. // found, then change the type of the European number to L.
  7769. for (var i = 0, cur = outerType; i < len; ++i) {
  7770. var type = types[i];
  7771. if (cur == "L" && type == "1") types[i] = "L";
  7772. else if (isStrong.test(type)) cur = type;
  7773. }
  7774. // N1. A sequence of neutrals takes the direction of the
  7775. // surrounding strong text if the text on both sides has the same
  7776. // direction. European and Arabic numbers act as if they were R in
  7777. // terms of their influence on neutrals. Start-of-level-run (sor)
  7778. // and end-of-level-run (eor) are used at level run boundaries.
  7779. // N2. Any remaining neutrals take the embedding direction.
  7780. for (var i = 0; i < len; ++i) {
  7781. if (isNeutral.test(types[i])) {
  7782. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  7783. var before = (i ? types[i-1] : outerType) == "L";
  7784. var after = (end < len ? types[end] : outerType) == "L";
  7785. var replace = before || after ? "L" : "R";
  7786. for (var j = i; j < end; ++j) types[j] = replace;
  7787. i = end - 1;
  7788. }
  7789. }
  7790. // Here we depart from the documented algorithm, in order to avoid
  7791. // building up an actual levels array. Since there are only three
  7792. // levels (0, 1, 2) in an implementation that doesn't take
  7793. // explicit embedding into account, we can build up the order on
  7794. // the fly, without following the level-based algorithm.
  7795. var order = [], m;
  7796. for (var i = 0; i < len;) {
  7797. if (countsAsLeft.test(types[i])) {
  7798. var start = i;
  7799. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  7800. order.push(new BidiSpan(0, start, i));
  7801. } else {
  7802. var pos = i, at = order.length;
  7803. for (++i; i < len && types[i] != "L"; ++i) {}
  7804. for (var j = pos; j < i;) {
  7805. if (countsAsNum.test(types[j])) {
  7806. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  7807. var nstart = j;
  7808. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  7809. order.splice(at, 0, new BidiSpan(2, nstart, j));
  7810. pos = j;
  7811. } else ++j;
  7812. }
  7813. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  7814. }
  7815. }
  7816. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  7817. order[0].from = m[0].length;
  7818. order.unshift(new BidiSpan(0, 0, m[0].length));
  7819. }
  7820. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  7821. lst(order).to -= m[0].length;
  7822. order.push(new BidiSpan(0, len - m[0].length, len));
  7823. }
  7824. if (order[0].level != lst(order).level)
  7825. order.push(new BidiSpan(order[0].level, len, len));
  7826. return order;
  7827. };
  7828. })();
  7829. // THE END
  7830. CodeMirror.version = "5.0.0";
  7831. return CodeMirror;
  7832. });