codemirror.js 346 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function(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 || window).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 userAgent = navigator.userAgent;
  21. var platform = navigator.platform;
  22. var gecko = /gecko\/\d/i.test(userAgent);
  23. var ie_upto10 = /MSIE \d/.test(userAgent);
  24. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  25. var ie = ie_upto10 || ie_11up;
  26. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  27. var webkit = /WebKit\//.test(userAgent);
  28. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  29. var chrome = /Chrome\//.test(userAgent);
  30. var presto = /Opera\//.test(userAgent);
  31. var safari = /Apple Computer/.test(navigator.vendor);
  32. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  33. var phantom = /PhantomJS/.test(userAgent);
  34. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  35. // This is woefully incomplete. Suggestions for alternative methods welcome.
  36. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  37. var mac = ios || /Mac/.test(platform);
  38. var chromeOS = /\bCrOS\b/.test(userAgent);
  39. var windows = /win/i.test(platform);
  40. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  41. if (presto_version) presto_version = Number(presto_version[1]);
  42. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  43. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  44. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  45. var captureRightClick = gecko || (ie && ie_version >= 9);
  46. // Optimize some code when these features are not used.
  47. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  48. // EDITOR CONSTRUCTOR
  49. // A CodeMirror instance represents an editor. This is the object
  50. // that user code is usually dealing with.
  51. function CodeMirror(place, options) {
  52. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  53. this.options = options = options ? copyObj(options) : {};
  54. // Determine effective options based on given values and defaults.
  55. copyObj(defaults, options, false);
  56. setGuttersForLineNumbers(options);
  57. var doc = options.value;
  58. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  59. this.doc = doc;
  60. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  61. var display = this.display = new Display(place, doc, input);
  62. display.wrapper.CodeMirror = this;
  63. updateGutters(this);
  64. themeChanged(this);
  65. if (options.lineWrapping)
  66. this.display.wrapper.className += " CodeMirror-wrap";
  67. if (options.autofocus && !mobile) display.input.focus();
  68. initScrollbars(this);
  69. this.state = {
  70. keyMaps: [], // stores maps added by addKeyMap
  71. overlays: [], // highlighting overlays, as added by addOverlay
  72. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  73. overwrite: false,
  74. delayingBlurEvent: false,
  75. focused: false,
  76. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  77. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  78. selectingText: false,
  79. draggingText: false,
  80. highlight: new Delayed(), // stores highlight worker timeout
  81. keySeq: null, // Unfinished key sequence
  82. specialChars: null
  83. };
  84. var cm = this;
  85. // Override magic textarea content restore that IE sometimes does
  86. // on our hidden textarea on reload
  87. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  88. registerEventHandlers(this);
  89. ensureGlobalHandlers();
  90. startOperation(this);
  91. this.curOp.forceUpdate = true;
  92. attachDoc(this, doc);
  93. if ((options.autofocus && !mobile) || cm.hasFocus())
  94. setTimeout(bind(onFocus, this), 20);
  95. else
  96. onBlur(this);
  97. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  98. optionHandlers[opt](this, options[opt], Init);
  99. maybeUpdateLineNumberWidth(this);
  100. if (options.finishInit) options.finishInit(this);
  101. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  102. endOperation(this);
  103. // Suppress optimizelegibility in Webkit, since it breaks text
  104. // measuring on line wrapping boundaries.
  105. if (webkit && options.lineWrapping &&
  106. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  107. display.lineDiv.style.textRendering = "auto";
  108. }
  109. // DISPLAY CONSTRUCTOR
  110. // The display handles the DOM integration, both for input reading
  111. // and content drawing. It holds references to DOM nodes and
  112. // display-related state.
  113. function Display(place, doc, input) {
  114. var d = this;
  115. this.input = input;
  116. // Covers bottom-right square when both scrollbars are present.
  117. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  118. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  119. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  120. // and h scrollbar is present.
  121. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  122. d.gutterFiller.setAttribute("cm-not-content", "true");
  123. // Will contain the actual code, positioned to cover the viewport.
  124. d.lineDiv = elt("div", null, "CodeMirror-code");
  125. // Elements are added to these to represent selection and cursors.
  126. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  127. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  128. // A visibility: hidden element used to find the size of things.
  129. d.measure = elt("div", null, "CodeMirror-measure");
  130. // When lines outside of the viewport are measured, they are drawn in this.
  131. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  132. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  133. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  134. null, "position: relative; outline: none");
  135. // Moved around its parent to cover visible view.
  136. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  137. // Set to the height of the document, allowing scrolling.
  138. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  139. d.sizerWidth = null;
  140. // Behavior of elts with overflow: auto and padding is
  141. // inconsistent across browsers. This is used to ensure the
  142. // scrollable area is big enough.
  143. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  144. // Will contain the gutters, if any.
  145. d.gutters = elt("div", null, "CodeMirror-gutters");
  146. d.lineGutter = null;
  147. // Actual scrollable element.
  148. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  149. d.scroller.setAttribute("tabIndex", "-1");
  150. // The element in which the editor lives.
  151. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  152. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  153. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  154. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  155. if (place) {
  156. if (place.appendChild) place.appendChild(d.wrapper);
  157. else place(d.wrapper);
  158. }
  159. // Current rendered range (may be bigger than the view window).
  160. d.viewFrom = d.viewTo = doc.first;
  161. d.reportedViewFrom = d.reportedViewTo = doc.first;
  162. // Information about the rendered lines.
  163. d.view = [];
  164. d.renderedView = null;
  165. // Holds info about a single rendered line when it was rendered
  166. // for measurement, while not in view.
  167. d.externalMeasured = null;
  168. // Empty space (in pixels) above the view
  169. d.viewOffset = 0;
  170. d.lastWrapHeight = d.lastWrapWidth = 0;
  171. d.updateLineNumbers = null;
  172. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  173. d.scrollbarsClipped = false;
  174. // Used to only resize the line number gutter when necessary (when
  175. // the amount of lines crosses a boundary that makes its width change)
  176. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  177. // Set to true when a non-horizontal-scrolling line widget is
  178. // added. As an optimization, line widget aligning is skipped when
  179. // this is false.
  180. d.alignWidgets = false;
  181. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  182. // Tracks the maximum line length so that the horizontal scrollbar
  183. // can be kept static when scrolling.
  184. d.maxLine = null;
  185. d.maxLineLength = 0;
  186. d.maxLineChanged = false;
  187. // Used for measuring wheel scrolling granularity
  188. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  189. // True when shift is held down.
  190. d.shift = false;
  191. // Used to track whether anything happened since the context menu
  192. // was opened.
  193. d.selForContextMenu = null;
  194. d.activeTouch = null;
  195. input.init(d);
  196. }
  197. // STATE UPDATES
  198. // Used to get the editor into a consistent state again when options change.
  199. function loadMode(cm) {
  200. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  201. resetModeState(cm);
  202. }
  203. function resetModeState(cm) {
  204. cm.doc.iter(function(line) {
  205. if (line.stateAfter) line.stateAfter = null;
  206. if (line.styles) line.styles = null;
  207. });
  208. cm.doc.frontier = cm.doc.first;
  209. startWorker(cm, 100);
  210. cm.state.modeGen++;
  211. if (cm.curOp) regChange(cm);
  212. }
  213. function wrappingChanged(cm) {
  214. if (cm.options.lineWrapping) {
  215. addClass(cm.display.wrapper, "CodeMirror-wrap");
  216. cm.display.sizer.style.minWidth = "";
  217. cm.display.sizerWidth = null;
  218. } else {
  219. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  220. findMaxLine(cm);
  221. }
  222. estimateLineHeights(cm);
  223. regChange(cm);
  224. clearCaches(cm);
  225. setTimeout(function(){updateScrollbars(cm);}, 100);
  226. }
  227. // Returns a function that estimates the height of a line, to use as
  228. // first approximation until the line becomes visible (and is thus
  229. // properly measurable).
  230. function estimateHeight(cm) {
  231. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  232. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  233. return function(line) {
  234. if (lineIsHidden(cm.doc, line)) return 0;
  235. var widgetsHeight = 0;
  236. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  237. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  238. }
  239. if (wrapping)
  240. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  241. else
  242. return widgetsHeight + th;
  243. };
  244. }
  245. function estimateLineHeights(cm) {
  246. var doc = cm.doc, est = estimateHeight(cm);
  247. doc.iter(function(line) {
  248. var estHeight = est(line);
  249. if (estHeight != line.height) updateLineHeight(line, estHeight);
  250. });
  251. }
  252. function themeChanged(cm) {
  253. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  254. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  255. clearCaches(cm);
  256. }
  257. function guttersChanged(cm) {
  258. updateGutters(cm);
  259. regChange(cm);
  260. setTimeout(function(){alignHorizontally(cm);}, 20);
  261. }
  262. // Rebuild the gutter elements, ensure the margin to the left of the
  263. // code matches their width.
  264. function updateGutters(cm) {
  265. var gutters = cm.display.gutters, specs = cm.options.gutters;
  266. removeChildren(gutters);
  267. for (var i = 0; i < specs.length; ++i) {
  268. var gutterClass = specs[i];
  269. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  270. if (gutterClass == "CodeMirror-linenumbers") {
  271. cm.display.lineGutter = gElt;
  272. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  273. }
  274. }
  275. gutters.style.display = i ? "" : "none";
  276. updateGutterSpace(cm);
  277. }
  278. function updateGutterSpace(cm) {
  279. var width = cm.display.gutters.offsetWidth;
  280. cm.display.sizer.style.marginLeft = width + "px";
  281. }
  282. // Compute the character length of a line, taking into account
  283. // collapsed ranges (see markText) that might hide parts, and join
  284. // other lines onto it.
  285. function lineLength(line) {
  286. if (line.height == 0) return 0;
  287. var len = line.text.length, merged, cur = line;
  288. while (merged = collapsedSpanAtStart(cur)) {
  289. var found = merged.find(0, true);
  290. cur = found.from.line;
  291. len += found.from.ch - found.to.ch;
  292. }
  293. cur = line;
  294. while (merged = collapsedSpanAtEnd(cur)) {
  295. var found = merged.find(0, true);
  296. len -= cur.text.length - found.from.ch;
  297. cur = found.to.line;
  298. len += cur.text.length - found.to.ch;
  299. }
  300. return len;
  301. }
  302. // Find the longest line in the document.
  303. function findMaxLine(cm) {
  304. var d = cm.display, doc = cm.doc;
  305. d.maxLine = getLine(doc, doc.first);
  306. d.maxLineLength = lineLength(d.maxLine);
  307. d.maxLineChanged = true;
  308. doc.iter(function(line) {
  309. var len = lineLength(line);
  310. if (len > d.maxLineLength) {
  311. d.maxLineLength = len;
  312. d.maxLine = line;
  313. }
  314. });
  315. }
  316. // Make sure the gutters options contains the element
  317. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  318. function setGuttersForLineNumbers(options) {
  319. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  320. if (found == -1 && options.lineNumbers) {
  321. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  322. } else if (found > -1 && !options.lineNumbers) {
  323. options.gutters = options.gutters.slice(0);
  324. options.gutters.splice(found, 1);
  325. }
  326. }
  327. // SCROLLBARS
  328. // Prepare DOM reads needed to update the scrollbars. Done in one
  329. // shot to minimize update/measure roundtrips.
  330. function measureForScrollbars(cm) {
  331. var d = cm.display, gutterW = d.gutters.offsetWidth;
  332. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  333. return {
  334. clientHeight: d.scroller.clientHeight,
  335. viewHeight: d.wrapper.clientHeight,
  336. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  337. viewWidth: d.wrapper.clientWidth,
  338. barLeft: cm.options.fixedGutter ? gutterW : 0,
  339. docHeight: docH,
  340. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  341. nativeBarWidth: d.nativeBarWidth,
  342. gutterWidth: gutterW
  343. };
  344. }
  345. function NativeScrollbars(place, scroll, cm) {
  346. this.cm = cm;
  347. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  348. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  349. place(vert); place(horiz);
  350. on(vert, "scroll", function() {
  351. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  352. });
  353. on(horiz, "scroll", function() {
  354. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  355. });
  356. this.checkedZeroWidth = false;
  357. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  358. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  359. }
  360. NativeScrollbars.prototype = copyObj({
  361. update: function(measure) {
  362. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  363. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  364. var sWidth = measure.nativeBarWidth;
  365. if (needsV) {
  366. this.vert.style.display = "block";
  367. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  368. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  369. // A bug in IE8 can cause this value to be negative, so guard it.
  370. this.vert.firstChild.style.height =
  371. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  372. } else {
  373. this.vert.style.display = "";
  374. this.vert.firstChild.style.height = "0";
  375. }
  376. if (needsH) {
  377. this.horiz.style.display = "block";
  378. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  379. this.horiz.style.left = measure.barLeft + "px";
  380. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  381. this.horiz.firstChild.style.width =
  382. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  383. } else {
  384. this.horiz.style.display = "";
  385. this.horiz.firstChild.style.width = "0";
  386. }
  387. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  388. if (sWidth == 0) this.zeroWidthHack();
  389. this.checkedZeroWidth = true;
  390. }
  391. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  392. },
  393. setScrollLeft: function(pos) {
  394. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  395. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  396. },
  397. setScrollTop: function(pos) {
  398. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  399. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  400. },
  401. zeroWidthHack: function() {
  402. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  403. this.horiz.style.height = this.vert.style.width = w;
  404. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  405. this.disableHoriz = new Delayed;
  406. this.disableVert = new Delayed;
  407. },
  408. enableZeroWidthBar: function(bar, delay) {
  409. bar.style.pointerEvents = "auto";
  410. function maybeDisable() {
  411. // To find out whether the scrollbar is still visible, we
  412. // check whether the element under the pixel in the bottom
  413. // left corner of the scrollbar box is the scrollbar box
  414. // itself (when the bar is still visible) or its filler child
  415. // (when the bar is hidden). If it is still visible, we keep
  416. // it enabled, if it's hidden, we disable pointer events.
  417. var box = bar.getBoundingClientRect();
  418. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  419. if (elt != bar) bar.style.pointerEvents = "none";
  420. else delay.set(1000, maybeDisable);
  421. }
  422. delay.set(1000, maybeDisable);
  423. },
  424. clear: function() {
  425. var parent = this.horiz.parentNode;
  426. parent.removeChild(this.horiz);
  427. parent.removeChild(this.vert);
  428. }
  429. }, NativeScrollbars.prototype);
  430. function NullScrollbars() {}
  431. NullScrollbars.prototype = copyObj({
  432. update: function() { return {bottom: 0, right: 0}; },
  433. setScrollLeft: function() {},
  434. setScrollTop: function() {},
  435. clear: function() {}
  436. }, NullScrollbars.prototype);
  437. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  438. function initScrollbars(cm) {
  439. if (cm.display.scrollbars) {
  440. cm.display.scrollbars.clear();
  441. if (cm.display.scrollbars.addClass)
  442. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  443. }
  444. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  445. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  446. // Prevent clicks in the scrollbars from killing focus
  447. on(node, "mousedown", function() {
  448. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  449. });
  450. node.setAttribute("cm-not-content", "true");
  451. }, function(pos, axis) {
  452. if (axis == "horizontal") setScrollLeft(cm, pos);
  453. else setScrollTop(cm, pos);
  454. }, cm);
  455. if (cm.display.scrollbars.addClass)
  456. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  457. }
  458. function updateScrollbars(cm, measure) {
  459. if (!measure) measure = measureForScrollbars(cm);
  460. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  461. updateScrollbarsInner(cm, measure);
  462. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  463. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  464. updateHeightsInViewport(cm);
  465. updateScrollbarsInner(cm, measureForScrollbars(cm));
  466. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  467. }
  468. }
  469. // Re-synchronize the fake scrollbars with the actual size of the
  470. // content.
  471. function updateScrollbarsInner(cm, measure) {
  472. var d = cm.display;
  473. var sizes = d.scrollbars.update(measure);
  474. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  475. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  476. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  477. if (sizes.right && sizes.bottom) {
  478. d.scrollbarFiller.style.display = "block";
  479. d.scrollbarFiller.style.height = sizes.bottom + "px";
  480. d.scrollbarFiller.style.width = sizes.right + "px";
  481. } else d.scrollbarFiller.style.display = "";
  482. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  483. d.gutterFiller.style.display = "block";
  484. d.gutterFiller.style.height = sizes.bottom + "px";
  485. d.gutterFiller.style.width = measure.gutterWidth + "px";
  486. } else d.gutterFiller.style.display = "";
  487. }
  488. // Compute the lines that are visible in a given viewport (defaults
  489. // the the current scroll position). viewport may contain top,
  490. // height, and ensure (see op.scrollToPos) properties.
  491. function visibleLines(display, doc, viewport) {
  492. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  493. top = Math.floor(top - paddingTop(display));
  494. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  495. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  496. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  497. // forces those lines into the viewport (if possible).
  498. if (viewport && viewport.ensure) {
  499. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  500. if (ensureFrom < from) {
  501. from = ensureFrom;
  502. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  503. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  504. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  505. to = ensureTo;
  506. }
  507. }
  508. return {from: from, to: Math.max(to, from + 1)};
  509. }
  510. // LINE NUMBERS
  511. // Re-align line numbers and gutter marks to compensate for
  512. // horizontal scrolling.
  513. function alignHorizontally(cm) {
  514. var display = cm.display, view = display.view;
  515. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  516. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  517. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  518. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  519. if (cm.options.fixedGutter && view[i].gutter)
  520. view[i].gutter.style.left = left;
  521. var align = view[i].alignable;
  522. if (align) for (var j = 0; j < align.length; j++)
  523. align[j].style.left = left;
  524. }
  525. if (cm.options.fixedGutter)
  526. display.gutters.style.left = (comp + gutterW) + "px";
  527. }
  528. // Used to ensure that the line number gutter is still the right
  529. // size for the current document size. Returns true when an update
  530. // is needed.
  531. function maybeUpdateLineNumberWidth(cm) {
  532. if (!cm.options.lineNumbers) return false;
  533. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  534. if (last.length != display.lineNumChars) {
  535. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  536. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  537. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  538. display.lineGutter.style.width = "";
  539. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  540. display.lineNumWidth = display.lineNumInnerWidth + padding;
  541. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  542. display.lineGutter.style.width = display.lineNumWidth + "px";
  543. updateGutterSpace(cm);
  544. return true;
  545. }
  546. return false;
  547. }
  548. function lineNumberFor(options, i) {
  549. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  550. }
  551. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  552. // but using getBoundingClientRect to get a sub-pixel-accurate
  553. // result.
  554. function compensateForHScroll(display) {
  555. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  556. }
  557. // DISPLAY DRAWING
  558. function DisplayUpdate(cm, viewport, force) {
  559. var display = cm.display;
  560. this.viewport = viewport;
  561. // Store some values that we'll need later (but don't want to force a relayout for)
  562. this.visible = visibleLines(display, cm.doc, viewport);
  563. this.editorIsHidden = !display.wrapper.offsetWidth;
  564. this.wrapperHeight = display.wrapper.clientHeight;
  565. this.wrapperWidth = display.wrapper.clientWidth;
  566. this.oldDisplayWidth = displayWidth(cm);
  567. this.force = force;
  568. this.dims = getDimensions(cm);
  569. this.events = [];
  570. }
  571. DisplayUpdate.prototype.signal = function(emitter, type) {
  572. if (hasHandler(emitter, type))
  573. this.events.push(arguments);
  574. };
  575. DisplayUpdate.prototype.finish = function() {
  576. for (var i = 0; i < this.events.length; i++)
  577. signal.apply(null, this.events[i]);
  578. };
  579. function maybeClipScrollbars(cm) {
  580. var display = cm.display;
  581. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  582. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  583. display.heightForcer.style.height = scrollGap(cm) + "px";
  584. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  585. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  586. display.scrollbarsClipped = true;
  587. }
  588. }
  589. // Does the actual updating of the line display. Bails out
  590. // (returning false) when there is nothing to be done and forced is
  591. // false.
  592. function updateDisplayIfNeeded(cm, update) {
  593. var display = cm.display, doc = cm.doc;
  594. if (update.editorIsHidden) {
  595. resetView(cm);
  596. return false;
  597. }
  598. // Bail out if the visible area is already rendered and nothing changed.
  599. if (!update.force &&
  600. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  601. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  602. display.renderedView == display.view && countDirtyView(cm) == 0)
  603. return false;
  604. if (maybeUpdateLineNumberWidth(cm)) {
  605. resetView(cm);
  606. update.dims = getDimensions(cm);
  607. }
  608. // Compute a suitable new viewport (from & to)
  609. var end = doc.first + doc.size;
  610. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  611. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  612. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  613. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  614. if (sawCollapsedSpans) {
  615. from = visualLineNo(cm.doc, from);
  616. to = visualLineEndNo(cm.doc, to);
  617. }
  618. var different = from != display.viewFrom || to != display.viewTo ||
  619. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  620. adjustView(cm, from, to);
  621. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  622. // Position the mover div to align with the current scroll position
  623. cm.display.mover.style.top = display.viewOffset + "px";
  624. var toUpdate = countDirtyView(cm);
  625. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  626. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  627. return false;
  628. // For big changes, we hide the enclosing element during the
  629. // update, since that speeds up the operations on most browsers.
  630. var focused = activeElt();
  631. if (toUpdate > 4) display.lineDiv.style.display = "none";
  632. patchDisplay(cm, display.updateLineNumbers, update.dims);
  633. if (toUpdate > 4) display.lineDiv.style.display = "";
  634. display.renderedView = display.view;
  635. // There might have been a widget with a focused element that got
  636. // hidden or updated, if so re-focus it.
  637. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  638. // Prevent selection and cursors from interfering with the scroll
  639. // width and height.
  640. removeChildren(display.cursorDiv);
  641. removeChildren(display.selectionDiv);
  642. display.gutters.style.height = display.sizer.style.minHeight = 0;
  643. if (different) {
  644. display.lastWrapHeight = update.wrapperHeight;
  645. display.lastWrapWidth = update.wrapperWidth;
  646. startWorker(cm, 400);
  647. }
  648. display.updateLineNumbers = null;
  649. return true;
  650. }
  651. function postUpdateDisplay(cm, update) {
  652. var viewport = update.viewport;
  653. for (var first = true;; first = false) {
  654. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  655. // Clip forced viewport to actual scrollable area.
  656. if (viewport && viewport.top != null)
  657. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  658. // Updated line heights might result in the drawn area not
  659. // actually covering the viewport. Keep looping until it does.
  660. update.visible = visibleLines(cm.display, cm.doc, viewport);
  661. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  662. break;
  663. }
  664. if (!updateDisplayIfNeeded(cm, update)) break;
  665. updateHeightsInViewport(cm);
  666. var barMeasure = measureForScrollbars(cm);
  667. updateSelection(cm);
  668. updateScrollbars(cm, barMeasure);
  669. setDocumentHeight(cm, barMeasure);
  670. }
  671. update.signal(cm, "update", cm);
  672. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  673. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  674. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  675. }
  676. }
  677. function updateDisplaySimple(cm, viewport) {
  678. var update = new DisplayUpdate(cm, viewport);
  679. if (updateDisplayIfNeeded(cm, update)) {
  680. updateHeightsInViewport(cm);
  681. postUpdateDisplay(cm, update);
  682. var barMeasure = measureForScrollbars(cm);
  683. updateSelection(cm);
  684. updateScrollbars(cm, barMeasure);
  685. setDocumentHeight(cm, barMeasure);
  686. update.finish();
  687. }
  688. }
  689. function setDocumentHeight(cm, measure) {
  690. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  691. cm.display.heightForcer.style.top = measure.docHeight + "px";
  692. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  693. }
  694. // Read the actual heights of the rendered lines, and update their
  695. // stored heights to match.
  696. function updateHeightsInViewport(cm) {
  697. var display = cm.display;
  698. var prevBottom = display.lineDiv.offsetTop;
  699. for (var i = 0; i < display.view.length; i++) {
  700. var cur = display.view[i], height;
  701. if (cur.hidden) continue;
  702. if (ie && ie_version < 8) {
  703. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  704. height = bot - prevBottom;
  705. prevBottom = bot;
  706. } else {
  707. var box = cur.node.getBoundingClientRect();
  708. height = box.bottom - box.top;
  709. }
  710. var diff = cur.line.height - height;
  711. if (height < 2) height = textHeight(display);
  712. if (diff > .001 || diff < -.001) {
  713. updateLineHeight(cur.line, height);
  714. updateWidgetHeight(cur.line);
  715. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  716. updateWidgetHeight(cur.rest[j]);
  717. }
  718. }
  719. }
  720. // Read and store the height of line widgets associated with the
  721. // given line.
  722. function updateWidgetHeight(line) {
  723. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  724. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  725. }
  726. // Do a bulk-read of the DOM positions and sizes needed to draw the
  727. // view, so that we don't interleave reading and writing to the DOM.
  728. function getDimensions(cm) {
  729. var d = cm.display, left = {}, width = {};
  730. var gutterLeft = d.gutters.clientLeft;
  731. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  732. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  733. width[cm.options.gutters[i]] = n.clientWidth;
  734. }
  735. return {fixedPos: compensateForHScroll(d),
  736. gutterTotalWidth: d.gutters.offsetWidth,
  737. gutterLeft: left,
  738. gutterWidth: width,
  739. wrapperWidth: d.wrapper.clientWidth};
  740. }
  741. // Sync the actual display DOM structure with display.view, removing
  742. // nodes for lines that are no longer in view, and creating the ones
  743. // that are not there yet, and updating the ones that are out of
  744. // date.
  745. function patchDisplay(cm, updateNumbersFrom, dims) {
  746. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  747. var container = display.lineDiv, cur = container.firstChild;
  748. function rm(node) {
  749. var next = node.nextSibling;
  750. // Works around a throw-scroll bug in OS X Webkit
  751. if (webkit && mac && cm.display.currentWheelTarget == node)
  752. node.style.display = "none";
  753. else
  754. node.parentNode.removeChild(node);
  755. return next;
  756. }
  757. var view = display.view, lineN = display.viewFrom;
  758. // Loop over the elements in the view, syncing cur (the DOM nodes
  759. // in display.lineDiv) with the view as we go.
  760. for (var i = 0; i < view.length; i++) {
  761. var lineView = view[i];
  762. if (lineView.hidden) {
  763. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  764. var node = buildLineElement(cm, lineView, lineN, dims);
  765. container.insertBefore(node, cur);
  766. } else { // Already drawn
  767. while (cur != lineView.node) cur = rm(cur);
  768. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  769. updateNumbersFrom <= lineN && lineView.lineNumber;
  770. if (lineView.changes) {
  771. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  772. updateLineForChanges(cm, lineView, lineN, dims);
  773. }
  774. if (updateNumber) {
  775. removeChildren(lineView.lineNumber);
  776. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  777. }
  778. cur = lineView.node.nextSibling;
  779. }
  780. lineN += lineView.size;
  781. }
  782. while (cur) cur = rm(cur);
  783. }
  784. // When an aspect of a line changes, a string is added to
  785. // lineView.changes. This updates the relevant part of the line's
  786. // DOM structure.
  787. function updateLineForChanges(cm, lineView, lineN, dims) {
  788. for (var j = 0; j < lineView.changes.length; j++) {
  789. var type = lineView.changes[j];
  790. if (type == "text") updateLineText(cm, lineView);
  791. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  792. else if (type == "class") updateLineClasses(lineView);
  793. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  794. }
  795. lineView.changes = null;
  796. }
  797. // Lines with gutter elements, widgets or a background class need to
  798. // be wrapped, and have the extra elements added to the wrapper div
  799. function ensureLineWrapped(lineView) {
  800. if (lineView.node == lineView.text) {
  801. lineView.node = elt("div", null, null, "position: relative");
  802. if (lineView.text.parentNode)
  803. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  804. lineView.node.appendChild(lineView.text);
  805. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  806. }
  807. return lineView.node;
  808. }
  809. function updateLineBackground(lineView) {
  810. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  811. if (cls) cls += " CodeMirror-linebackground";
  812. if (lineView.background) {
  813. if (cls) lineView.background.className = cls;
  814. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  815. } else if (cls) {
  816. var wrap = ensureLineWrapped(lineView);
  817. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  818. }
  819. }
  820. // Wrapper around buildLineContent which will reuse the structure
  821. // in display.externalMeasured when possible.
  822. function getLineContent(cm, lineView) {
  823. var ext = cm.display.externalMeasured;
  824. if (ext && ext.line == lineView.line) {
  825. cm.display.externalMeasured = null;
  826. lineView.measure = ext.measure;
  827. return ext.built;
  828. }
  829. return buildLineContent(cm, lineView);
  830. }
  831. // Redraw the line's text. Interacts with the background and text
  832. // classes because the mode may output tokens that influence these
  833. // classes.
  834. function updateLineText(cm, lineView) {
  835. var cls = lineView.text.className;
  836. var built = getLineContent(cm, lineView);
  837. if (lineView.text == lineView.node) lineView.node = built.pre;
  838. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  839. lineView.text = built.pre;
  840. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  841. lineView.bgClass = built.bgClass;
  842. lineView.textClass = built.textClass;
  843. updateLineClasses(lineView);
  844. } else if (cls) {
  845. lineView.text.className = cls;
  846. }
  847. }
  848. function updateLineClasses(lineView) {
  849. updateLineBackground(lineView);
  850. if (lineView.line.wrapClass)
  851. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  852. else if (lineView.node != lineView.text)
  853. lineView.node.className = "";
  854. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  855. lineView.text.className = textClass || "";
  856. }
  857. function updateLineGutter(cm, lineView, lineN, dims) {
  858. if (lineView.gutter) {
  859. lineView.node.removeChild(lineView.gutter);
  860. lineView.gutter = null;
  861. }
  862. if (lineView.gutterBackground) {
  863. lineView.node.removeChild(lineView.gutterBackground);
  864. lineView.gutterBackground = null;
  865. }
  866. if (lineView.line.gutterClass) {
  867. var wrap = ensureLineWrapped(lineView);
  868. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  869. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  870. "px; width: " + dims.gutterTotalWidth + "px");
  871. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  872. }
  873. var markers = lineView.line.gutterMarkers;
  874. if (cm.options.lineNumbers || markers) {
  875. var wrap = ensureLineWrapped(lineView);
  876. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  877. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  878. cm.display.input.setUneditable(gutterWrap);
  879. wrap.insertBefore(gutterWrap, lineView.text);
  880. if (lineView.line.gutterClass)
  881. gutterWrap.className += " " + lineView.line.gutterClass;
  882. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  883. lineView.lineNumber = gutterWrap.appendChild(
  884. elt("div", lineNumberFor(cm.options, lineN),
  885. "CodeMirror-linenumber CodeMirror-gutter-elt",
  886. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  887. + cm.display.lineNumInnerWidth + "px"));
  888. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  889. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  890. if (found)
  891. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  892. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  893. }
  894. }
  895. }
  896. function updateLineWidgets(cm, lineView, dims) {
  897. if (lineView.alignable) lineView.alignable = null;
  898. for (var node = lineView.node.firstChild, next; node; node = next) {
  899. var next = node.nextSibling;
  900. if (node.className == "CodeMirror-linewidget")
  901. lineView.node.removeChild(node);
  902. }
  903. insertLineWidgets(cm, lineView, dims);
  904. }
  905. // Build a line's DOM representation from scratch
  906. function buildLineElement(cm, lineView, lineN, dims) {
  907. var built = getLineContent(cm, lineView);
  908. lineView.text = lineView.node = built.pre;
  909. if (built.bgClass) lineView.bgClass = built.bgClass;
  910. if (built.textClass) lineView.textClass = built.textClass;
  911. updateLineClasses(lineView);
  912. updateLineGutter(cm, lineView, lineN, dims);
  913. insertLineWidgets(cm, lineView, dims);
  914. return lineView.node;
  915. }
  916. // A lineView may contain multiple logical lines (when merged by
  917. // collapsed spans). The widgets for all of them need to be drawn.
  918. function insertLineWidgets(cm, lineView, dims) {
  919. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  920. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  921. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  922. }
  923. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  924. if (!line.widgets) return;
  925. var wrap = ensureLineWrapped(lineView);
  926. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  927. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  928. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  929. positionLineWidget(widget, node, lineView, dims);
  930. cm.display.input.setUneditable(node);
  931. if (allowAbove && widget.above)
  932. wrap.insertBefore(node, lineView.gutter || lineView.text);
  933. else
  934. wrap.appendChild(node);
  935. signalLater(widget, "redraw");
  936. }
  937. }
  938. function positionLineWidget(widget, node, lineView, dims) {
  939. if (widget.noHScroll) {
  940. (lineView.alignable || (lineView.alignable = [])).push(node);
  941. var width = dims.wrapperWidth;
  942. node.style.left = dims.fixedPos + "px";
  943. if (!widget.coverGutter) {
  944. width -= dims.gutterTotalWidth;
  945. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  946. }
  947. node.style.width = width + "px";
  948. }
  949. if (widget.coverGutter) {
  950. node.style.zIndex = 5;
  951. node.style.position = "relative";
  952. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  953. }
  954. }
  955. // POSITION OBJECT
  956. // A Pos instance represents a position within the text.
  957. var Pos = CodeMirror.Pos = function(line, ch) {
  958. if (!(this instanceof Pos)) return new Pos(line, ch);
  959. this.line = line; this.ch = ch;
  960. };
  961. // Compare two positions, return 0 if they are the same, a negative
  962. // number when a is less, and a positive number otherwise.
  963. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  964. function copyPos(x) {return Pos(x.line, x.ch);}
  965. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  966. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  967. // INPUT HANDLING
  968. function ensureFocus(cm) {
  969. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  970. }
  971. // This will be set to a {lineWise: bool, text: [string]} object, so
  972. // that, when pasting, we know what kind of selections the copied
  973. // text was made out of.
  974. var lastCopied = null;
  975. function applyTextInput(cm, inserted, deleted, sel, origin) {
  976. var doc = cm.doc;
  977. cm.display.shift = false;
  978. if (!sel) sel = doc.sel;
  979. var paste = cm.state.pasteIncoming || origin == "paste";
  980. var textLines = doc.splitLines(inserted), multiPaste = null
  981. // When pasing N lines into N selections, insert one line per selection
  982. if (paste && sel.ranges.length > 1) {
  983. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  984. if (sel.ranges.length % lastCopied.text.length == 0) {
  985. multiPaste = [];
  986. for (var i = 0; i < lastCopied.text.length; i++)
  987. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  988. }
  989. } else if (textLines.length == sel.ranges.length) {
  990. multiPaste = map(textLines, function(l) { return [l]; });
  991. }
  992. }
  993. // Normal behavior is to insert the new text into every selection
  994. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  995. var range = sel.ranges[i];
  996. var from = range.from(), to = range.to();
  997. if (range.empty()) {
  998. if (deleted && deleted > 0) // Handle deletion
  999. from = Pos(from.line, from.ch - deleted);
  1000. else if (cm.state.overwrite && !paste) // Handle overwrite
  1001. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  1002. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  1003. from = to = Pos(from.line, 0)
  1004. }
  1005. var updateInput = cm.curOp.updateInput;
  1006. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  1007. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  1008. makeChange(cm.doc, changeEvent);
  1009. signalLater(cm, "inputRead", cm, changeEvent);
  1010. }
  1011. if (inserted && !paste)
  1012. triggerElectric(cm, inserted);
  1013. ensureCursorVisible(cm);
  1014. cm.curOp.updateInput = updateInput;
  1015. cm.curOp.typing = true;
  1016. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  1017. }
  1018. function handlePaste(e, cm) {
  1019. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  1020. if (pasted) {
  1021. e.preventDefault();
  1022. if (!cm.isReadOnly() && !cm.options.disableInput)
  1023. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  1024. return true;
  1025. }
  1026. }
  1027. function triggerElectric(cm, inserted) {
  1028. // When an 'electric' character is inserted, immediately trigger a reindent
  1029. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  1030. var sel = cm.doc.sel;
  1031. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  1032. var range = sel.ranges[i];
  1033. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  1034. var mode = cm.getModeAt(range.head);
  1035. var indented = false;
  1036. if (mode.electricChars) {
  1037. for (var j = 0; j < mode.electricChars.length; j++)
  1038. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  1039. indented = indentLine(cm, range.head.line, "smart");
  1040. break;
  1041. }
  1042. } else if (mode.electricInput) {
  1043. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  1044. indented = indentLine(cm, range.head.line, "smart");
  1045. }
  1046. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  1047. }
  1048. }
  1049. function copyableRanges(cm) {
  1050. var text = [], ranges = [];
  1051. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  1052. var line = cm.doc.sel.ranges[i].head.line;
  1053. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  1054. ranges.push(lineRange);
  1055. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  1056. }
  1057. return {text: text, ranges: ranges};
  1058. }
  1059. function disableBrowserMagic(field) {
  1060. field.setAttribute("autocorrect", "off");
  1061. field.setAttribute("autocapitalize", "off");
  1062. field.setAttribute("spellcheck", "false");
  1063. }
  1064. // TEXTAREA INPUT STYLE
  1065. function TextareaInput(cm) {
  1066. this.cm = cm;
  1067. // See input.poll and input.reset
  1068. this.prevInput = "";
  1069. // Flag that indicates whether we expect input to appear real soon
  1070. // now (after some event like 'keypress' or 'input') and are
  1071. // polling intensively.
  1072. this.pollingFast = false;
  1073. // Self-resetting timeout for the poller
  1074. this.polling = new Delayed();
  1075. // Tracks when input.reset has punted to just putting a short
  1076. // string into the textarea instead of the full selection.
  1077. this.inaccurateSelection = false;
  1078. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  1079. this.hasSelection = false;
  1080. this.composing = null;
  1081. };
  1082. function hiddenTextarea() {
  1083. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  1084. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  1085. // The textarea is kept positioned near the cursor to prevent the
  1086. // fact that it'll be scrolled into view on input from scrolling
  1087. // our fake cursor out of view. On webkit, when wrap=off, paste is
  1088. // very slow. So make the area wide instead.
  1089. if (webkit) te.style.width = "1000px";
  1090. else te.setAttribute("wrap", "off");
  1091. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  1092. if (ios) te.style.border = "1px solid black";
  1093. disableBrowserMagic(te);
  1094. return div;
  1095. }
  1096. TextareaInput.prototype = copyObj({
  1097. init: function(display) {
  1098. var input = this, cm = this.cm;
  1099. // Wraps and hides input textarea
  1100. var div = this.wrapper = hiddenTextarea();
  1101. // The semihidden textarea that is focused when the editor is
  1102. // focused, and receives input.
  1103. var te = this.textarea = div.firstChild;
  1104. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  1105. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  1106. if (ios) te.style.width = "0px";
  1107. on(te, "input", function() {
  1108. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  1109. input.poll();
  1110. });
  1111. on(te, "paste", function(e) {
  1112. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  1113. cm.state.pasteIncoming = true;
  1114. input.fastPoll();
  1115. });
  1116. function prepareCopyCut(e) {
  1117. if (signalDOMEvent(cm, e)) return
  1118. if (cm.somethingSelected()) {
  1119. lastCopied = {lineWise: false, text: cm.getSelections()};
  1120. if (input.inaccurateSelection) {
  1121. input.prevInput = "";
  1122. input.inaccurateSelection = false;
  1123. te.value = lastCopied.text.join("\n");
  1124. selectInput(te);
  1125. }
  1126. } else if (!cm.options.lineWiseCopyCut) {
  1127. return;
  1128. } else {
  1129. var ranges = copyableRanges(cm);
  1130. lastCopied = {lineWise: true, text: ranges.text};
  1131. if (e.type == "cut") {
  1132. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  1133. } else {
  1134. input.prevInput = "";
  1135. te.value = ranges.text.join("\n");
  1136. selectInput(te);
  1137. }
  1138. }
  1139. if (e.type == "cut") cm.state.cutIncoming = true;
  1140. }
  1141. on(te, "cut", prepareCopyCut);
  1142. on(te, "copy", prepareCopyCut);
  1143. on(display.scroller, "paste", function(e) {
  1144. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  1145. cm.state.pasteIncoming = true;
  1146. input.focus();
  1147. });
  1148. // Prevent normal selection in the editor (we handle our own)
  1149. on(display.lineSpace, "selectstart", function(e) {
  1150. if (!eventInWidget(display, e)) e_preventDefault(e);
  1151. });
  1152. on(te, "compositionstart", function() {
  1153. var start = cm.getCursor("from");
  1154. if (input.composing) input.composing.range.clear()
  1155. input.composing = {
  1156. start: start,
  1157. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  1158. };
  1159. });
  1160. on(te, "compositionend", function() {
  1161. if (input.composing) {
  1162. input.poll();
  1163. input.composing.range.clear();
  1164. input.composing = null;
  1165. }
  1166. });
  1167. },
  1168. prepareSelection: function() {
  1169. // Redraw the selection and/or cursor
  1170. var cm = this.cm, display = cm.display, doc = cm.doc;
  1171. var result = prepareSelection(cm);
  1172. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1173. if (cm.options.moveInputWithCursor) {
  1174. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1175. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1176. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1177. headPos.top + lineOff.top - wrapOff.top));
  1178. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1179. headPos.left + lineOff.left - wrapOff.left));
  1180. }
  1181. return result;
  1182. },
  1183. showSelection: function(drawn) {
  1184. var cm = this.cm, display = cm.display;
  1185. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  1186. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  1187. if (drawn.teTop != null) {
  1188. this.wrapper.style.top = drawn.teTop + "px";
  1189. this.wrapper.style.left = drawn.teLeft + "px";
  1190. }
  1191. },
  1192. // Reset the input to correspond to the selection (or to be empty,
  1193. // when not typing and nothing is selected)
  1194. reset: function(typing) {
  1195. if (this.contextMenuPending) return;
  1196. var minimal, selected, cm = this.cm, doc = cm.doc;
  1197. if (cm.somethingSelected()) {
  1198. this.prevInput = "";
  1199. var range = doc.sel.primary();
  1200. minimal = hasCopyEvent &&
  1201. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  1202. var content = minimal ? "-" : selected || cm.getSelection();
  1203. this.textarea.value = content;
  1204. if (cm.state.focused) selectInput(this.textarea);
  1205. if (ie && ie_version >= 9) this.hasSelection = content;
  1206. } else if (!typing) {
  1207. this.prevInput = this.textarea.value = "";
  1208. if (ie && ie_version >= 9) this.hasSelection = null;
  1209. }
  1210. this.inaccurateSelection = minimal;
  1211. },
  1212. getField: function() { return this.textarea; },
  1213. supportsTouch: function() { return false; },
  1214. focus: function() {
  1215. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  1216. try { this.textarea.focus(); }
  1217. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  1218. }
  1219. },
  1220. blur: function() { this.textarea.blur(); },
  1221. resetPosition: function() {
  1222. this.wrapper.style.top = this.wrapper.style.left = 0;
  1223. },
  1224. receivedFocus: function() { this.slowPoll(); },
  1225. // Poll for input changes, using the normal rate of polling. This
  1226. // runs as long as the editor is focused.
  1227. slowPoll: function() {
  1228. var input = this;
  1229. if (input.pollingFast) return;
  1230. input.polling.set(this.cm.options.pollInterval, function() {
  1231. input.poll();
  1232. if (input.cm.state.focused) input.slowPoll();
  1233. });
  1234. },
  1235. // When an event has just come in that is likely to add or change
  1236. // something in the input textarea, we poll faster, to ensure that
  1237. // the change appears on the screen quickly.
  1238. fastPoll: function() {
  1239. var missed = false, input = this;
  1240. input.pollingFast = true;
  1241. function p() {
  1242. var changed = input.poll();
  1243. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  1244. else {input.pollingFast = false; input.slowPoll();}
  1245. }
  1246. input.polling.set(20, p);
  1247. },
  1248. // Read input from the textarea, and update the document to match.
  1249. // When something is selected, it is present in the textarea, and
  1250. // selected (unless it is huge, in which case a placeholder is
  1251. // used). When nothing is selected, the cursor sits after previously
  1252. // seen text (can be empty), which is stored in prevInput (we must
  1253. // not reset the textarea when typing, because that breaks IME).
  1254. poll: function() {
  1255. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  1256. // Since this is called a *lot*, try to bail out as cheaply as
  1257. // possible when it is clear that nothing happened. hasSelection
  1258. // will be the case when there is a lot of text in the textarea,
  1259. // in which case reading its value would be expensive.
  1260. if (this.contextMenuPending || !cm.state.focused ||
  1261. (hasSelection(input) && !prevInput && !this.composing) ||
  1262. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  1263. return false;
  1264. var text = input.value;
  1265. // If nothing changed, bail.
  1266. if (text == prevInput && !cm.somethingSelected()) return false;
  1267. // Work around nonsensical selection resetting in IE9/10, and
  1268. // inexplicable appearance of private area unicode characters on
  1269. // some key combos in Mac (#2689).
  1270. if (ie && ie_version >= 9 && this.hasSelection === text ||
  1271. mac && /[\uf700-\uf7ff]/.test(text)) {
  1272. cm.display.input.reset();
  1273. return false;
  1274. }
  1275. if (cm.doc.sel == cm.display.selForContextMenu) {
  1276. var first = text.charCodeAt(0);
  1277. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  1278. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  1279. }
  1280. // Find the part of the input that is actually new
  1281. var same = 0, l = Math.min(prevInput.length, text.length);
  1282. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  1283. var self = this;
  1284. runInOp(cm, function() {
  1285. applyTextInput(cm, text.slice(same), prevInput.length - same,
  1286. null, self.composing ? "*compose" : null);
  1287. // Don't leave long text in the textarea, since it makes further polling slow
  1288. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  1289. else self.prevInput = text;
  1290. if (self.composing) {
  1291. self.composing.range.clear();
  1292. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  1293. {className: "CodeMirror-composing"});
  1294. }
  1295. });
  1296. return true;
  1297. },
  1298. ensurePolled: function() {
  1299. if (this.pollingFast && this.poll()) this.pollingFast = false;
  1300. },
  1301. onKeyPress: function() {
  1302. if (ie && ie_version >= 9) this.hasSelection = null;
  1303. this.fastPoll();
  1304. },
  1305. onContextMenu: function(e) {
  1306. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  1307. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1308. if (!pos || presto) return; // Opera is difficult.
  1309. // Reset the current text selection only if the click is done outside of the selection
  1310. // and 'resetSelectionOnContextMenu' option is true.
  1311. var reset = cm.options.resetSelectionOnContextMenu;
  1312. if (reset && cm.doc.sel.contains(pos) == -1)
  1313. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  1314. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  1315. input.wrapper.style.cssText = "position: absolute"
  1316. var wrapperBox = input.wrapper.getBoundingClientRect()
  1317. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  1318. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  1319. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  1320. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  1321. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  1322. display.input.focus();
  1323. if (webkit) window.scrollTo(null, oldScrollY);
  1324. display.input.reset();
  1325. // Adds "Select all" to context menu in FF
  1326. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  1327. input.contextMenuPending = true;
  1328. display.selForContextMenu = cm.doc.sel;
  1329. clearTimeout(display.detectingSelectAll);
  1330. // Select-all will be greyed out if there's nothing to select, so
  1331. // this adds a zero-width space so that we can later check whether
  1332. // it got selected.
  1333. function prepareSelectAllHack() {
  1334. if (te.selectionStart != null) {
  1335. var selected = cm.somethingSelected();
  1336. var extval = "\u200b" + (selected ? te.value : "");
  1337. te.value = "\u21da"; // Used to catch context-menu undo
  1338. te.value = extval;
  1339. input.prevInput = selected ? "" : "\u200b";
  1340. te.selectionStart = 1; te.selectionEnd = extval.length;
  1341. // Re-set this, in case some other handler touched the
  1342. // selection in the meantime.
  1343. display.selForContextMenu = cm.doc.sel;
  1344. }
  1345. }
  1346. function rehide() {
  1347. input.contextMenuPending = false;
  1348. input.wrapper.style.cssText = oldWrapperCSS
  1349. te.style.cssText = oldCSS;
  1350. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  1351. // Try to detect the user choosing select-all
  1352. if (te.selectionStart != null) {
  1353. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  1354. var i = 0, poll = function() {
  1355. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  1356. te.selectionEnd > 0 && input.prevInput == "\u200b")
  1357. operation(cm, commands.selectAll)(cm);
  1358. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  1359. else display.input.reset();
  1360. };
  1361. display.detectingSelectAll = setTimeout(poll, 200);
  1362. }
  1363. }
  1364. if (ie && ie_version >= 9) prepareSelectAllHack();
  1365. if (captureRightClick) {
  1366. e_stop(e);
  1367. var mouseup = function() {
  1368. off(window, "mouseup", mouseup);
  1369. setTimeout(rehide, 20);
  1370. };
  1371. on(window, "mouseup", mouseup);
  1372. } else {
  1373. setTimeout(rehide, 50);
  1374. }
  1375. },
  1376. readOnlyChanged: function(val) {
  1377. if (!val) this.reset();
  1378. },
  1379. setUneditable: nothing,
  1380. needsContentAttribute: false
  1381. }, TextareaInput.prototype);
  1382. // CONTENTEDITABLE INPUT STYLE
  1383. function ContentEditableInput(cm) {
  1384. this.cm = cm;
  1385. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  1386. this.polling = new Delayed();
  1387. this.gracePeriod = false;
  1388. }
  1389. ContentEditableInput.prototype = copyObj({
  1390. init: function(display) {
  1391. var input = this, cm = input.cm;
  1392. var div = input.div = display.lineDiv;
  1393. disableBrowserMagic(div);
  1394. on(div, "paste", function(e) {
  1395. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  1396. })
  1397. on(div, "compositionstart", function(e) {
  1398. var data = e.data;
  1399. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  1400. if (!data) return;
  1401. var prim = cm.doc.sel.primary();
  1402. var line = cm.getLine(prim.head.line);
  1403. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  1404. if (found > -1 && found <= prim.head.ch)
  1405. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  1406. Pos(prim.head.line, found + data.length));
  1407. });
  1408. on(div, "compositionupdate", function(e) {
  1409. input.composing.data = e.data;
  1410. });
  1411. on(div, "compositionend", function(e) {
  1412. var ours = input.composing;
  1413. if (!ours) return;
  1414. if (e.data != ours.startData && !/\u200b/.test(e.data))
  1415. ours.data = e.data;
  1416. // Need a small delay to prevent other code (input event,
  1417. // selection polling) from doing damage when fired right after
  1418. // compositionend.
  1419. setTimeout(function() {
  1420. if (!ours.handled)
  1421. input.applyComposition(ours);
  1422. if (input.composing == ours)
  1423. input.composing = null;
  1424. }, 50);
  1425. });
  1426. on(div, "touchstart", function() {
  1427. input.forceCompositionEnd();
  1428. });
  1429. on(div, "input", function() {
  1430. if (input.composing) return;
  1431. if (cm.isReadOnly() || !input.pollContent())
  1432. runInOp(input.cm, function() {regChange(cm);});
  1433. });
  1434. function onCopyCut(e) {
  1435. if (signalDOMEvent(cm, e)) return
  1436. if (cm.somethingSelected()) {
  1437. lastCopied = {lineWise: false, text: cm.getSelections()};
  1438. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  1439. } else if (!cm.options.lineWiseCopyCut) {
  1440. return;
  1441. } else {
  1442. var ranges = copyableRanges(cm);
  1443. lastCopied = {lineWise: true, text: ranges.text};
  1444. if (e.type == "cut") {
  1445. cm.operation(function() {
  1446. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  1447. cm.replaceSelection("", null, "cut");
  1448. });
  1449. }
  1450. }
  1451. // iOS exposes the clipboard API, but seems to discard content inserted into it
  1452. if (e.clipboardData && !ios) {
  1453. e.preventDefault();
  1454. e.clipboardData.clearData();
  1455. e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
  1456. } else {
  1457. // Old-fashioned briefly-focus-a-textarea hack
  1458. var kludge = hiddenTextarea(), te = kludge.firstChild;
  1459. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  1460. te.value = lastCopied.text.join("\n");
  1461. var hadFocus = document.activeElement;
  1462. selectInput(te);
  1463. setTimeout(function() {
  1464. cm.display.lineSpace.removeChild(kludge);
  1465. hadFocus.focus();
  1466. }, 50);
  1467. }
  1468. }
  1469. on(div, "copy", onCopyCut);
  1470. on(div, "cut", onCopyCut);
  1471. },
  1472. prepareSelection: function() {
  1473. var result = prepareSelection(this.cm, false);
  1474. result.focus = this.cm.state.focused;
  1475. return result;
  1476. },
  1477. showSelection: function(info, takeFocus) {
  1478. if (!info || !this.cm.display.view.length) return;
  1479. if (info.focus || takeFocus) this.showPrimarySelection();
  1480. this.showMultipleSelections(info);
  1481. },
  1482. showPrimarySelection: function() {
  1483. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  1484. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  1485. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  1486. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  1487. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  1488. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  1489. return;
  1490. var start = posToDOM(this.cm, prim.from());
  1491. var end = posToDOM(this.cm, prim.to());
  1492. if (!start && !end) return;
  1493. var view = this.cm.display.view;
  1494. var old = sel.rangeCount && sel.getRangeAt(0);
  1495. if (!start) {
  1496. start = {node: view[0].measure.map[2], offset: 0};
  1497. } else if (!end) { // FIXME dangerously hacky
  1498. var measure = view[view.length - 1].measure;
  1499. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  1500. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  1501. }
  1502. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  1503. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  1504. if (rng) {
  1505. if (!gecko && this.cm.state.focused) {
  1506. sel.collapse(start.node, start.offset);
  1507. if (!rng.collapsed) sel.addRange(rng);
  1508. } else {
  1509. sel.removeAllRanges();
  1510. sel.addRange(rng);
  1511. }
  1512. if (old && sel.anchorNode == null) sel.addRange(old);
  1513. else if (gecko) this.startGracePeriod();
  1514. }
  1515. this.rememberSelection();
  1516. },
  1517. startGracePeriod: function() {
  1518. var input = this;
  1519. clearTimeout(this.gracePeriod);
  1520. this.gracePeriod = setTimeout(function() {
  1521. input.gracePeriod = false;
  1522. if (input.selectionChanged())
  1523. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  1524. }, 20);
  1525. },
  1526. showMultipleSelections: function(info) {
  1527. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  1528. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  1529. },
  1530. rememberSelection: function() {
  1531. var sel = window.getSelection();
  1532. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  1533. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  1534. },
  1535. selectionInEditor: function() {
  1536. var sel = window.getSelection();
  1537. if (!sel.rangeCount) return false;
  1538. var node = sel.getRangeAt(0).commonAncestorContainer;
  1539. return contains(this.div, node);
  1540. },
  1541. focus: function() {
  1542. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  1543. },
  1544. blur: function() { this.div.blur(); },
  1545. getField: function() { return this.div; },
  1546. supportsTouch: function() { return true; },
  1547. receivedFocus: function() {
  1548. var input = this;
  1549. if (this.selectionInEditor())
  1550. this.pollSelection();
  1551. else
  1552. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  1553. function poll() {
  1554. if (input.cm.state.focused) {
  1555. input.pollSelection();
  1556. input.polling.set(input.cm.options.pollInterval, poll);
  1557. }
  1558. }
  1559. this.polling.set(this.cm.options.pollInterval, poll);
  1560. },
  1561. selectionChanged: function() {
  1562. var sel = window.getSelection();
  1563. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  1564. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  1565. },
  1566. pollSelection: function() {
  1567. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  1568. var sel = window.getSelection(), cm = this.cm;
  1569. this.rememberSelection();
  1570. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  1571. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  1572. if (anchor && head) runInOp(cm, function() {
  1573. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  1574. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  1575. });
  1576. }
  1577. },
  1578. pollContent: function() {
  1579. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  1580. var from = sel.from(), to = sel.to();
  1581. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  1582. var fromIndex;
  1583. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  1584. var fromLine = lineNo(display.view[0].line);
  1585. var fromNode = display.view[0].node;
  1586. } else {
  1587. var fromLine = lineNo(display.view[fromIndex].line);
  1588. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  1589. }
  1590. var toIndex = findViewIndex(cm, to.line);
  1591. if (toIndex == display.view.length - 1) {
  1592. var toLine = display.viewTo - 1;
  1593. var toNode = display.lineDiv.lastChild;
  1594. } else {
  1595. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  1596. var toNode = display.view[toIndex + 1].node.previousSibling;
  1597. }
  1598. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  1599. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  1600. while (newText.length > 1 && oldText.length > 1) {
  1601. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  1602. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  1603. else break;
  1604. }
  1605. var cutFront = 0, cutEnd = 0;
  1606. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  1607. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  1608. ++cutFront;
  1609. var newBot = lst(newText), oldBot = lst(oldText);
  1610. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  1611. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  1612. while (cutEnd < maxCutEnd &&
  1613. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  1614. ++cutEnd;
  1615. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  1616. newText[0] = newText[0].slice(cutFront);
  1617. var chFrom = Pos(fromLine, cutFront);
  1618. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  1619. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  1620. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  1621. return true;
  1622. }
  1623. },
  1624. ensurePolled: function() {
  1625. this.forceCompositionEnd();
  1626. },
  1627. reset: function() {
  1628. this.forceCompositionEnd();
  1629. },
  1630. forceCompositionEnd: function() {
  1631. if (!this.composing || this.composing.handled) return;
  1632. this.applyComposition(this.composing);
  1633. this.composing.handled = true;
  1634. this.div.blur();
  1635. this.div.focus();
  1636. },
  1637. applyComposition: function(composing) {
  1638. if (this.cm.isReadOnly())
  1639. operation(this.cm, regChange)(this.cm)
  1640. else if (composing.data && composing.data != composing.startData)
  1641. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  1642. },
  1643. setUneditable: function(node) {
  1644. node.contentEditable = "false"
  1645. },
  1646. onKeyPress: function(e) {
  1647. e.preventDefault();
  1648. if (!this.cm.isReadOnly())
  1649. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  1650. },
  1651. readOnlyChanged: function(val) {
  1652. this.div.contentEditable = String(val != "nocursor")
  1653. },
  1654. onContextMenu: nothing,
  1655. resetPosition: nothing,
  1656. needsContentAttribute: true
  1657. }, ContentEditableInput.prototype);
  1658. function posToDOM(cm, pos) {
  1659. var view = findViewForLine(cm, pos.line);
  1660. if (!view || view.hidden) return null;
  1661. var line = getLine(cm.doc, pos.line);
  1662. var info = mapFromLineView(view, line, pos.line);
  1663. var order = getOrder(line), side = "left";
  1664. if (order) {
  1665. var partPos = getBidiPartAt(order, pos.ch);
  1666. side = partPos % 2 ? "right" : "left";
  1667. }
  1668. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  1669. result.offset = result.collapse == "right" ? result.end : result.start;
  1670. return result;
  1671. }
  1672. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  1673. function domToPos(cm, node, offset) {
  1674. var lineNode;
  1675. if (node == cm.display.lineDiv) {
  1676. lineNode = cm.display.lineDiv.childNodes[offset];
  1677. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  1678. node = null; offset = 0;
  1679. } else {
  1680. for (lineNode = node;; lineNode = lineNode.parentNode) {
  1681. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  1682. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  1683. }
  1684. }
  1685. for (var i = 0; i < cm.display.view.length; i++) {
  1686. var lineView = cm.display.view[i];
  1687. if (lineView.node == lineNode)
  1688. return locateNodeInLineView(lineView, node, offset);
  1689. }
  1690. }
  1691. function locateNodeInLineView(lineView, node, offset) {
  1692. var wrapper = lineView.text.firstChild, bad = false;
  1693. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  1694. if (node == wrapper) {
  1695. bad = true;
  1696. node = wrapper.childNodes[offset];
  1697. offset = 0;
  1698. if (!node) {
  1699. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  1700. return badPos(Pos(lineNo(line), line.text.length), bad);
  1701. }
  1702. }
  1703. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  1704. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  1705. textNode = node.firstChild;
  1706. if (offset) offset = textNode.nodeValue.length;
  1707. }
  1708. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  1709. var measure = lineView.measure, maps = measure.maps;
  1710. function find(textNode, topNode, offset) {
  1711. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  1712. var map = i < 0 ? measure.map : maps[i];
  1713. for (var j = 0; j < map.length; j += 3) {
  1714. var curNode = map[j + 2];
  1715. if (curNode == textNode || curNode == topNode) {
  1716. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  1717. var ch = map[j] + offset;
  1718. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  1719. return Pos(line, ch);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. var found = find(textNode, topNode, offset);
  1725. if (found) return badPos(found, bad);
  1726. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  1727. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  1728. found = find(after, after.firstChild, 0);
  1729. if (found)
  1730. return badPos(Pos(found.line, found.ch - dist), bad);
  1731. else
  1732. dist += after.textContent.length;
  1733. }
  1734. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  1735. found = find(before, before.firstChild, -1);
  1736. if (found)
  1737. return badPos(Pos(found.line, found.ch + dist), bad);
  1738. else
  1739. dist += after.textContent.length;
  1740. }
  1741. }
  1742. function domTextBetween(cm, from, to, fromLine, toLine) {
  1743. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  1744. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  1745. function walk(node) {
  1746. if (node.nodeType == 1) {
  1747. var cmText = node.getAttribute("cm-text");
  1748. if (cmText != null) {
  1749. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  1750. text += cmText;
  1751. return;
  1752. }
  1753. var markerID = node.getAttribute("cm-marker"), range;
  1754. if (markerID) {
  1755. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  1756. if (found.length && (range = found[0].find()))
  1757. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  1758. return;
  1759. }
  1760. if (node.getAttribute("contenteditable") == "false") return;
  1761. for (var i = 0; i < node.childNodes.length; i++)
  1762. walk(node.childNodes[i]);
  1763. if (/^(pre|div|p)$/i.test(node.nodeName))
  1764. closing = true;
  1765. } else if (node.nodeType == 3) {
  1766. var val = node.nodeValue;
  1767. if (!val) return;
  1768. if (closing) {
  1769. text += lineSep;
  1770. closing = false;
  1771. }
  1772. text += val;
  1773. }
  1774. }
  1775. for (;;) {
  1776. walk(from);
  1777. if (from == to) break;
  1778. from = from.nextSibling;
  1779. }
  1780. return text;
  1781. }
  1782. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  1783. // SELECTION / CURSOR
  1784. // Selection objects are immutable. A new one is created every time
  1785. // the selection changes. A selection is one or more non-overlapping
  1786. // (and non-touching) ranges, sorted, and an integer that indicates
  1787. // which one is the primary selection (the one that's scrolled into
  1788. // view, that getCursor returns, etc).
  1789. function Selection(ranges, primIndex) {
  1790. this.ranges = ranges;
  1791. this.primIndex = primIndex;
  1792. }
  1793. Selection.prototype = {
  1794. primary: function() { return this.ranges[this.primIndex]; },
  1795. equals: function(other) {
  1796. if (other == this) return true;
  1797. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  1798. for (var i = 0; i < this.ranges.length; i++) {
  1799. var here = this.ranges[i], there = other.ranges[i];
  1800. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  1801. }
  1802. return true;
  1803. },
  1804. deepCopy: function() {
  1805. for (var out = [], i = 0; i < this.ranges.length; i++)
  1806. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  1807. return new Selection(out, this.primIndex);
  1808. },
  1809. somethingSelected: function() {
  1810. for (var i = 0; i < this.ranges.length; i++)
  1811. if (!this.ranges[i].empty()) return true;
  1812. return false;
  1813. },
  1814. contains: function(pos, end) {
  1815. if (!end) end = pos;
  1816. for (var i = 0; i < this.ranges.length; i++) {
  1817. var range = this.ranges[i];
  1818. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  1819. return i;
  1820. }
  1821. return -1;
  1822. }
  1823. };
  1824. function Range(anchor, head) {
  1825. this.anchor = anchor; this.head = head;
  1826. }
  1827. Range.prototype = {
  1828. from: function() { return minPos(this.anchor, this.head); },
  1829. to: function() { return maxPos(this.anchor, this.head); },
  1830. empty: function() {
  1831. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  1832. }
  1833. };
  1834. // Take an unsorted, potentially overlapping set of ranges, and
  1835. // build a selection out of it. 'Consumes' ranges array (modifying
  1836. // it).
  1837. function normalizeSelection(ranges, primIndex) {
  1838. var prim = ranges[primIndex];
  1839. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  1840. primIndex = indexOf(ranges, prim);
  1841. for (var i = 1; i < ranges.length; i++) {
  1842. var cur = ranges[i], prev = ranges[i - 1];
  1843. if (cmp(prev.to(), cur.from()) >= 0) {
  1844. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  1845. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  1846. if (i <= primIndex) --primIndex;
  1847. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  1848. }
  1849. }
  1850. return new Selection(ranges, primIndex);
  1851. }
  1852. function simpleSelection(anchor, head) {
  1853. return new Selection([new Range(anchor, head || anchor)], 0);
  1854. }
  1855. // Most of the external API clips given positions to make sure they
  1856. // actually exist within the document.
  1857. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  1858. function clipPos(doc, pos) {
  1859. if (pos.line < doc.first) return Pos(doc.first, 0);
  1860. var last = doc.first + doc.size - 1;
  1861. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  1862. return clipToLen(pos, getLine(doc, pos.line).text.length);
  1863. }
  1864. function clipToLen(pos, linelen) {
  1865. var ch = pos.ch;
  1866. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  1867. else if (ch < 0) return Pos(pos.line, 0);
  1868. else return pos;
  1869. }
  1870. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  1871. function clipPosArray(doc, array) {
  1872. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  1873. return out;
  1874. }
  1875. // SELECTION UPDATES
  1876. // The 'scroll' parameter given to many of these indicated whether
  1877. // the new cursor position should be scrolled into view after
  1878. // modifying the selection.
  1879. // If shift is held or the extend flag is set, extends a range to
  1880. // include a given position (and optionally a second position).
  1881. // Otherwise, simply returns the range between the given positions.
  1882. // Used for cursor motion and such.
  1883. function extendRange(doc, range, head, other) {
  1884. if (doc.cm && doc.cm.display.shift || doc.extend) {
  1885. var anchor = range.anchor;
  1886. if (other) {
  1887. var posBefore = cmp(head, anchor) < 0;
  1888. if (posBefore != (cmp(other, anchor) < 0)) {
  1889. anchor = head;
  1890. head = other;
  1891. } else if (posBefore != (cmp(head, other) < 0)) {
  1892. head = other;
  1893. }
  1894. }
  1895. return new Range(anchor, head);
  1896. } else {
  1897. return new Range(other || head, head);
  1898. }
  1899. }
  1900. // Extend the primary selection range, discard the rest.
  1901. function extendSelection(doc, head, other, options) {
  1902. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  1903. }
  1904. // Extend all selections (pos is an array of selections with length
  1905. // equal the number of selections)
  1906. function extendSelections(doc, heads, options) {
  1907. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  1908. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  1909. var newSel = normalizeSelection(out, doc.sel.primIndex);
  1910. setSelection(doc, newSel, options);
  1911. }
  1912. // Updates a single range in the selection.
  1913. function replaceOneSelection(doc, i, range, options) {
  1914. var ranges = doc.sel.ranges.slice(0);
  1915. ranges[i] = range;
  1916. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  1917. }
  1918. // Reset the selection to a single range.
  1919. function setSimpleSelection(doc, anchor, head, options) {
  1920. setSelection(doc, simpleSelection(anchor, head), options);
  1921. }
  1922. // Give beforeSelectionChange handlers a change to influence a
  1923. // selection update.
  1924. function filterSelectionChange(doc, sel, options) {
  1925. var obj = {
  1926. ranges: sel.ranges,
  1927. update: function(ranges) {
  1928. this.ranges = [];
  1929. for (var i = 0; i < ranges.length; i++)
  1930. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  1931. clipPos(doc, ranges[i].head));
  1932. },
  1933. origin: options && options.origin
  1934. };
  1935. signal(doc, "beforeSelectionChange", doc, obj);
  1936. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  1937. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1938. else return sel;
  1939. }
  1940. function setSelectionReplaceHistory(doc, sel, options) {
  1941. var done = doc.history.done, last = lst(done);
  1942. if (last && last.ranges) {
  1943. done[done.length - 1] = sel;
  1944. setSelectionNoUndo(doc, sel, options);
  1945. } else {
  1946. setSelection(doc, sel, options);
  1947. }
  1948. }
  1949. // Set a new selection.
  1950. function setSelection(doc, sel, options) {
  1951. setSelectionNoUndo(doc, sel, options);
  1952. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1953. }
  1954. function setSelectionNoUndo(doc, sel, options) {
  1955. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1956. sel = filterSelectionChange(doc, sel, options);
  1957. var bias = options && options.bias ||
  1958. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  1959. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1960. if (!(options && options.scroll === false) && doc.cm)
  1961. ensureCursorVisible(doc.cm);
  1962. }
  1963. function setSelectionInner(doc, sel) {
  1964. if (sel.equals(doc.sel)) return;
  1965. doc.sel = sel;
  1966. if (doc.cm) {
  1967. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1968. signalCursorActivity(doc.cm);
  1969. }
  1970. signalLater(doc, "cursorActivity", doc);
  1971. }
  1972. // Verify that the selection does not partially select any atomic
  1973. // marked ranges.
  1974. function reCheckSelection(doc) {
  1975. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1976. }
  1977. // Return a selection that does not partially select any atomic
  1978. // ranges.
  1979. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1980. var out;
  1981. for (var i = 0; i < sel.ranges.length; i++) {
  1982. var range = sel.ranges[i];
  1983. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  1984. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  1985. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  1986. if (out || newAnchor != range.anchor || newHead != range.head) {
  1987. if (!out) out = sel.ranges.slice(0, i);
  1988. out[i] = new Range(newAnchor, newHead);
  1989. }
  1990. }
  1991. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1992. }
  1993. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  1994. var line = getLine(doc, pos.line);
  1995. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  1996. var sp = line.markedSpans[i], m = sp.marker;
  1997. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  1998. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  1999. if (mayClear) {
  2000. signal(m, "beforeCursorEnter");
  2001. if (m.explicitlyCleared) {
  2002. if (!line.markedSpans) break;
  2003. else {--i; continue;}
  2004. }
  2005. }
  2006. if (!m.atomic) continue;
  2007. if (oldPos) {
  2008. var near = m.find(dir < 0 ? 1 : -1), diff;
  2009. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  2010. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  2011. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  2012. return skipAtomicInner(doc, near, pos, dir, mayClear);
  2013. }
  2014. var far = m.find(dir < 0 ? -1 : 1);
  2015. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  2016. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  2017. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  2018. }
  2019. }
  2020. return pos;
  2021. }
  2022. // Ensure a given position is not inside an atomic range.
  2023. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  2024. var dir = bias || 1;
  2025. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  2026. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  2027. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  2028. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  2029. if (!found) {
  2030. doc.cantEdit = true;
  2031. return Pos(doc.first, 0);
  2032. }
  2033. return found;
  2034. }
  2035. function movePos(doc, pos, dir, line) {
  2036. if (dir < 0 && pos.ch == 0) {
  2037. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  2038. else return null;
  2039. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  2040. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  2041. else return null;
  2042. } else {
  2043. return new Pos(pos.line, pos.ch + dir);
  2044. }
  2045. }
  2046. // SELECTION DRAWING
  2047. function updateSelection(cm) {
  2048. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2049. }
  2050. function prepareSelection(cm, primary) {
  2051. var doc = cm.doc, result = {};
  2052. var curFragment = result.cursors = document.createDocumentFragment();
  2053. var selFragment = result.selection = document.createDocumentFragment();
  2054. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2055. if (primary === false && i == doc.sel.primIndex) continue;
  2056. var range = doc.sel.ranges[i];
  2057. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  2058. var collapsed = range.empty();
  2059. if (collapsed || cm.options.showCursorWhenSelecting)
  2060. drawSelectionCursor(cm, range.head, curFragment);
  2061. if (!collapsed)
  2062. drawSelectionRange(cm, range, selFragment);
  2063. }
  2064. return result;
  2065. }
  2066. // Draws a cursor for the given range
  2067. function drawSelectionCursor(cm, head, output) {
  2068. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2069. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2070. cursor.style.left = pos.left + "px";
  2071. cursor.style.top = pos.top + "px";
  2072. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2073. if (pos.other) {
  2074. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2075. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2076. otherCursor.style.display = "";
  2077. otherCursor.style.left = pos.other.left + "px";
  2078. otherCursor.style.top = pos.other.top + "px";
  2079. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2080. }
  2081. }
  2082. // Draws the given range as a highlighted selection
  2083. function drawSelectionRange(cm, range, output) {
  2084. var display = cm.display, doc = cm.doc;
  2085. var fragment = document.createDocumentFragment();
  2086. var padding = paddingH(cm.display), leftSide = padding.left;
  2087. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2088. function add(left, top, width, bottom) {
  2089. if (top < 0) top = 0;
  2090. top = Math.round(top);
  2091. bottom = Math.round(bottom);
  2092. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  2093. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  2094. "px; height: " + (bottom - top) + "px"));
  2095. }
  2096. function drawForLine(line, fromArg, toArg) {
  2097. var lineObj = getLine(doc, line);
  2098. var lineLen = lineObj.text.length;
  2099. var start, end;
  2100. function coords(ch, bias) {
  2101. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  2102. }
  2103. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  2104. var leftPos = coords(from, "left"), rightPos, left, right;
  2105. if (from == to) {
  2106. rightPos = leftPos;
  2107. left = right = leftPos.left;
  2108. } else {
  2109. rightPos = coords(to - 1, "right");
  2110. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  2111. left = leftPos.left;
  2112. right = rightPos.right;
  2113. }
  2114. if (fromArg == null && from == 0) left = leftSide;
  2115. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  2116. add(left, leftPos.top, null, leftPos.bottom);
  2117. left = leftSide;
  2118. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  2119. }
  2120. if (toArg == null && to == lineLen) right = rightSide;
  2121. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  2122. start = leftPos;
  2123. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  2124. end = rightPos;
  2125. if (left < leftSide + 1) left = leftSide;
  2126. add(left, rightPos.top, right - left, rightPos.bottom);
  2127. });
  2128. return {start: start, end: end};
  2129. }
  2130. var sFrom = range.from(), sTo = range.to();
  2131. if (sFrom.line == sTo.line) {
  2132. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2133. } else {
  2134. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2135. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2136. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2137. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2138. if (singleVLine) {
  2139. if (leftEnd.top < rightStart.top - 2) {
  2140. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2141. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2142. } else {
  2143. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2144. }
  2145. }
  2146. if (leftEnd.bottom < rightStart.top)
  2147. add(leftSide, leftEnd.bottom, null, rightStart.top);
  2148. }
  2149. output.appendChild(fragment);
  2150. }
  2151. // Cursor-blinking
  2152. function restartBlink(cm) {
  2153. if (!cm.state.focused) return;
  2154. var display = cm.display;
  2155. clearInterval(display.blinker);
  2156. var on = true;
  2157. display.cursorDiv.style.visibility = "";
  2158. if (cm.options.cursorBlinkRate > 0)
  2159. display.blinker = setInterval(function() {
  2160. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  2161. }, cm.options.cursorBlinkRate);
  2162. else if (cm.options.cursorBlinkRate < 0)
  2163. display.cursorDiv.style.visibility = "hidden";
  2164. }
  2165. // HIGHLIGHT WORKER
  2166. function startWorker(cm, time) {
  2167. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  2168. cm.state.highlight.set(time, bind(highlightWorker, cm));
  2169. }
  2170. function highlightWorker(cm) {
  2171. var doc = cm.doc;
  2172. if (doc.frontier < doc.first) doc.frontier = doc.first;
  2173. if (doc.frontier >= cm.display.viewTo) return;
  2174. var end = +new Date + cm.options.workTime;
  2175. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  2176. var changedLines = [];
  2177. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  2178. if (doc.frontier >= cm.display.viewFrom) { // Visible
  2179. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  2180. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  2181. line.styles = highlighted.styles;
  2182. var oldCls = line.styleClasses, newCls = highlighted.classes;
  2183. if (newCls) line.styleClasses = newCls;
  2184. else if (oldCls) line.styleClasses = null;
  2185. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  2186. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  2187. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  2188. if (ischange) changedLines.push(doc.frontier);
  2189. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  2190. } else {
  2191. if (line.text.length <= cm.options.maxHighlightLength)
  2192. processLine(cm, line.text, state);
  2193. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  2194. }
  2195. ++doc.frontier;
  2196. if (+new Date > end) {
  2197. startWorker(cm, cm.options.workDelay);
  2198. return true;
  2199. }
  2200. });
  2201. if (changedLines.length) runInOp(cm, function() {
  2202. for (var i = 0; i < changedLines.length; i++)
  2203. regLineChange(cm, changedLines[i], "text");
  2204. });
  2205. }
  2206. // Finds the line to start with when starting a parse. Tries to
  2207. // find a line with a stateAfter, so that it can start with a
  2208. // valid state. If that fails, it returns the line with the
  2209. // smallest indentation, which tends to need the least context to
  2210. // parse correctly.
  2211. function findStartLine(cm, n, precise) {
  2212. var minindent, minline, doc = cm.doc;
  2213. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  2214. for (var search = n; search > lim; --search) {
  2215. if (search <= doc.first) return doc.first;
  2216. var line = getLine(doc, search - 1);
  2217. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  2218. var indented = countColumn(line.text, null, cm.options.tabSize);
  2219. if (minline == null || minindent > indented) {
  2220. minline = search - 1;
  2221. minindent = indented;
  2222. }
  2223. }
  2224. return minline;
  2225. }
  2226. function getStateBefore(cm, n, precise) {
  2227. var doc = cm.doc, display = cm.display;
  2228. if (!doc.mode.startState) return true;
  2229. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  2230. if (!state) state = startState(doc.mode);
  2231. else state = copyState(doc.mode, state);
  2232. doc.iter(pos, n, function(line) {
  2233. processLine(cm, line.text, state);
  2234. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  2235. line.stateAfter = save ? copyState(doc.mode, state) : null;
  2236. ++pos;
  2237. });
  2238. if (precise) doc.frontier = pos;
  2239. return state;
  2240. }
  2241. // POSITION MEASUREMENT
  2242. function paddingTop(display) {return display.lineSpace.offsetTop;}
  2243. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  2244. function paddingH(display) {
  2245. if (display.cachedPaddingH) return display.cachedPaddingH;
  2246. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2247. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2248. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2249. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  2250. return data;
  2251. }
  2252. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  2253. function displayWidth(cm) {
  2254. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  2255. }
  2256. function displayHeight(cm) {
  2257. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  2258. }
  2259. // Ensure the lineView.wrapping.heights array is populated. This is
  2260. // an array of bottom offsets for the lines that make up a drawn
  2261. // line. When lineWrapping is on, there might be more than one
  2262. // height.
  2263. function ensureLineHeights(cm, lineView, rect) {
  2264. var wrapping = cm.options.lineWrapping;
  2265. var curWidth = wrapping && displayWidth(cm);
  2266. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2267. var heights = lineView.measure.heights = [];
  2268. if (wrapping) {
  2269. lineView.measure.width = curWidth;
  2270. var rects = lineView.text.firstChild.getClientRects();
  2271. for (var i = 0; i < rects.length - 1; i++) {
  2272. var cur = rects[i], next = rects[i + 1];
  2273. if (Math.abs(cur.bottom - next.bottom) > 2)
  2274. heights.push((cur.bottom + next.top) / 2 - rect.top);
  2275. }
  2276. }
  2277. heights.push(rect.bottom - rect.top);
  2278. }
  2279. }
  2280. // Find a line map (mapping character offsets to text nodes) and a
  2281. // measurement cache for the given line number. (A line view might
  2282. // contain multiple lines when collapsed ranges are present.)
  2283. function mapFromLineView(lineView, line, lineN) {
  2284. if (lineView.line == line)
  2285. return {map: lineView.measure.map, cache: lineView.measure.cache};
  2286. for (var i = 0; i < lineView.rest.length; i++)
  2287. if (lineView.rest[i] == line)
  2288. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  2289. for (var i = 0; i < lineView.rest.length; i++)
  2290. if (lineNo(lineView.rest[i]) > lineN)
  2291. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  2292. }
  2293. // Render a line into the hidden node display.externalMeasured. Used
  2294. // when measurement is needed for a line that's not in the viewport.
  2295. function updateExternalMeasurement(cm, line) {
  2296. line = visualLine(line);
  2297. var lineN = lineNo(line);
  2298. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2299. view.lineN = lineN;
  2300. var built = view.built = buildLineContent(cm, view);
  2301. view.text = built.pre;
  2302. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2303. return view;
  2304. }
  2305. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2306. // for a given character.
  2307. function measureChar(cm, line, ch, bias) {
  2308. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  2309. }
  2310. // Find a line view that corresponds to the given line number.
  2311. function findViewForLine(cm, lineN) {
  2312. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2313. return cm.display.view[findViewIndex(cm, lineN)];
  2314. var ext = cm.display.externalMeasured;
  2315. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2316. return ext;
  2317. }
  2318. // Measurement can be split in two steps, the set-up work that
  2319. // applies to the whole line, and the measurement of the actual
  2320. // character. Functions like coordsChar, that need to do a lot of
  2321. // measurements in a row, can thus ensure that the set-up work is
  2322. // only done once.
  2323. function prepareMeasureForLine(cm, line) {
  2324. var lineN = lineNo(line);
  2325. var view = findViewForLine(cm, lineN);
  2326. if (view && !view.text) {
  2327. view = null;
  2328. } else if (view && view.changes) {
  2329. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2330. cm.curOp.forceUpdate = true;
  2331. }
  2332. if (!view)
  2333. view = updateExternalMeasurement(cm, line);
  2334. var info = mapFromLineView(view, line, lineN);
  2335. return {
  2336. line: line, view: view, rect: null,
  2337. map: info.map, cache: info.cache, before: info.before,
  2338. hasHeights: false
  2339. };
  2340. }
  2341. // Given a prepared measurement object, measures the position of an
  2342. // actual character (or fetches it from the cache).
  2343. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2344. if (prepared.before) ch = -1;
  2345. var key = ch + (bias || ""), found;
  2346. if (prepared.cache.hasOwnProperty(key)) {
  2347. found = prepared.cache[key];
  2348. } else {
  2349. if (!prepared.rect)
  2350. prepared.rect = prepared.view.text.getBoundingClientRect();
  2351. if (!prepared.hasHeights) {
  2352. ensureLineHeights(cm, prepared.view, prepared.rect);
  2353. prepared.hasHeights = true;
  2354. }
  2355. found = measureCharInner(cm, prepared, ch, bias);
  2356. if (!found.bogus) prepared.cache[key] = found;
  2357. }
  2358. return {left: found.left, right: found.right,
  2359. top: varHeight ? found.rtop : found.top,
  2360. bottom: varHeight ? found.rbottom : found.bottom};
  2361. }
  2362. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2363. function nodeAndOffsetInLineMap(map, ch, bias) {
  2364. var node, start, end, collapse;
  2365. // First, search the line map for the text node corresponding to,
  2366. // or closest to, the target character.
  2367. for (var i = 0; i < map.length; i += 3) {
  2368. var mStart = map[i], mEnd = map[i + 1];
  2369. if (ch < mStart) {
  2370. start = 0; end = 1;
  2371. collapse = "left";
  2372. } else if (ch < mEnd) {
  2373. start = ch - mStart;
  2374. end = start + 1;
  2375. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2376. end = mEnd - mStart;
  2377. start = end - 1;
  2378. if (ch >= mEnd) collapse = "right";
  2379. }
  2380. if (start != null) {
  2381. node = map[i + 2];
  2382. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2383. collapse = bias;
  2384. if (bias == "left" && start == 0)
  2385. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2386. node = map[(i -= 3) + 2];
  2387. collapse = "left";
  2388. }
  2389. if (bias == "right" && start == mEnd - mStart)
  2390. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2391. node = map[(i += 3) + 2];
  2392. collapse = "right";
  2393. }
  2394. break;
  2395. }
  2396. }
  2397. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  2398. }
  2399. function measureCharInner(cm, prepared, ch, bias) {
  2400. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2401. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2402. var rect;
  2403. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2404. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2405. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  2406. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  2407. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  2408. rect = node.parentNode.getBoundingClientRect();
  2409. } else if (ie && cm.options.lineWrapping) {
  2410. var rects = range(node, start, end).getClientRects();
  2411. if (rects.length)
  2412. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2413. else
  2414. rect = nullRect;
  2415. } else {
  2416. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  2417. }
  2418. if (rect.left || rect.right || start == 0) break;
  2419. end = start;
  2420. start = start - 1;
  2421. collapse = "right";
  2422. }
  2423. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  2424. } else { // If it is a widget, simply get the box for the whole widget.
  2425. if (start > 0) collapse = bias = "right";
  2426. var rects;
  2427. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2428. rect = rects[bias == "right" ? rects.length - 1 : 0];
  2429. else
  2430. rect = node.getBoundingClientRect();
  2431. }
  2432. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2433. var rSpan = node.parentNode.getClientRects()[0];
  2434. if (rSpan)
  2435. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  2436. else
  2437. rect = nullRect;
  2438. }
  2439. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2440. var mid = (rtop + rbot) / 2;
  2441. var heights = prepared.view.measure.heights;
  2442. for (var i = 0; i < heights.length - 1; i++)
  2443. if (mid < heights[i]) break;
  2444. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2445. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2446. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2447. top: top, bottom: bot};
  2448. if (!rect.left && !rect.right) result.bogus = true;
  2449. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2450. return result;
  2451. }
  2452. // Work around problem with bounding client rects on ranges being
  2453. // returned incorrectly when zoomed on IE10 and below.
  2454. function maybeUpdateRectForZooming(measure, rect) {
  2455. if (!window.screen || screen.logicalXDPI == null ||
  2456. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2457. return rect;
  2458. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2459. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2460. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2461. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  2462. }
  2463. function clearLineMeasurementCacheFor(lineView) {
  2464. if (lineView.measure) {
  2465. lineView.measure.cache = {};
  2466. lineView.measure.heights = null;
  2467. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2468. lineView.measure.caches[i] = {};
  2469. }
  2470. }
  2471. function clearLineMeasurementCache(cm) {
  2472. cm.display.externalMeasure = null;
  2473. removeChildren(cm.display.lineMeasure);
  2474. for (var i = 0; i < cm.display.view.length; i++)
  2475. clearLineMeasurementCacheFor(cm.display.view[i]);
  2476. }
  2477. function clearCaches(cm) {
  2478. clearLineMeasurementCache(cm);
  2479. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2480. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  2481. cm.display.lineNumChars = null;
  2482. }
  2483. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  2484. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  2485. // Converts a {top, bottom, left, right} box from line-local
  2486. // coordinates into another coordinate system. Context may be one of
  2487. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  2488. // or "page".
  2489. function intoCoordSystem(cm, lineObj, rect, context) {
  2490. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  2491. var size = widgetHeight(lineObj.widgets[i]);
  2492. rect.top += size; rect.bottom += size;
  2493. }
  2494. if (context == "line") return rect;
  2495. if (!context) context = "local";
  2496. var yOff = heightAtLine(lineObj);
  2497. if (context == "local") yOff += paddingTop(cm.display);
  2498. else yOff -= cm.display.viewOffset;
  2499. if (context == "page" || context == "window") {
  2500. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2501. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2502. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2503. rect.left += xOff; rect.right += xOff;
  2504. }
  2505. rect.top += yOff; rect.bottom += yOff;
  2506. return rect;
  2507. }
  2508. // Coverts a box from "div" coords to another coordinate system.
  2509. // Context may be "window", "page", "div", or "local"/null.
  2510. function fromCoordSystem(cm, coords, context) {
  2511. if (context == "div") return coords;
  2512. var left = coords.left, top = coords.top;
  2513. // First move into "page" coordinate system
  2514. if (context == "page") {
  2515. left -= pageScrollX();
  2516. top -= pageScrollY();
  2517. } else if (context == "local" || !context) {
  2518. var localBox = cm.display.sizer.getBoundingClientRect();
  2519. left += localBox.left;
  2520. top += localBox.top;
  2521. }
  2522. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2523. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  2524. }
  2525. function charCoords(cm, pos, context, lineObj, bias) {
  2526. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  2527. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  2528. }
  2529. // Returns a box for a given cursor position, which may have an
  2530. // 'other' property containing the position of the secondary cursor
  2531. // on a bidi boundary.
  2532. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2533. lineObj = lineObj || getLine(cm.doc, pos.line);
  2534. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2535. function get(ch, right) {
  2536. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2537. if (right) m.left = m.right; else m.right = m.left;
  2538. return intoCoordSystem(cm, lineObj, m, context);
  2539. }
  2540. function getBidi(ch, partPos) {
  2541. var part = order[partPos], right = part.level % 2;
  2542. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  2543. part = order[--partPos];
  2544. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  2545. right = true;
  2546. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  2547. part = order[++partPos];
  2548. ch = bidiLeft(part) - part.level % 2;
  2549. right = false;
  2550. }
  2551. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  2552. return get(ch, right);
  2553. }
  2554. var order = getOrder(lineObj), ch = pos.ch;
  2555. if (!order) return get(ch);
  2556. var partPos = getBidiPartAt(order, ch);
  2557. var val = getBidi(ch, partPos);
  2558. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  2559. return val;
  2560. }
  2561. // Used to cheaply estimate the coordinates for a position. Used for
  2562. // intermediate scroll updates.
  2563. function estimateCoords(cm, pos) {
  2564. var left = 0, pos = clipPos(cm.doc, pos);
  2565. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  2566. var lineObj = getLine(cm.doc, pos.line);
  2567. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2568. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  2569. }
  2570. // Positions returned by coordsChar contain some extra information.
  2571. // xRel is the relative x position of the input coordinates compared
  2572. // to the found position (so xRel > 0 means the coordinates are to
  2573. // the right of the character position, for example). When outside
  2574. // is true, that means the coordinates lie outside the line's
  2575. // vertical range.
  2576. function PosWithInfo(line, ch, outside, xRel) {
  2577. var pos = Pos(line, ch);
  2578. pos.xRel = xRel;
  2579. if (outside) pos.outside = true;
  2580. return pos;
  2581. }
  2582. // Compute the character position closest to the given coordinates.
  2583. // Input must be lineSpace-local ("div" coordinate system).
  2584. function coordsChar(cm, x, y) {
  2585. var doc = cm.doc;
  2586. y += cm.display.viewOffset;
  2587. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  2588. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2589. if (lineN > last)
  2590. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  2591. if (x < 0) x = 0;
  2592. var lineObj = getLine(doc, lineN);
  2593. for (;;) {
  2594. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2595. var merged = collapsedSpanAtEnd(lineObj);
  2596. var mergedPos = merged && merged.find(0, true);
  2597. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2598. lineN = lineNo(lineObj = mergedPos.to.line);
  2599. else
  2600. return found;
  2601. }
  2602. }
  2603. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2604. var innerOff = y - heightAtLine(lineObj);
  2605. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  2606. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2607. function getX(ch) {
  2608. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  2609. wrongLine = true;
  2610. if (innerOff > sp.bottom) return sp.left - adjust;
  2611. else if (innerOff < sp.top) return sp.left + adjust;
  2612. else wrongLine = false;
  2613. return sp.left;
  2614. }
  2615. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  2616. var from = lineLeft(lineObj), to = lineRight(lineObj);
  2617. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  2618. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  2619. // Do a binary search between these bounds.
  2620. for (;;) {
  2621. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  2622. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  2623. var xDiff = x - (ch == from ? fromX : toX);
  2624. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  2625. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  2626. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  2627. return pos;
  2628. }
  2629. var step = Math.ceil(dist / 2), middle = from + step;
  2630. if (bidi) {
  2631. middle = from;
  2632. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  2633. }
  2634. var middleX = getX(middle);
  2635. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  2636. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  2637. }
  2638. }
  2639. var measureText;
  2640. // Compute the default text height.
  2641. function textHeight(display) {
  2642. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  2643. if (measureText == null) {
  2644. measureText = elt("pre");
  2645. // Measure a bunch of lines, for browsers that compute
  2646. // fractional heights.
  2647. for (var i = 0; i < 49; ++i) {
  2648. measureText.appendChild(document.createTextNode("x"));
  2649. measureText.appendChild(elt("br"));
  2650. }
  2651. measureText.appendChild(document.createTextNode("x"));
  2652. }
  2653. removeChildrenAndAdd(display.measure, measureText);
  2654. var height = measureText.offsetHeight / 50;
  2655. if (height > 3) display.cachedTextHeight = height;
  2656. removeChildren(display.measure);
  2657. return height || 1;
  2658. }
  2659. // Compute the default character width.
  2660. function charWidth(display) {
  2661. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  2662. var anchor = elt("span", "xxxxxxxxxx");
  2663. var pre = elt("pre", [anchor]);
  2664. removeChildrenAndAdd(display.measure, pre);
  2665. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2666. if (width > 2) display.cachedCharWidth = width;
  2667. return width || 10;
  2668. }
  2669. // OPERATIONS
  2670. // Operations are used to wrap a series of changes to the editor
  2671. // state in such a way that each change won't have to update the
  2672. // cursor and display (which would be awkward, slow, and
  2673. // error-prone). Instead, display updates are batched and then all
  2674. // combined and executed at once.
  2675. var operationGroup = null;
  2676. var nextOpId = 0;
  2677. // Start a new operation.
  2678. function startOperation(cm) {
  2679. cm.curOp = {
  2680. cm: cm,
  2681. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  2682. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  2683. forceUpdate: false, // Used to force a redraw
  2684. updateInput: null, // Whether to reset the input textarea
  2685. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  2686. changeObjs: null, // Accumulated changes, for firing change events
  2687. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  2688. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  2689. selectionChanged: false, // Whether the selection needs to be redrawn
  2690. updateMaxLine: false, // Set when the widest line needs to be determined anew
  2691. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  2692. scrollToPos: null, // Used to scroll to a specific position
  2693. focus: false,
  2694. id: ++nextOpId // Unique ID
  2695. };
  2696. if (operationGroup) {
  2697. operationGroup.ops.push(cm.curOp);
  2698. } else {
  2699. cm.curOp.ownsGroup = operationGroup = {
  2700. ops: [cm.curOp],
  2701. delayedCallbacks: []
  2702. };
  2703. }
  2704. }
  2705. function fireCallbacksForOps(group) {
  2706. // Calls delayed callbacks and cursorActivity handlers until no
  2707. // new ones appear
  2708. var callbacks = group.delayedCallbacks, i = 0;
  2709. do {
  2710. for (; i < callbacks.length; i++)
  2711. callbacks[i].call(null);
  2712. for (var j = 0; j < group.ops.length; j++) {
  2713. var op = group.ops[j];
  2714. if (op.cursorActivityHandlers)
  2715. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  2716. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  2717. }
  2718. } while (i < callbacks.length);
  2719. }
  2720. // Finish an operation, updating the display and signalling delayed events
  2721. function endOperation(cm) {
  2722. var op = cm.curOp, group = op.ownsGroup;
  2723. if (!group) return;
  2724. try { fireCallbacksForOps(group); }
  2725. finally {
  2726. operationGroup = null;
  2727. for (var i = 0; i < group.ops.length; i++)
  2728. group.ops[i].cm.curOp = null;
  2729. endOperations(group);
  2730. }
  2731. }
  2732. // The DOM updates done when an operation finishes are batched so
  2733. // that the minimum number of relayouts are required.
  2734. function endOperations(group) {
  2735. var ops = group.ops;
  2736. for (var i = 0; i < ops.length; i++) // Read DOM
  2737. endOperation_R1(ops[i]);
  2738. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2739. endOperation_W1(ops[i]);
  2740. for (var i = 0; i < ops.length; i++) // Read DOM
  2741. endOperation_R2(ops[i]);
  2742. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  2743. endOperation_W2(ops[i]);
  2744. for (var i = 0; i < ops.length; i++) // Read DOM
  2745. endOperation_finish(ops[i]);
  2746. }
  2747. function endOperation_R1(op) {
  2748. var cm = op.cm, display = cm.display;
  2749. maybeClipScrollbars(cm);
  2750. if (op.updateMaxLine) findMaxLine(cm);
  2751. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  2752. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  2753. op.scrollToPos.to.line >= display.viewTo) ||
  2754. display.maxLineChanged && cm.options.lineWrapping;
  2755. op.update = op.mustUpdate &&
  2756. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  2757. }
  2758. function endOperation_W1(op) {
  2759. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  2760. }
  2761. function endOperation_R2(op) {
  2762. var cm = op.cm, display = cm.display;
  2763. if (op.updatedDisplay) updateHeightsInViewport(cm);
  2764. op.barMeasure = measureForScrollbars(cm);
  2765. // If the max line changed since it was last measured, measure it,
  2766. // and ensure the document's width matches it.
  2767. // updateDisplay_W2 will use these properties to do the actual resizing
  2768. if (display.maxLineChanged && !cm.options.lineWrapping) {
  2769. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  2770. cm.display.sizerWidth = op.adjustWidthTo;
  2771. op.barMeasure.scrollWidth =
  2772. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  2773. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  2774. }
  2775. if (op.updatedDisplay || op.selectionChanged)
  2776. op.preparedSelection = display.input.prepareSelection(op.focus);
  2777. }
  2778. function endOperation_W2(op) {
  2779. var cm = op.cm;
  2780. if (op.adjustWidthTo != null) {
  2781. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  2782. if (op.maxScrollLeft < cm.doc.scrollLeft)
  2783. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  2784. cm.display.maxLineChanged = false;
  2785. }
  2786. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  2787. if (op.preparedSelection)
  2788. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  2789. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  2790. updateScrollbars(cm, op.barMeasure);
  2791. if (op.updatedDisplay)
  2792. setDocumentHeight(cm, op.barMeasure);
  2793. if (op.selectionChanged) restartBlink(cm);
  2794. if (cm.state.focused && op.updateInput)
  2795. cm.display.input.reset(op.typing);
  2796. if (takeFocus) ensureFocus(op.cm);
  2797. }
  2798. function endOperation_finish(op) {
  2799. var cm = op.cm, display = cm.display, doc = cm.doc;
  2800. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  2801. // Abort mouse wheel delta measurement, when scrolling explicitly
  2802. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  2803. display.wheelStartX = display.wheelStartY = null;
  2804. // Propagate the scroll position to the actual DOM scroller
  2805. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  2806. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  2807. display.scrollbars.setScrollTop(doc.scrollTop);
  2808. display.scroller.scrollTop = doc.scrollTop;
  2809. }
  2810. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  2811. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  2812. display.scrollbars.setScrollLeft(doc.scrollLeft);
  2813. display.scroller.scrollLeft = doc.scrollLeft;
  2814. alignHorizontally(cm);
  2815. }
  2816. // If we need to scroll a specific position into view, do so.
  2817. if (op.scrollToPos) {
  2818. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  2819. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  2820. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  2821. }
  2822. // Fire events for markers that are hidden/unidden by editing or
  2823. // undoing
  2824. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  2825. if (hidden) for (var i = 0; i < hidden.length; ++i)
  2826. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  2827. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  2828. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  2829. if (display.wrapper.offsetHeight)
  2830. doc.scrollTop = cm.display.scroller.scrollTop;
  2831. // Fire change events, and delayed event handlers
  2832. if (op.changeObjs)
  2833. signal(cm, "changes", cm, op.changeObjs);
  2834. if (op.update)
  2835. op.update.finish();
  2836. }
  2837. // Run the given function in an operation
  2838. function runInOp(cm, f) {
  2839. if (cm.curOp) return f();
  2840. startOperation(cm);
  2841. try { return f(); }
  2842. finally { endOperation(cm); }
  2843. }
  2844. // Wraps a function in an operation. Returns the wrapped function.
  2845. function operation(cm, f) {
  2846. return function() {
  2847. if (cm.curOp) return f.apply(cm, arguments);
  2848. startOperation(cm);
  2849. try { return f.apply(cm, arguments); }
  2850. finally { endOperation(cm); }
  2851. };
  2852. }
  2853. // Used to add methods to editor and doc instances, wrapping them in
  2854. // operations.
  2855. function methodOp(f) {
  2856. return function() {
  2857. if (this.curOp) return f.apply(this, arguments);
  2858. startOperation(this);
  2859. try { return f.apply(this, arguments); }
  2860. finally { endOperation(this); }
  2861. };
  2862. }
  2863. function docMethodOp(f) {
  2864. return function() {
  2865. var cm = this.cm;
  2866. if (!cm || cm.curOp) return f.apply(this, arguments);
  2867. startOperation(cm);
  2868. try { return f.apply(this, arguments); }
  2869. finally { endOperation(cm); }
  2870. };
  2871. }
  2872. // VIEW TRACKING
  2873. // These objects are used to represent the visible (currently drawn)
  2874. // part of the document. A LineView may correspond to multiple
  2875. // logical lines, if those are connected by collapsed ranges.
  2876. function LineView(doc, line, lineN) {
  2877. // The starting line
  2878. this.line = line;
  2879. // Continuing lines, if any
  2880. this.rest = visualLineContinued(line);
  2881. // Number of logical lines in this visual line
  2882. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  2883. this.node = this.text = null;
  2884. this.hidden = lineIsHidden(doc, line);
  2885. }
  2886. // Create a range of LineView objects for the given lines.
  2887. function buildViewArray(cm, from, to) {
  2888. var array = [], nextPos;
  2889. for (var pos = from; pos < to; pos = nextPos) {
  2890. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  2891. nextPos = pos + view.size;
  2892. array.push(view);
  2893. }
  2894. return array;
  2895. }
  2896. // Updates the display.view data structure for a given change to the
  2897. // document. From and to are in pre-change coordinates. Lendiff is
  2898. // the amount of lines added or subtracted by the change. This is
  2899. // used for changes that span multiple lines, or change the way
  2900. // lines are divided into visual lines. regLineChange (below)
  2901. // registers single-line changes.
  2902. function regChange(cm, from, to, lendiff) {
  2903. if (from == null) from = cm.doc.first;
  2904. if (to == null) to = cm.doc.first + cm.doc.size;
  2905. if (!lendiff) lendiff = 0;
  2906. var display = cm.display;
  2907. if (lendiff && to < display.viewTo &&
  2908. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2909. display.updateLineNumbers = from;
  2910. cm.curOp.viewChanged = true;
  2911. if (from >= display.viewTo) { // Change after
  2912. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2913. resetView(cm);
  2914. } else if (to <= display.viewFrom) { // Change before
  2915. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2916. resetView(cm);
  2917. } else {
  2918. display.viewFrom += lendiff;
  2919. display.viewTo += lendiff;
  2920. }
  2921. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2922. resetView(cm);
  2923. } else if (from <= display.viewFrom) { // Top overlap
  2924. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2925. if (cut) {
  2926. display.view = display.view.slice(cut.index);
  2927. display.viewFrom = cut.lineN;
  2928. display.viewTo += lendiff;
  2929. } else {
  2930. resetView(cm);
  2931. }
  2932. } else if (to >= display.viewTo) { // Bottom overlap
  2933. var cut = viewCuttingPoint(cm, from, from, -1);
  2934. if (cut) {
  2935. display.view = display.view.slice(0, cut.index);
  2936. display.viewTo = cut.lineN;
  2937. } else {
  2938. resetView(cm);
  2939. }
  2940. } else { // Gap in the middle
  2941. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2942. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2943. if (cutTop && cutBot) {
  2944. display.view = display.view.slice(0, cutTop.index)
  2945. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2946. .concat(display.view.slice(cutBot.index));
  2947. display.viewTo += lendiff;
  2948. } else {
  2949. resetView(cm);
  2950. }
  2951. }
  2952. var ext = display.externalMeasured;
  2953. if (ext) {
  2954. if (to < ext.lineN)
  2955. ext.lineN += lendiff;
  2956. else if (from < ext.lineN + ext.size)
  2957. display.externalMeasured = null;
  2958. }
  2959. }
  2960. // Register a change to a single line. Type must be one of "text",
  2961. // "gutter", "class", "widget"
  2962. function regLineChange(cm, line, type) {
  2963. cm.curOp.viewChanged = true;
  2964. var display = cm.display, ext = cm.display.externalMeasured;
  2965. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2966. display.externalMeasured = null;
  2967. if (line < display.viewFrom || line >= display.viewTo) return;
  2968. var lineView = display.view[findViewIndex(cm, line)];
  2969. if (lineView.node == null) return;
  2970. var arr = lineView.changes || (lineView.changes = []);
  2971. if (indexOf(arr, type) == -1) arr.push(type);
  2972. }
  2973. // Clear the view.
  2974. function resetView(cm) {
  2975. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2976. cm.display.view = [];
  2977. cm.display.viewOffset = 0;
  2978. }
  2979. // Find the view element corresponding to a given line. Return null
  2980. // when the line isn't visible.
  2981. function findViewIndex(cm, n) {
  2982. if (n >= cm.display.viewTo) return null;
  2983. n -= cm.display.viewFrom;
  2984. if (n < 0) return null;
  2985. var view = cm.display.view;
  2986. for (var i = 0; i < view.length; i++) {
  2987. n -= view[i].size;
  2988. if (n < 0) return i;
  2989. }
  2990. }
  2991. function viewCuttingPoint(cm, oldN, newN, dir) {
  2992. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2993. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2994. return {index: index, lineN: newN};
  2995. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  2996. n += view[i].size;
  2997. if (n != oldN) {
  2998. if (dir > 0) {
  2999. if (index == view.length - 1) return null;
  3000. diff = (n + view[index].size) - oldN;
  3001. index++;
  3002. } else {
  3003. diff = n - oldN;
  3004. }
  3005. oldN += diff; newN += diff;
  3006. }
  3007. while (visualLineNo(cm.doc, newN) != newN) {
  3008. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  3009. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3010. index += dir;
  3011. }
  3012. return {index: index, lineN: newN};
  3013. }
  3014. // Force the view to cover a given range, adding empty view element
  3015. // or clipping off existing ones as needed.
  3016. function adjustView(cm, from, to) {
  3017. var display = cm.display, view = display.view;
  3018. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3019. display.view = buildViewArray(cm, from, to);
  3020. display.viewFrom = from;
  3021. } else {
  3022. if (display.viewFrom > from)
  3023. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  3024. else if (display.viewFrom < from)
  3025. display.view = display.view.slice(findViewIndex(cm, from));
  3026. display.viewFrom = from;
  3027. if (display.viewTo < to)
  3028. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  3029. else if (display.viewTo > to)
  3030. display.view = display.view.slice(0, findViewIndex(cm, to));
  3031. }
  3032. display.viewTo = to;
  3033. }
  3034. // Count the number of lines in the view whose DOM representation is
  3035. // out of date (or nonexistent).
  3036. function countDirtyView(cm) {
  3037. var view = cm.display.view, dirty = 0;
  3038. for (var i = 0; i < view.length; i++) {
  3039. var lineView = view[i];
  3040. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  3041. }
  3042. return dirty;
  3043. }
  3044. // EVENT HANDLERS
  3045. // Attach the necessary event handlers when initializing the editor
  3046. function registerEventHandlers(cm) {
  3047. var d = cm.display;
  3048. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  3049. // Older IE's will not fire a second mousedown for a double click
  3050. if (ie && ie_version < 11)
  3051. on(d.scroller, "dblclick", operation(cm, function(e) {
  3052. if (signalDOMEvent(cm, e)) return;
  3053. var pos = posFromMouse(cm, e);
  3054. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  3055. e_preventDefault(e);
  3056. var word = cm.findWordAt(pos);
  3057. extendSelection(cm.doc, word.anchor, word.head);
  3058. }));
  3059. else
  3060. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  3061. // Some browsers fire contextmenu *after* opening the menu, at
  3062. // which point we can't mess with it anymore. Context menu is
  3063. // handled in onMouseDown for these browsers.
  3064. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  3065. // Used to suppress mouse event handling when a touch happens
  3066. var touchFinished, prevTouch = {end: 0};
  3067. function finishTouch() {
  3068. if (d.activeTouch) {
  3069. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  3070. prevTouch = d.activeTouch;
  3071. prevTouch.end = +new Date;
  3072. }
  3073. };
  3074. function isMouseLikeTouchEvent(e) {
  3075. if (e.touches.length != 1) return false;
  3076. var touch = e.touches[0];
  3077. return touch.radiusX <= 1 && touch.radiusY <= 1;
  3078. }
  3079. function farAway(touch, other) {
  3080. if (other.left == null) return true;
  3081. var dx = other.left - touch.left, dy = other.top - touch.top;
  3082. return dx * dx + dy * dy > 20 * 20;
  3083. }
  3084. on(d.scroller, "touchstart", function(e) {
  3085. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  3086. clearTimeout(touchFinished);
  3087. var now = +new Date;
  3088. d.activeTouch = {start: now, moved: false,
  3089. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  3090. if (e.touches.length == 1) {
  3091. d.activeTouch.left = e.touches[0].pageX;
  3092. d.activeTouch.top = e.touches[0].pageY;
  3093. }
  3094. }
  3095. });
  3096. on(d.scroller, "touchmove", function() {
  3097. if (d.activeTouch) d.activeTouch.moved = true;
  3098. });
  3099. on(d.scroller, "touchend", function(e) {
  3100. var touch = d.activeTouch;
  3101. if (touch && !eventInWidget(d, e) && touch.left != null &&
  3102. !touch.moved && new Date - touch.start < 300) {
  3103. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  3104. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  3105. range = new Range(pos, pos);
  3106. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  3107. range = cm.findWordAt(pos);
  3108. else // Triple tap
  3109. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  3110. cm.setSelection(range.anchor, range.head);
  3111. cm.focus();
  3112. e_preventDefault(e);
  3113. }
  3114. finishTouch();
  3115. });
  3116. on(d.scroller, "touchcancel", finishTouch);
  3117. // Sync scrolling between fake scrollbars and real scrollable
  3118. // area, ensure viewport is updated when scrolling.
  3119. on(d.scroller, "scroll", function() {
  3120. if (d.scroller.clientHeight) {
  3121. setScrollTop(cm, d.scroller.scrollTop);
  3122. setScrollLeft(cm, d.scroller.scrollLeft, true);
  3123. signal(cm, "scroll", cm);
  3124. }
  3125. });
  3126. // Listen to wheel events in order to try and update the viewport on time.
  3127. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  3128. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  3129. // Prevent wrapper from ever scrolling
  3130. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  3131. d.dragFunctions = {
  3132. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  3133. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  3134. start: function(e){onDragStart(cm, e);},
  3135. drop: operation(cm, onDrop),
  3136. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  3137. };
  3138. var inp = d.input.getField();
  3139. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  3140. on(inp, "keydown", operation(cm, onKeyDown));
  3141. on(inp, "keypress", operation(cm, onKeyPress));
  3142. on(inp, "focus", bind(onFocus, cm));
  3143. on(inp, "blur", bind(onBlur, cm));
  3144. }
  3145. function dragDropChanged(cm, value, old) {
  3146. var wasOn = old && old != CodeMirror.Init;
  3147. if (!value != !wasOn) {
  3148. var funcs = cm.display.dragFunctions;
  3149. var toggle = value ? on : off;
  3150. toggle(cm.display.scroller, "dragstart", funcs.start);
  3151. toggle(cm.display.scroller, "dragenter", funcs.enter);
  3152. toggle(cm.display.scroller, "dragover", funcs.over);
  3153. toggle(cm.display.scroller, "dragleave", funcs.leave);
  3154. toggle(cm.display.scroller, "drop", funcs.drop);
  3155. }
  3156. }
  3157. // Called when the window resizes
  3158. function onResize(cm) {
  3159. var d = cm.display;
  3160. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  3161. return;
  3162. // Might be a text scaling operation, clear size caches.
  3163. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3164. d.scrollbarsClipped = false;
  3165. cm.setSize();
  3166. }
  3167. // MOUSE EVENTS
  3168. // Return true when the given mouse event happened in a widget
  3169. function eventInWidget(display, e) {
  3170. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  3171. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  3172. (n.parentNode == display.sizer && n != display.mover))
  3173. return true;
  3174. }
  3175. }
  3176. // Given a mouse event, find the corresponding position. If liberal
  3177. // is false, it checks whether a gutter or scrollbar was clicked,
  3178. // and returns null if it was. forRect is used by rectangular
  3179. // selections, and tries to estimate a character position even for
  3180. // coordinates beyond the right of the text.
  3181. function posFromMouse(cm, e, liberal, forRect) {
  3182. var display = cm.display;
  3183. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  3184. var x, y, space = display.lineSpace.getBoundingClientRect();
  3185. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  3186. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  3187. catch (e) { return null; }
  3188. var coords = coordsChar(cm, x, y), line;
  3189. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  3190. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  3191. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  3192. }
  3193. return coords;
  3194. }
  3195. // A mouse down can be a single click, double click, triple click,
  3196. // start of selection drag, start of text drag, new cursor
  3197. // (ctrl-click), rectangle drag (alt-drag), or xwin
  3198. // middle-click-paste. Or it might be a click on something we should
  3199. // not interfere with, such as a scrollbar or widget.
  3200. function onMouseDown(e) {
  3201. var cm = this, display = cm.display;
  3202. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  3203. display.shift = e.shiftKey;
  3204. if (eventInWidget(display, e)) {
  3205. if (!webkit) {
  3206. // Briefly turn off draggability, to allow widgets to do
  3207. // normal dragging things.
  3208. display.scroller.draggable = false;
  3209. setTimeout(function(){display.scroller.draggable = true;}, 100);
  3210. }
  3211. return;
  3212. }
  3213. if (clickInGutter(cm, e)) return;
  3214. var start = posFromMouse(cm, e);
  3215. window.focus();
  3216. switch (e_button(e)) {
  3217. case 1:
  3218. // #3261: make sure, that we're not starting a second selection
  3219. if (cm.state.selectingText)
  3220. cm.state.selectingText(e);
  3221. else if (start)
  3222. leftButtonDown(cm, e, start);
  3223. else if (e_target(e) == display.scroller)
  3224. e_preventDefault(e);
  3225. break;
  3226. case 2:
  3227. if (webkit) cm.state.lastMiddleDown = +new Date;
  3228. if (start) extendSelection(cm.doc, start);
  3229. setTimeout(function() {display.input.focus();}, 20);
  3230. e_preventDefault(e);
  3231. break;
  3232. case 3:
  3233. if (captureRightClick) onContextMenu(cm, e);
  3234. else delayBlurEvent(cm);
  3235. break;
  3236. }
  3237. }
  3238. var lastClick, lastDoubleClick;
  3239. function leftButtonDown(cm, e, start) {
  3240. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  3241. else cm.curOp.focus = activeElt();
  3242. var now = +new Date, type;
  3243. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  3244. type = "triple";
  3245. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  3246. type = "double";
  3247. lastDoubleClick = {time: now, pos: start};
  3248. } else {
  3249. type = "single";
  3250. lastClick = {time: now, pos: start};
  3251. }
  3252. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  3253. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  3254. type == "single" && (contained = sel.contains(start)) > -1 &&
  3255. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  3256. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  3257. leftButtonStartDrag(cm, e, start, modifier);
  3258. else
  3259. leftButtonSelect(cm, e, start, type, modifier);
  3260. }
  3261. // Start a text drag. When it ends, see if any dragging actually
  3262. // happen, and treat as a click if it didn't.
  3263. function leftButtonStartDrag(cm, e, start, modifier) {
  3264. var display = cm.display, startTime = +new Date;
  3265. var dragEnd = operation(cm, function(e2) {
  3266. if (webkit) display.scroller.draggable = false;
  3267. cm.state.draggingText = false;
  3268. off(document, "mouseup", dragEnd);
  3269. off(display.scroller, "drop", dragEnd);
  3270. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  3271. e_preventDefault(e2);
  3272. if (!modifier && +new Date - 200 < startTime)
  3273. extendSelection(cm.doc, start);
  3274. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  3275. if (webkit || ie && ie_version == 9)
  3276. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  3277. else
  3278. display.input.focus();
  3279. }
  3280. });
  3281. // Let the drag handler handle this.
  3282. if (webkit) display.scroller.draggable = true;
  3283. cm.state.draggingText = dragEnd;
  3284. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  3285. // IE's approach to draggable
  3286. if (display.scroller.dragDrop) display.scroller.dragDrop();
  3287. on(document, "mouseup", dragEnd);
  3288. on(display.scroller, "drop", dragEnd);
  3289. }
  3290. // Normal selection, as opposed to text dragging.
  3291. function leftButtonSelect(cm, e, start, type, addNew) {
  3292. var display = cm.display, doc = cm.doc;
  3293. e_preventDefault(e);
  3294. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  3295. if (addNew && !e.shiftKey) {
  3296. ourIndex = doc.sel.contains(start);
  3297. if (ourIndex > -1)
  3298. ourRange = ranges[ourIndex];
  3299. else
  3300. ourRange = new Range(start, start);
  3301. } else {
  3302. ourRange = doc.sel.primary();
  3303. ourIndex = doc.sel.primIndex;
  3304. }
  3305. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  3306. type = "rect";
  3307. if (!addNew) ourRange = new Range(start, start);
  3308. start = posFromMouse(cm, e, true, true);
  3309. ourIndex = -1;
  3310. } else if (type == "double") {
  3311. var word = cm.findWordAt(start);
  3312. if (cm.display.shift || doc.extend)
  3313. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  3314. else
  3315. ourRange = word;
  3316. } else if (type == "triple") {
  3317. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  3318. if (cm.display.shift || doc.extend)
  3319. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  3320. else
  3321. ourRange = line;
  3322. } else {
  3323. ourRange = extendRange(doc, ourRange, start);
  3324. }
  3325. if (!addNew) {
  3326. ourIndex = 0;
  3327. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  3328. startSel = doc.sel;
  3329. } else if (ourIndex == -1) {
  3330. ourIndex = ranges.length;
  3331. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  3332. {scroll: false, origin: "*mouse"});
  3333. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  3334. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  3335. {scroll: false, origin: "*mouse"});
  3336. startSel = doc.sel;
  3337. } else {
  3338. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  3339. }
  3340. var lastPos = start;
  3341. function extendTo(pos) {
  3342. if (cmp(lastPos, pos) == 0) return;
  3343. lastPos = pos;
  3344. if (type == "rect") {
  3345. var ranges = [], tabSize = cm.options.tabSize;
  3346. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  3347. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  3348. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  3349. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  3350. line <= end; line++) {
  3351. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  3352. if (left == right)
  3353. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  3354. else if (text.length > leftPos)
  3355. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  3356. }
  3357. if (!ranges.length) ranges.push(new Range(start, start));
  3358. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  3359. {origin: "*mouse", scroll: false});
  3360. cm.scrollIntoView(pos);
  3361. } else {
  3362. var oldRange = ourRange;
  3363. var anchor = oldRange.anchor, head = pos;
  3364. if (type != "single") {
  3365. if (type == "double")
  3366. var range = cm.findWordAt(pos);
  3367. else
  3368. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  3369. if (cmp(range.anchor, anchor) > 0) {
  3370. head = range.head;
  3371. anchor = minPos(oldRange.from(), range.anchor);
  3372. } else {
  3373. head = range.anchor;
  3374. anchor = maxPos(oldRange.to(), range.head);
  3375. }
  3376. }
  3377. var ranges = startSel.ranges.slice(0);
  3378. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  3379. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  3380. }
  3381. }
  3382. var editorSize = display.wrapper.getBoundingClientRect();
  3383. // Used to ensure timeout re-tries don't fire when another extend
  3384. // happened in the meantime (clearTimeout isn't reliable -- at
  3385. // least on Chrome, the timeouts still happen even when cleared,
  3386. // if the clear happens after their scheduled firing time).
  3387. var counter = 0;
  3388. function extend(e) {
  3389. var curCount = ++counter;
  3390. var cur = posFromMouse(cm, e, true, type == "rect");
  3391. if (!cur) return;
  3392. if (cmp(cur, lastPos) != 0) {
  3393. cm.curOp.focus = activeElt();
  3394. extendTo(cur);
  3395. var visible = visibleLines(display, doc);
  3396. if (cur.line >= visible.to || cur.line < visible.from)
  3397. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  3398. } else {
  3399. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  3400. if (outside) setTimeout(operation(cm, function() {
  3401. if (counter != curCount) return;
  3402. display.scroller.scrollTop += outside;
  3403. extend(e);
  3404. }), 50);
  3405. }
  3406. }
  3407. function done(e) {
  3408. cm.state.selectingText = false;
  3409. counter = Infinity;
  3410. e_preventDefault(e);
  3411. display.input.focus();
  3412. off(document, "mousemove", move);
  3413. off(document, "mouseup", up);
  3414. doc.history.lastSelOrigin = null;
  3415. }
  3416. var move = operation(cm, function(e) {
  3417. if (!e_button(e)) done(e);
  3418. else extend(e);
  3419. });
  3420. var up = operation(cm, done);
  3421. cm.state.selectingText = up;
  3422. on(document, "mousemove", move);
  3423. on(document, "mouseup", up);
  3424. }
  3425. // Determines whether an event happened in the gutter, and fires the
  3426. // handlers for the corresponding event.
  3427. function gutterEvent(cm, e, type, prevent) {
  3428. try { var mX = e.clientX, mY = e.clientY; }
  3429. catch(e) { return false; }
  3430. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  3431. if (prevent) e_preventDefault(e);
  3432. var display = cm.display;
  3433. var lineBox = display.lineDiv.getBoundingClientRect();
  3434. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  3435. mY -= lineBox.top - display.viewOffset;
  3436. for (var i = 0; i < cm.options.gutters.length; ++i) {
  3437. var g = display.gutters.childNodes[i];
  3438. if (g && g.getBoundingClientRect().right >= mX) {
  3439. var line = lineAtHeight(cm.doc, mY);
  3440. var gutter = cm.options.gutters[i];
  3441. signal(cm, type, cm, line, gutter, e);
  3442. return e_defaultPrevented(e);
  3443. }
  3444. }
  3445. }
  3446. function clickInGutter(cm, e) {
  3447. return gutterEvent(cm, e, "gutterClick", true);
  3448. }
  3449. // Kludge to work around strange IE behavior where it'll sometimes
  3450. // re-fire a series of drag-related events right after the drop (#1551)
  3451. var lastDrop = 0;
  3452. function onDrop(e) {
  3453. var cm = this;
  3454. clearDragCursor(cm);
  3455. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  3456. return;
  3457. e_preventDefault(e);
  3458. if (ie) lastDrop = +new Date;
  3459. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  3460. if (!pos || cm.isReadOnly()) return;
  3461. // Might be a file drop, in which case we simply extract the text
  3462. // and insert it.
  3463. if (files && files.length && window.FileReader && window.File) {
  3464. var n = files.length, text = Array(n), read = 0;
  3465. var loadFile = function(file, i) {
  3466. if (cm.options.allowDropFileTypes &&
  3467. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  3468. return;
  3469. var reader = new FileReader;
  3470. reader.onload = operation(cm, function() {
  3471. var content = reader.result;
  3472. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  3473. text[i] = content;
  3474. if (++read == n) {
  3475. pos = clipPos(cm.doc, pos);
  3476. var change = {from: pos, to: pos,
  3477. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  3478. origin: "paste"};
  3479. makeChange(cm.doc, change);
  3480. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  3481. }
  3482. });
  3483. reader.readAsText(file);
  3484. };
  3485. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  3486. } else { // Normal drop
  3487. // Don't do a replace if the drop happened inside of the selected text.
  3488. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  3489. cm.state.draggingText(e);
  3490. // Ensure the editor is re-focused
  3491. setTimeout(function() {cm.display.input.focus();}, 20);
  3492. return;
  3493. }
  3494. try {
  3495. var text = e.dataTransfer.getData("Text");
  3496. if (text) {
  3497. if (cm.state.draggingText && !cm.state.draggingText.copy)
  3498. var selected = cm.listSelections();
  3499. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  3500. if (selected) for (var i = 0; i < selected.length; ++i)
  3501. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  3502. cm.replaceSelection(text, "around", "paste");
  3503. cm.display.input.focus();
  3504. }
  3505. }
  3506. catch(e){}
  3507. }
  3508. }
  3509. function onDragStart(cm, e) {
  3510. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  3511. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  3512. e.dataTransfer.setData("Text", cm.getSelection());
  3513. e.dataTransfer.effectAllowed = "copyMove"
  3514. // Use dummy image instead of default browsers image.
  3515. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  3516. if (e.dataTransfer.setDragImage && !safari) {
  3517. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  3518. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  3519. if (presto) {
  3520. img.width = img.height = 1;
  3521. cm.display.wrapper.appendChild(img);
  3522. // Force a relayout, or Opera won't use our image for some obscure reason
  3523. img._top = img.offsetTop;
  3524. }
  3525. e.dataTransfer.setDragImage(img, 0, 0);
  3526. if (presto) img.parentNode.removeChild(img);
  3527. }
  3528. }
  3529. function onDragOver(cm, e) {
  3530. var pos = posFromMouse(cm, e);
  3531. if (!pos) return;
  3532. var frag = document.createDocumentFragment();
  3533. drawSelectionCursor(cm, pos, frag);
  3534. if (!cm.display.dragCursor) {
  3535. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  3536. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  3537. }
  3538. removeChildrenAndAdd(cm.display.dragCursor, frag);
  3539. }
  3540. function clearDragCursor(cm) {
  3541. if (cm.display.dragCursor) {
  3542. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  3543. cm.display.dragCursor = null;
  3544. }
  3545. }
  3546. // SCROLL EVENTS
  3547. // Sync the scrollable area and scrollbars, ensure the viewport
  3548. // covers the visible area.
  3549. function setScrollTop(cm, val) {
  3550. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  3551. cm.doc.scrollTop = val;
  3552. if (!gecko) updateDisplaySimple(cm, {top: val});
  3553. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  3554. cm.display.scrollbars.setScrollTop(val);
  3555. if (gecko) updateDisplaySimple(cm);
  3556. startWorker(cm, 100);
  3557. }
  3558. // Sync scroller and scrollbar, ensure the gutter elements are
  3559. // aligned.
  3560. function setScrollLeft(cm, val, isScroller) {
  3561. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  3562. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3563. cm.doc.scrollLeft = val;
  3564. alignHorizontally(cm);
  3565. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  3566. cm.display.scrollbars.setScrollLeft(val);
  3567. }
  3568. // Since the delta values reported on mouse wheel events are
  3569. // unstandardized between browsers and even browser versions, and
  3570. // generally horribly unpredictable, this code starts by measuring
  3571. // the scroll effect that the first few mouse wheel events have,
  3572. // and, from that, detects the way it can convert deltas to pixel
  3573. // offsets afterwards.
  3574. //
  3575. // The reason we want to know the amount a wheel event will scroll
  3576. // is that it gives us a chance to update the display before the
  3577. // actual scrolling happens, reducing flickering.
  3578. var wheelSamples = 0, wheelPixelsPerUnit = null;
  3579. // Fill in a browser-detected starting value on browsers where we
  3580. // know one. These don't have to be accurate -- the result of them
  3581. // being wrong would just be a slight flicker on the first wheel
  3582. // scroll (if it is large enough).
  3583. if (ie) wheelPixelsPerUnit = -.53;
  3584. else if (gecko) wheelPixelsPerUnit = 15;
  3585. else if (chrome) wheelPixelsPerUnit = -.7;
  3586. else if (safari) wheelPixelsPerUnit = -1/3;
  3587. var wheelEventDelta = function(e) {
  3588. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3589. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  3590. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  3591. else if (dy == null) dy = e.wheelDelta;
  3592. return {x: dx, y: dy};
  3593. };
  3594. CodeMirror.wheelEventPixels = function(e) {
  3595. var delta = wheelEventDelta(e);
  3596. delta.x *= wheelPixelsPerUnit;
  3597. delta.y *= wheelPixelsPerUnit;
  3598. return delta;
  3599. };
  3600. function onScrollWheel(cm, e) {
  3601. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3602. var display = cm.display, scroll = display.scroller;
  3603. // Quit if there's nothing to scroll here
  3604. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3605. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3606. if (!(dx && canScrollX || dy && canScrollY)) return;
  3607. // Webkit browsers on OS X abort momentum scrolls when the target
  3608. // of the scroll event is removed from the scrollable element.
  3609. // This hack (see related code in patchDisplay) makes sure the
  3610. // element is kept around.
  3611. if (dy && mac && webkit) {
  3612. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3613. for (var i = 0; i < view.length; i++) {
  3614. if (view[i].node == cur) {
  3615. cm.display.currentWheelTarget = cur;
  3616. break outer;
  3617. }
  3618. }
  3619. }
  3620. }
  3621. // On some browsers, horizontal scrolling will cause redraws to
  3622. // happen before the gutter has been realigned, causing it to
  3623. // wriggle around in a most unseemly way. When we have an
  3624. // estimated pixels/delta value, we just handle horizontal
  3625. // scrolling entirely here. It'll be slightly off from native, but
  3626. // better than glitching out.
  3627. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  3628. if (dy && canScrollY)
  3629. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  3630. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  3631. // Only prevent default scrolling if vertical scrolling is
  3632. // actually possible. Otherwise, it causes vertical scroll
  3633. // jitter on OSX trackpads when deltaX is small and deltaY
  3634. // is large (issue #3579)
  3635. if (!dy || (dy && canScrollY))
  3636. e_preventDefault(e);
  3637. display.wheelStartX = null; // Abort measurement, if in progress
  3638. return;
  3639. }
  3640. // 'Project' the visible viewport to cover the area that is being
  3641. // scrolled into view (if we know enough to estimate it).
  3642. if (dy && wheelPixelsPerUnit != null) {
  3643. var pixels = dy * wheelPixelsPerUnit;
  3644. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  3645. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  3646. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  3647. updateDisplaySimple(cm, {top: top, bottom: bot});
  3648. }
  3649. if (wheelSamples < 20) {
  3650. if (display.wheelStartX == null) {
  3651. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  3652. display.wheelDX = dx; display.wheelDY = dy;
  3653. setTimeout(function() {
  3654. if (display.wheelStartX == null) return;
  3655. var movedX = scroll.scrollLeft - display.wheelStartX;
  3656. var movedY = scroll.scrollTop - display.wheelStartY;
  3657. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  3658. (movedX && display.wheelDX && movedX / display.wheelDX);
  3659. display.wheelStartX = display.wheelStartY = null;
  3660. if (!sample) return;
  3661. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  3662. ++wheelSamples;
  3663. }, 200);
  3664. } else {
  3665. display.wheelDX += dx; display.wheelDY += dy;
  3666. }
  3667. }
  3668. }
  3669. // KEY EVENTS
  3670. // Run a handler that was bound to a key.
  3671. function doHandleBinding(cm, bound, dropShift) {
  3672. if (typeof bound == "string") {
  3673. bound = commands[bound];
  3674. if (!bound) return false;
  3675. }
  3676. // Ensure previous input has been read, so that the handler sees a
  3677. // consistent view of the document
  3678. cm.display.input.ensurePolled();
  3679. var prevShift = cm.display.shift, done = false;
  3680. try {
  3681. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  3682. if (dropShift) cm.display.shift = false;
  3683. done = bound(cm) != Pass;
  3684. } finally {
  3685. cm.display.shift = prevShift;
  3686. cm.state.suppressEdits = false;
  3687. }
  3688. return done;
  3689. }
  3690. function lookupKeyForEditor(cm, name, handle) {
  3691. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  3692. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  3693. if (result) return result;
  3694. }
  3695. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  3696. || lookupKey(name, cm.options.keyMap, handle, cm);
  3697. }
  3698. var stopSeq = new Delayed;
  3699. function dispatchKey(cm, name, e, handle) {
  3700. var seq = cm.state.keySeq;
  3701. if (seq) {
  3702. if (isModifierKey(name)) return "handled";
  3703. stopSeq.set(50, function() {
  3704. if (cm.state.keySeq == seq) {
  3705. cm.state.keySeq = null;
  3706. cm.display.input.reset();
  3707. }
  3708. });
  3709. name = seq + " " + name;
  3710. }
  3711. var result = lookupKeyForEditor(cm, name, handle);
  3712. if (result == "multi")
  3713. cm.state.keySeq = name;
  3714. if (result == "handled")
  3715. signalLater(cm, "keyHandled", cm, name, e);
  3716. if (result == "handled" || result == "multi") {
  3717. e_preventDefault(e);
  3718. restartBlink(cm);
  3719. }
  3720. if (seq && !result && /\'$/.test(name)) {
  3721. e_preventDefault(e);
  3722. return true;
  3723. }
  3724. return !!result;
  3725. }
  3726. // Handle a key from the keydown event.
  3727. function handleKeyBinding(cm, e) {
  3728. var name = keyName(e, true);
  3729. if (!name) return false;
  3730. if (e.shiftKey && !cm.state.keySeq) {
  3731. // First try to resolve full name (including 'Shift-'). Failing
  3732. // that, see if there is a cursor-motion command (starting with
  3733. // 'go') bound to the keyname without 'Shift-'.
  3734. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  3735. || dispatchKey(cm, name, e, function(b) {
  3736. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  3737. return doHandleBinding(cm, b);
  3738. });
  3739. } else {
  3740. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  3741. }
  3742. }
  3743. // Handle a key from the keypress event
  3744. function handleCharBinding(cm, e, ch) {
  3745. return dispatchKey(cm, "'" + ch + "'", e,
  3746. function(b) { return doHandleBinding(cm, b, true); });
  3747. }
  3748. var lastStoppedKey = null;
  3749. function onKeyDown(e) {
  3750. var cm = this;
  3751. cm.curOp.focus = activeElt();
  3752. if (signalDOMEvent(cm, e)) return;
  3753. // IE does strange things with escape.
  3754. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  3755. var code = e.keyCode;
  3756. cm.display.shift = code == 16 || e.shiftKey;
  3757. var handled = handleKeyBinding(cm, e);
  3758. if (presto) {
  3759. lastStoppedKey = handled ? code : null;
  3760. // Opera has no cut event... we try to at least catch the key combo
  3761. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  3762. cm.replaceSelection("", null, "cut");
  3763. }
  3764. // Turn mouse into crosshair when Alt is held on Mac.
  3765. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  3766. showCrossHair(cm);
  3767. }
  3768. function showCrossHair(cm) {
  3769. var lineDiv = cm.display.lineDiv;
  3770. addClass(lineDiv, "CodeMirror-crosshair");
  3771. function up(e) {
  3772. if (e.keyCode == 18 || !e.altKey) {
  3773. rmClass(lineDiv, "CodeMirror-crosshair");
  3774. off(document, "keyup", up);
  3775. off(document, "mouseover", up);
  3776. }
  3777. }
  3778. on(document, "keyup", up);
  3779. on(document, "mouseover", up);
  3780. }
  3781. function onKeyUp(e) {
  3782. if (e.keyCode == 16) this.doc.sel.shift = false;
  3783. signalDOMEvent(this, e);
  3784. }
  3785. function onKeyPress(e) {
  3786. var cm = this;
  3787. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  3788. var keyCode = e.keyCode, charCode = e.charCode;
  3789. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  3790. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  3791. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  3792. if (handleCharBinding(cm, e, ch)) return;
  3793. cm.display.input.onKeyPress(e);
  3794. }
  3795. // FOCUS/BLUR EVENTS
  3796. function delayBlurEvent(cm) {
  3797. cm.state.delayingBlurEvent = true;
  3798. setTimeout(function() {
  3799. if (cm.state.delayingBlurEvent) {
  3800. cm.state.delayingBlurEvent = false;
  3801. onBlur(cm);
  3802. }
  3803. }, 100);
  3804. }
  3805. function onFocus(cm) {
  3806. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  3807. if (cm.options.readOnly == "nocursor") return;
  3808. if (!cm.state.focused) {
  3809. signal(cm, "focus", cm);
  3810. cm.state.focused = true;
  3811. addClass(cm.display.wrapper, "CodeMirror-focused");
  3812. // This test prevents this from firing when a context
  3813. // menu is closed (since the input reset would kill the
  3814. // select-all detection hack)
  3815. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3816. cm.display.input.reset();
  3817. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  3818. }
  3819. cm.display.input.receivedFocus();
  3820. }
  3821. restartBlink(cm);
  3822. }
  3823. function onBlur(cm) {
  3824. if (cm.state.delayingBlurEvent) return;
  3825. if (cm.state.focused) {
  3826. signal(cm, "blur", cm);
  3827. cm.state.focused = false;
  3828. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3829. }
  3830. clearInterval(cm.display.blinker);
  3831. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  3832. }
  3833. // CONTEXT MENU HANDLING
  3834. // To make the context menu work, we need to briefly unhide the
  3835. // textarea (making it as unobtrusive as possible) to let the
  3836. // right-click take effect on it.
  3837. function onContextMenu(cm, e) {
  3838. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  3839. if (signalDOMEvent(cm, e, "contextmenu")) return;
  3840. cm.display.input.onContextMenu(e);
  3841. }
  3842. function contextMenuInGutter(cm, e) {
  3843. if (!hasHandler(cm, "gutterContextMenu")) return false;
  3844. return gutterEvent(cm, e, "gutterContextMenu", false);
  3845. }
  3846. // UPDATING
  3847. // Compute the position of the end of a change (its 'to' property
  3848. // refers to the pre-change end).
  3849. var changeEnd = CodeMirror.changeEnd = function(change) {
  3850. if (!change.text) return change.to;
  3851. return Pos(change.from.line + change.text.length - 1,
  3852. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  3853. };
  3854. // Adjust a position to refer to the post-change position of the
  3855. // same text, or the end of the change if the change covers it.
  3856. function adjustForChange(pos, change) {
  3857. if (cmp(pos, change.from) < 0) return pos;
  3858. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  3859. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  3860. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  3861. return Pos(line, ch);
  3862. }
  3863. function computeSelAfterChange(doc, change) {
  3864. var out = [];
  3865. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3866. var range = doc.sel.ranges[i];
  3867. out.push(new Range(adjustForChange(range.anchor, change),
  3868. adjustForChange(range.head, change)));
  3869. }
  3870. return normalizeSelection(out, doc.sel.primIndex);
  3871. }
  3872. function offsetPos(pos, old, nw) {
  3873. if (pos.line == old.line)
  3874. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  3875. else
  3876. return Pos(nw.line + (pos.line - old.line), pos.ch);
  3877. }
  3878. // Used by replaceSelections to allow moving the selection to the
  3879. // start or around the replaced test. Hint may be "start" or "around".
  3880. function computeReplacedSel(doc, changes, hint) {
  3881. var out = [];
  3882. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  3883. for (var i = 0; i < changes.length; i++) {
  3884. var change = changes[i];
  3885. var from = offsetPos(change.from, oldPrev, newPrev);
  3886. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  3887. oldPrev = change.to;
  3888. newPrev = to;
  3889. if (hint == "around") {
  3890. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  3891. out[i] = new Range(inv ? to : from, inv ? from : to);
  3892. } else {
  3893. out[i] = new Range(from, from);
  3894. }
  3895. }
  3896. return new Selection(out, doc.sel.primIndex);
  3897. }
  3898. // Allow "beforeChange" event handlers to influence a change
  3899. function filterChange(doc, change, update) {
  3900. var obj = {
  3901. canceled: false,
  3902. from: change.from,
  3903. to: change.to,
  3904. text: change.text,
  3905. origin: change.origin,
  3906. cancel: function() { this.canceled = true; }
  3907. };
  3908. if (update) obj.update = function(from, to, text, origin) {
  3909. if (from) this.from = clipPos(doc, from);
  3910. if (to) this.to = clipPos(doc, to);
  3911. if (text) this.text = text;
  3912. if (origin !== undefined) this.origin = origin;
  3913. };
  3914. signal(doc, "beforeChange", doc, obj);
  3915. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  3916. if (obj.canceled) return null;
  3917. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  3918. }
  3919. // Apply a change to a document, and add it to the document's
  3920. // history, and propagating it to all linked documents.
  3921. function makeChange(doc, change, ignoreReadOnly) {
  3922. if (doc.cm) {
  3923. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  3924. if (doc.cm.state.suppressEdits) return;
  3925. }
  3926. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  3927. change = filterChange(doc, change, true);
  3928. if (!change) return;
  3929. }
  3930. // Possibly split or suppress the update based on the presence
  3931. // of read-only spans in its range.
  3932. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  3933. if (split) {
  3934. for (var i = split.length - 1; i >= 0; --i)
  3935. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  3936. } else {
  3937. makeChangeInner(doc, change);
  3938. }
  3939. }
  3940. function makeChangeInner(doc, change) {
  3941. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3942. var selAfter = computeSelAfterChange(doc, change);
  3943. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3944. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3945. var rebased = [];
  3946. linkedDocs(doc, function(doc, sharedHist) {
  3947. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3948. rebaseHist(doc.history, change);
  3949. rebased.push(doc.history);
  3950. }
  3951. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3952. });
  3953. }
  3954. // Revert a change stored in a document's history.
  3955. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3956. if (doc.cm && doc.cm.state.suppressEdits) return;
  3957. var hist = doc.history, event, selAfter = doc.sel;
  3958. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3959. // Verify that there is a useable event (so that ctrl-z won't
  3960. // needlessly clear selection events)
  3961. for (var i = 0; i < source.length; i++) {
  3962. event = source[i];
  3963. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3964. break;
  3965. }
  3966. if (i == source.length) return;
  3967. hist.lastOrigin = hist.lastSelOrigin = null;
  3968. for (;;) {
  3969. event = source.pop();
  3970. if (event.ranges) {
  3971. pushSelectionToHistory(event, dest);
  3972. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3973. setSelection(doc, event, {clearRedo: false});
  3974. return;
  3975. }
  3976. selAfter = event;
  3977. }
  3978. else break;
  3979. }
  3980. // Build up a reverse change object to add to the opposite history
  3981. // stack (redo when undoing, and vice versa).
  3982. var antiChanges = [];
  3983. pushSelectionToHistory(selAfter, dest);
  3984. dest.push({changes: antiChanges, generation: hist.generation});
  3985. hist.generation = event.generation || ++hist.maxGeneration;
  3986. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3987. for (var i = event.changes.length - 1; i >= 0; --i) {
  3988. var change = event.changes[i];
  3989. change.origin = type;
  3990. if (filter && !filterChange(doc, change, false)) {
  3991. source.length = 0;
  3992. return;
  3993. }
  3994. antiChanges.push(historyChangeFromChange(doc, change));
  3995. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  3996. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3997. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  3998. var rebased = [];
  3999. // Propagate to the linked documents
  4000. linkedDocs(doc, function(doc, sharedHist) {
  4001. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4002. rebaseHist(doc.history, change);
  4003. rebased.push(doc.history);
  4004. }
  4005. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4006. });
  4007. }
  4008. }
  4009. // Sub-views need their line numbers shifted when text is added
  4010. // above or below them in the parent document.
  4011. function shiftDoc(doc, distance) {
  4012. if (distance == 0) return;
  4013. doc.first += distance;
  4014. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  4015. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  4016. Pos(range.head.line + distance, range.head.ch));
  4017. }), doc.sel.primIndex);
  4018. if (doc.cm) {
  4019. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4020. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4021. regLineChange(doc.cm, l, "gutter");
  4022. }
  4023. }
  4024. // More lower-level change function, handling only a single document
  4025. // (not linked ones).
  4026. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4027. if (doc.cm && !doc.cm.curOp)
  4028. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  4029. if (change.to.line < doc.first) {
  4030. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4031. return;
  4032. }
  4033. if (change.from.line > doc.lastLine()) return;
  4034. // Clip the change to the size of this doc
  4035. if (change.from.line < doc.first) {
  4036. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4037. shiftDoc(doc, shift);
  4038. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4039. text: [lst(change.text)], origin: change.origin};
  4040. }
  4041. var last = doc.lastLine();
  4042. if (change.to.line > last) {
  4043. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4044. text: [change.text[0]], origin: change.origin};
  4045. }
  4046. change.removed = getBetween(doc, change.from, change.to);
  4047. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  4048. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  4049. else updateDoc(doc, change, spans);
  4050. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4051. }
  4052. // Handle the interaction of a change to a document with the editor
  4053. // that this document is part of.
  4054. function makeChangeSingleDocInEditor(cm, change, spans) {
  4055. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4056. var recomputeMaxLength = false, checkWidthStart = from.line;
  4057. if (!cm.options.lineWrapping) {
  4058. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4059. doc.iter(checkWidthStart, to.line + 1, function(line) {
  4060. if (line == display.maxLine) {
  4061. recomputeMaxLength = true;
  4062. return true;
  4063. }
  4064. });
  4065. }
  4066. if (doc.sel.contains(change.from, change.to) > -1)
  4067. signalCursorActivity(cm);
  4068. updateDoc(doc, change, spans, estimateHeight(cm));
  4069. if (!cm.options.lineWrapping) {
  4070. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  4071. var len = lineLength(line);
  4072. if (len > display.maxLineLength) {
  4073. display.maxLine = line;
  4074. display.maxLineLength = len;
  4075. display.maxLineChanged = true;
  4076. recomputeMaxLength = false;
  4077. }
  4078. });
  4079. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  4080. }
  4081. // Adjust frontier, schedule worker
  4082. doc.frontier = Math.min(doc.frontier, from.line);
  4083. startWorker(cm, 400);
  4084. var lendiff = change.text.length - (to.line - from.line) - 1;
  4085. // Remember that these lines changed, for updating the display
  4086. if (change.full)
  4087. regChange(cm);
  4088. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4089. regLineChange(cm, from.line, "text");
  4090. else
  4091. regChange(cm, from.line, to.line + 1, lendiff);
  4092. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4093. if (changeHandler || changesHandler) {
  4094. var obj = {
  4095. from: from, to: to,
  4096. text: change.text,
  4097. removed: change.removed,
  4098. origin: change.origin
  4099. };
  4100. if (changeHandler) signalLater(cm, "change", cm, obj);
  4101. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  4102. }
  4103. cm.display.selForContextMenu = null;
  4104. }
  4105. function replaceRange(doc, code, from, to, origin) {
  4106. if (!to) to = from;
  4107. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  4108. if (typeof code == "string") code = doc.splitLines(code);
  4109. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4110. }
  4111. // SCROLLING THINGS INTO VIEW
  4112. // If an editor sits on the top or bottom of the window, partially
  4113. // scrolled out of view, this ensures that the cursor is visible.
  4114. function maybeScrollWindow(cm, coords) {
  4115. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  4116. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4117. if (coords.top + box.top < 0) doScroll = true;
  4118. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  4119. if (doScroll != null && !phantom) {
  4120. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  4121. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  4122. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  4123. coords.left + "px; width: 2px;");
  4124. cm.display.lineSpace.appendChild(scrollNode);
  4125. scrollNode.scrollIntoView(doScroll);
  4126. cm.display.lineSpace.removeChild(scrollNode);
  4127. }
  4128. }
  4129. // Scroll a given position into view (immediately), verifying that
  4130. // it actually became visible (as line heights are accurately
  4131. // measured, the position of something may 'drift' during drawing).
  4132. function scrollPosIntoView(cm, pos, end, margin) {
  4133. if (margin == null) margin = 0;
  4134. for (var limit = 0; limit < 5; limit++) {
  4135. var changed = false, coords = cursorCoords(cm, pos);
  4136. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  4137. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  4138. Math.min(coords.top, endCoords.top) - margin,
  4139. Math.max(coords.left, endCoords.left),
  4140. Math.max(coords.bottom, endCoords.bottom) + margin);
  4141. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  4142. if (scrollPos.scrollTop != null) {
  4143. setScrollTop(cm, scrollPos.scrollTop);
  4144. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  4145. }
  4146. if (scrollPos.scrollLeft != null) {
  4147. setScrollLeft(cm, scrollPos.scrollLeft);
  4148. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  4149. }
  4150. if (!changed) break;
  4151. }
  4152. return coords;
  4153. }
  4154. // Scroll a given set of coordinates into view (immediately).
  4155. function scrollIntoView(cm, x1, y1, x2, y2) {
  4156. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  4157. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  4158. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  4159. }
  4160. // Calculate a new scroll position needed to scroll the given
  4161. // rectangle into view. Returns an object with scrollTop and
  4162. // scrollLeft properties. When these are undefined, the
  4163. // vertical/horizontal position does not need to be adjusted.
  4164. function calculateScrollPos(cm, x1, y1, x2, y2) {
  4165. var display = cm.display, snapMargin = textHeight(cm.display);
  4166. if (y1 < 0) y1 = 0;
  4167. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  4168. var screen = displayHeight(cm), result = {};
  4169. if (y2 - y1 > screen) y2 = y1 + screen;
  4170. var docBottom = cm.doc.height + paddingVert(display);
  4171. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  4172. if (y1 < screentop) {
  4173. result.scrollTop = atTop ? 0 : y1;
  4174. } else if (y2 > screentop + screen) {
  4175. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  4176. if (newTop != screentop) result.scrollTop = newTop;
  4177. }
  4178. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  4179. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  4180. var tooWide = x2 - x1 > screenw;
  4181. if (tooWide) x2 = x1 + screenw;
  4182. if (x1 < 10)
  4183. result.scrollLeft = 0;
  4184. else if (x1 < screenleft)
  4185. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  4186. else if (x2 > screenw + screenleft - 3)
  4187. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  4188. return result;
  4189. }
  4190. // Store a relative adjustment to the scroll position in the current
  4191. // operation (to be applied when the operation finishes).
  4192. function addToScrollPos(cm, left, top) {
  4193. if (left != null || top != null) resolveScrollToPos(cm);
  4194. if (left != null)
  4195. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  4196. if (top != null)
  4197. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  4198. }
  4199. // Make sure that at the end of the operation the current cursor is
  4200. // shown.
  4201. function ensureCursorVisible(cm) {
  4202. resolveScrollToPos(cm);
  4203. var cur = cm.getCursor(), from = cur, to = cur;
  4204. if (!cm.options.lineWrapping) {
  4205. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  4206. to = Pos(cur.line, cur.ch + 1);
  4207. }
  4208. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  4209. }
  4210. // When an operation has its scrollToPos property set, and another
  4211. // scroll action is applied before the end of the operation, this
  4212. // 'simulates' scrolling that position into view in a cheap way, so
  4213. // that the effect of intermediate scroll commands is not ignored.
  4214. function resolveScrollToPos(cm) {
  4215. var range = cm.curOp.scrollToPos;
  4216. if (range) {
  4217. cm.curOp.scrollToPos = null;
  4218. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  4219. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  4220. Math.min(from.top, to.top) - range.margin,
  4221. Math.max(from.right, to.right),
  4222. Math.max(from.bottom, to.bottom) + range.margin);
  4223. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4224. }
  4225. }
  4226. // API UTILITIES
  4227. // Indent the given line. The how parameter can be "smart",
  4228. // "add"/null, "subtract", or "prev". When aggressive is false
  4229. // (typically set to true for forced single-line indents), empty
  4230. // lines are not indented, and places where the mode returns Pass
  4231. // are left alone.
  4232. function indentLine(cm, n, how, aggressive) {
  4233. var doc = cm.doc, state;
  4234. if (how == null) how = "add";
  4235. if (how == "smart") {
  4236. // Fall back to "prev" when the mode doesn't have an indentation
  4237. // method.
  4238. if (!doc.mode.indent) how = "prev";
  4239. else state = getStateBefore(cm, n);
  4240. }
  4241. var tabSize = cm.options.tabSize;
  4242. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  4243. if (line.stateAfter) line.stateAfter = null;
  4244. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  4245. if (!aggressive && !/\S/.test(line.text)) {
  4246. indentation = 0;
  4247. how = "not";
  4248. } else if (how == "smart") {
  4249. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  4250. if (indentation == Pass || indentation > 150) {
  4251. if (!aggressive) return;
  4252. how = "prev";
  4253. }
  4254. }
  4255. if (how == "prev") {
  4256. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  4257. else indentation = 0;
  4258. } else if (how == "add") {
  4259. indentation = curSpace + cm.options.indentUnit;
  4260. } else if (how == "subtract") {
  4261. indentation = curSpace - cm.options.indentUnit;
  4262. } else if (typeof how == "number") {
  4263. indentation = curSpace + how;
  4264. }
  4265. indentation = Math.max(0, indentation);
  4266. var indentString = "", pos = 0;
  4267. if (cm.options.indentWithTabs)
  4268. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  4269. if (pos < indentation) indentString += spaceStr(indentation - pos);
  4270. if (indentString != curSpaceString) {
  4271. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  4272. line.stateAfter = null;
  4273. return true;
  4274. } else {
  4275. // Ensure that, if the cursor was in the whitespace at the start
  4276. // of the line, it is moved to the end of that space.
  4277. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4278. var range = doc.sel.ranges[i];
  4279. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  4280. var pos = Pos(n, curSpaceString.length);
  4281. replaceOneSelection(doc, i, new Range(pos, pos));
  4282. break;
  4283. }
  4284. }
  4285. }
  4286. }
  4287. // Utility for applying a change to a line by handle or number,
  4288. // returning the number and optionally registering the line as
  4289. // changed.
  4290. function changeLine(doc, handle, changeType, op) {
  4291. var no = handle, line = handle;
  4292. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  4293. else no = lineNo(handle);
  4294. if (no == null) return null;
  4295. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  4296. return line;
  4297. }
  4298. // Helper for deleting text near the selection(s), used to implement
  4299. // backspace, delete, and similar functionality.
  4300. function deleteNearSelection(cm, compute) {
  4301. var ranges = cm.doc.sel.ranges, kill = [];
  4302. // Build up a set of ranges to kill first, merging overlapping
  4303. // ranges.
  4304. for (var i = 0; i < ranges.length; i++) {
  4305. var toKill = compute(ranges[i]);
  4306. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  4307. var replaced = kill.pop();
  4308. if (cmp(replaced.from, toKill.from) < 0) {
  4309. toKill.from = replaced.from;
  4310. break;
  4311. }
  4312. }
  4313. kill.push(toKill);
  4314. }
  4315. // Next, remove those actual ranges.
  4316. runInOp(cm, function() {
  4317. for (var i = kill.length - 1; i >= 0; i--)
  4318. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  4319. ensureCursorVisible(cm);
  4320. });
  4321. }
  4322. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  4323. // right), unit can be "char", "column" (like char, but doesn't
  4324. // cross line boundaries), "word" (across next word), or "group" (to
  4325. // the start of next group of word or non-word-non-whitespace
  4326. // chars). The visually param controls whether, in right-to-left
  4327. // text, direction 1 means to move towards the next index in the
  4328. // string, or towards the character to the right of the current
  4329. // position. The resulting position will have a hitSide=true
  4330. // property if it reached the end of the document.
  4331. function findPosH(doc, pos, dir, unit, visually) {
  4332. var line = pos.line, ch = pos.ch, origDir = dir;
  4333. var lineObj = getLine(doc, line);
  4334. function findNextLine() {
  4335. var l = line + dir;
  4336. if (l < doc.first || l >= doc.first + doc.size) return false
  4337. line = l;
  4338. return lineObj = getLine(doc, l);
  4339. }
  4340. function moveOnce(boundToLine) {
  4341. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  4342. if (next == null) {
  4343. if (!boundToLine && findNextLine()) {
  4344. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  4345. else ch = dir < 0 ? lineObj.text.length : 0;
  4346. } else return false
  4347. } else ch = next;
  4348. return true;
  4349. }
  4350. if (unit == "char") {
  4351. moveOnce()
  4352. } else if (unit == "column") {
  4353. moveOnce(true)
  4354. } else if (unit == "word" || unit == "group") {
  4355. var sawType = null, group = unit == "group";
  4356. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  4357. for (var first = true;; first = false) {
  4358. if (dir < 0 && !moveOnce(!first)) break;
  4359. var cur = lineObj.text.charAt(ch) || "\n";
  4360. var type = isWordChar(cur, helper) ? "w"
  4361. : group && cur == "\n" ? "n"
  4362. : !group || /\s/.test(cur) ? null
  4363. : "p";
  4364. if (group && !first && !type) type = "s";
  4365. if (sawType && sawType != type) {
  4366. if (dir < 0) {dir = 1; moveOnce();}
  4367. break;
  4368. }
  4369. if (type) sawType = type;
  4370. if (dir > 0 && !moveOnce(!first)) break;
  4371. }
  4372. }
  4373. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  4374. if (!cmp(pos, result)) result.hitSide = true;
  4375. return result;
  4376. }
  4377. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  4378. // "page" or "line". The resulting position will have a hitSide=true
  4379. // property if it reached the end of the document.
  4380. function findPosV(cm, pos, dir, unit) {
  4381. var doc = cm.doc, x = pos.left, y;
  4382. if (unit == "page") {
  4383. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  4384. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  4385. } else if (unit == "line") {
  4386. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  4387. }
  4388. for (;;) {
  4389. var target = coordsChar(cm, x, y);
  4390. if (!target.outside) break;
  4391. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  4392. y += dir * 5;
  4393. }
  4394. return target;
  4395. }
  4396. // EDITOR METHODS
  4397. // The publicly visible API. Note that methodOp(f) means
  4398. // 'wrap f in an operation, performed on its `this` parameter'.
  4399. // This is not the complete set of editor methods. Most of the
  4400. // methods defined on the Doc type are also injected into
  4401. // CodeMirror.prototype, for backwards compatibility and
  4402. // convenience.
  4403. CodeMirror.prototype = {
  4404. constructor: CodeMirror,
  4405. focus: function(){window.focus(); this.display.input.focus();},
  4406. setOption: function(option, value) {
  4407. var options = this.options, old = options[option];
  4408. if (options[option] == value && option != "mode") return;
  4409. options[option] = value;
  4410. if (optionHandlers.hasOwnProperty(option))
  4411. operation(this, optionHandlers[option])(this, value, old);
  4412. },
  4413. getOption: function(option) {return this.options[option];},
  4414. getDoc: function() {return this.doc;},
  4415. addKeyMap: function(map, bottom) {
  4416. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  4417. },
  4418. removeKeyMap: function(map) {
  4419. var maps = this.state.keyMaps;
  4420. for (var i = 0; i < maps.length; ++i)
  4421. if (maps[i] == map || maps[i].name == map) {
  4422. maps.splice(i, 1);
  4423. return true;
  4424. }
  4425. },
  4426. addOverlay: methodOp(function(spec, options) {
  4427. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  4428. if (mode.startState) throw new Error("Overlays may not be stateful.");
  4429. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  4430. this.state.modeGen++;
  4431. regChange(this);
  4432. }),
  4433. removeOverlay: methodOp(function(spec) {
  4434. var overlays = this.state.overlays;
  4435. for (var i = 0; i < overlays.length; ++i) {
  4436. var cur = overlays[i].modeSpec;
  4437. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  4438. overlays.splice(i, 1);
  4439. this.state.modeGen++;
  4440. regChange(this);
  4441. return;
  4442. }
  4443. }
  4444. }),
  4445. indentLine: methodOp(function(n, dir, aggressive) {
  4446. if (typeof dir != "string" && typeof dir != "number") {
  4447. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  4448. else dir = dir ? "add" : "subtract";
  4449. }
  4450. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  4451. }),
  4452. indentSelection: methodOp(function(how) {
  4453. var ranges = this.doc.sel.ranges, end = -1;
  4454. for (var i = 0; i < ranges.length; i++) {
  4455. var range = ranges[i];
  4456. if (!range.empty()) {
  4457. var from = range.from(), to = range.to();
  4458. var start = Math.max(end, from.line);
  4459. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  4460. for (var j = start; j < end; ++j)
  4461. indentLine(this, j, how);
  4462. var newRanges = this.doc.sel.ranges;
  4463. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  4464. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  4465. } else if (range.head.line > end) {
  4466. indentLine(this, range.head.line, how, true);
  4467. end = range.head.line;
  4468. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  4469. }
  4470. }
  4471. }),
  4472. // Fetch the parser token for a given character. Useful for hacks
  4473. // that want to inspect the mode state (say, for completion).
  4474. getTokenAt: function(pos, precise) {
  4475. return takeToken(this, pos, precise);
  4476. },
  4477. getLineTokens: function(line, precise) {
  4478. return takeToken(this, Pos(line), precise, true);
  4479. },
  4480. getTokenTypeAt: function(pos) {
  4481. pos = clipPos(this.doc, pos);
  4482. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  4483. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  4484. var type;
  4485. if (ch == 0) type = styles[2];
  4486. else for (;;) {
  4487. var mid = (before + after) >> 1;
  4488. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  4489. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  4490. else { type = styles[mid * 2 + 2]; break; }
  4491. }
  4492. var cut = type ? type.indexOf("cm-overlay ") : -1;
  4493. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  4494. },
  4495. getModeAt: function(pos) {
  4496. var mode = this.doc.mode;
  4497. if (!mode.innerMode) return mode;
  4498. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  4499. },
  4500. getHelper: function(pos, type) {
  4501. return this.getHelpers(pos, type)[0];
  4502. },
  4503. getHelpers: function(pos, type) {
  4504. var found = [];
  4505. if (!helpers.hasOwnProperty(type)) return found;
  4506. var help = helpers[type], mode = this.getModeAt(pos);
  4507. if (typeof mode[type] == "string") {
  4508. if (help[mode[type]]) found.push(help[mode[type]]);
  4509. } else if (mode[type]) {
  4510. for (var i = 0; i < mode[type].length; i++) {
  4511. var val = help[mode[type][i]];
  4512. if (val) found.push(val);
  4513. }
  4514. } else if (mode.helperType && help[mode.helperType]) {
  4515. found.push(help[mode.helperType]);
  4516. } else if (help[mode.name]) {
  4517. found.push(help[mode.name]);
  4518. }
  4519. for (var i = 0; i < help._global.length; i++) {
  4520. var cur = help._global[i];
  4521. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  4522. found.push(cur.val);
  4523. }
  4524. return found;
  4525. },
  4526. getStateAfter: function(line, precise) {
  4527. var doc = this.doc;
  4528. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  4529. return getStateBefore(this, line + 1, precise);
  4530. },
  4531. cursorCoords: function(start, mode) {
  4532. var pos, range = this.doc.sel.primary();
  4533. if (start == null) pos = range.head;
  4534. else if (typeof start == "object") pos = clipPos(this.doc, start);
  4535. else pos = start ? range.from() : range.to();
  4536. return cursorCoords(this, pos, mode || "page");
  4537. },
  4538. charCoords: function(pos, mode) {
  4539. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  4540. },
  4541. coordsChar: function(coords, mode) {
  4542. coords = fromCoordSystem(this, coords, mode || "page");
  4543. return coordsChar(this, coords.left, coords.top);
  4544. },
  4545. lineAtHeight: function(height, mode) {
  4546. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  4547. return lineAtHeight(this.doc, height + this.display.viewOffset);
  4548. },
  4549. heightAtLine: function(line, mode) {
  4550. var end = false, lineObj;
  4551. if (typeof line == "number") {
  4552. var last = this.doc.first + this.doc.size - 1;
  4553. if (line < this.doc.first) line = this.doc.first;
  4554. else if (line > last) { line = last; end = true; }
  4555. lineObj = getLine(this.doc, line);
  4556. } else {
  4557. lineObj = line;
  4558. }
  4559. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  4560. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  4561. },
  4562. defaultTextHeight: function() { return textHeight(this.display); },
  4563. defaultCharWidth: function() { return charWidth(this.display); },
  4564. setGutterMarker: methodOp(function(line, gutterID, value) {
  4565. return changeLine(this.doc, line, "gutter", function(line) {
  4566. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  4567. markers[gutterID] = value;
  4568. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  4569. return true;
  4570. });
  4571. }),
  4572. clearGutter: methodOp(function(gutterID) {
  4573. var cm = this, doc = cm.doc, i = doc.first;
  4574. doc.iter(function(line) {
  4575. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  4576. line.gutterMarkers[gutterID] = null;
  4577. regLineChange(cm, i, "gutter");
  4578. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  4579. }
  4580. ++i;
  4581. });
  4582. }),
  4583. lineInfo: function(line) {
  4584. if (typeof line == "number") {
  4585. if (!isLine(this.doc, line)) return null;
  4586. var n = line;
  4587. line = getLine(this.doc, line);
  4588. if (!line) return null;
  4589. } else {
  4590. var n = lineNo(line);
  4591. if (n == null) return null;
  4592. }
  4593. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  4594. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  4595. widgets: line.widgets};
  4596. },
  4597. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  4598. addWidget: function(pos, node, scroll, vert, horiz) {
  4599. var display = this.display;
  4600. pos = cursorCoords(this, clipPos(this.doc, pos));
  4601. var top = pos.bottom, left = pos.left;
  4602. node.style.position = "absolute";
  4603. node.setAttribute("cm-ignore-events", "true");
  4604. this.display.input.setUneditable(node);
  4605. display.sizer.appendChild(node);
  4606. if (vert == "over") {
  4607. top = pos.top;
  4608. } else if (vert == "above" || vert == "near") {
  4609. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  4610. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  4611. // Default to positioning above (if specified and possible); otherwise default to positioning below
  4612. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  4613. top = pos.top - node.offsetHeight;
  4614. else if (pos.bottom + node.offsetHeight <= vspace)
  4615. top = pos.bottom;
  4616. if (left + node.offsetWidth > hspace)
  4617. left = hspace - node.offsetWidth;
  4618. }
  4619. node.style.top = top + "px";
  4620. node.style.left = node.style.right = "";
  4621. if (horiz == "right") {
  4622. left = display.sizer.clientWidth - node.offsetWidth;
  4623. node.style.right = "0px";
  4624. } else {
  4625. if (horiz == "left") left = 0;
  4626. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  4627. node.style.left = left + "px";
  4628. }
  4629. if (scroll)
  4630. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  4631. },
  4632. triggerOnKeyDown: methodOp(onKeyDown),
  4633. triggerOnKeyPress: methodOp(onKeyPress),
  4634. triggerOnKeyUp: onKeyUp,
  4635. execCommand: function(cmd) {
  4636. if (commands.hasOwnProperty(cmd))
  4637. return commands[cmd].call(null, this);
  4638. },
  4639. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  4640. findPosH: function(from, amount, unit, visually) {
  4641. var dir = 1;
  4642. if (amount < 0) { dir = -1; amount = -amount; }
  4643. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4644. cur = findPosH(this.doc, cur, dir, unit, visually);
  4645. if (cur.hitSide) break;
  4646. }
  4647. return cur;
  4648. },
  4649. moveH: methodOp(function(dir, unit) {
  4650. var cm = this;
  4651. cm.extendSelectionsBy(function(range) {
  4652. if (cm.display.shift || cm.doc.extend || range.empty())
  4653. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  4654. else
  4655. return dir < 0 ? range.from() : range.to();
  4656. }, sel_move);
  4657. }),
  4658. deleteH: methodOp(function(dir, unit) {
  4659. var sel = this.doc.sel, doc = this.doc;
  4660. if (sel.somethingSelected())
  4661. doc.replaceSelection("", null, "+delete");
  4662. else
  4663. deleteNearSelection(this, function(range) {
  4664. var other = findPosH(doc, range.head, dir, unit, false);
  4665. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  4666. });
  4667. }),
  4668. findPosV: function(from, amount, unit, goalColumn) {
  4669. var dir = 1, x = goalColumn;
  4670. if (amount < 0) { dir = -1; amount = -amount; }
  4671. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  4672. var coords = cursorCoords(this, cur, "div");
  4673. if (x == null) x = coords.left;
  4674. else coords.left = x;
  4675. cur = findPosV(this, coords, dir, unit);
  4676. if (cur.hitSide) break;
  4677. }
  4678. return cur;
  4679. },
  4680. moveV: methodOp(function(dir, unit) {
  4681. var cm = this, doc = this.doc, goals = [];
  4682. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  4683. doc.extendSelectionsBy(function(range) {
  4684. if (collapse)
  4685. return dir < 0 ? range.from() : range.to();
  4686. var headPos = cursorCoords(cm, range.head, "div");
  4687. if (range.goalColumn != null) headPos.left = range.goalColumn;
  4688. goals.push(headPos.left);
  4689. var pos = findPosV(cm, headPos, dir, unit);
  4690. if (unit == "page" && range == doc.sel.primary())
  4691. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  4692. return pos;
  4693. }, sel_move);
  4694. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  4695. doc.sel.ranges[i].goalColumn = goals[i];
  4696. }),
  4697. // Find the word at the given position (as returned by coordsChar).
  4698. findWordAt: function(pos) {
  4699. var doc = this.doc, line = getLine(doc, pos.line).text;
  4700. var start = pos.ch, end = pos.ch;
  4701. if (line) {
  4702. var helper = this.getHelper(pos, "wordChars");
  4703. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  4704. var startChar = line.charAt(start);
  4705. var check = isWordChar(startChar, helper)
  4706. ? function(ch) { return isWordChar(ch, helper); }
  4707. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  4708. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  4709. while (start > 0 && check(line.charAt(start - 1))) --start;
  4710. while (end < line.length && check(line.charAt(end))) ++end;
  4711. }
  4712. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  4713. },
  4714. toggleOverwrite: function(value) {
  4715. if (value != null && value == this.state.overwrite) return;
  4716. if (this.state.overwrite = !this.state.overwrite)
  4717. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4718. else
  4719. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  4720. signal(this, "overwriteToggle", this, this.state.overwrite);
  4721. },
  4722. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  4723. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  4724. scrollTo: methodOp(function(x, y) {
  4725. if (x != null || y != null) resolveScrollToPos(this);
  4726. if (x != null) this.curOp.scrollLeft = x;
  4727. if (y != null) this.curOp.scrollTop = y;
  4728. }),
  4729. getScrollInfo: function() {
  4730. var scroller = this.display.scroller;
  4731. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  4732. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  4733. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  4734. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  4735. },
  4736. scrollIntoView: methodOp(function(range, margin) {
  4737. if (range == null) {
  4738. range = {from: this.doc.sel.primary().head, to: null};
  4739. if (margin == null) margin = this.options.cursorScrollMargin;
  4740. } else if (typeof range == "number") {
  4741. range = {from: Pos(range, 0), to: null};
  4742. } else if (range.from == null) {
  4743. range = {from: range, to: null};
  4744. }
  4745. if (!range.to) range.to = range.from;
  4746. range.margin = margin || 0;
  4747. if (range.from.line != null) {
  4748. resolveScrollToPos(this);
  4749. this.curOp.scrollToPos = range;
  4750. } else {
  4751. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  4752. Math.min(range.from.top, range.to.top) - range.margin,
  4753. Math.max(range.from.right, range.to.right),
  4754. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  4755. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  4756. }
  4757. }),
  4758. setSize: methodOp(function(width, height) {
  4759. var cm = this;
  4760. function interpret(val) {
  4761. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  4762. }
  4763. if (width != null) cm.display.wrapper.style.width = interpret(width);
  4764. if (height != null) cm.display.wrapper.style.height = interpret(height);
  4765. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  4766. var lineNo = cm.display.viewFrom;
  4767. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  4768. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  4769. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  4770. ++lineNo;
  4771. });
  4772. cm.curOp.forceUpdate = true;
  4773. signal(cm, "refresh", this);
  4774. }),
  4775. operation: function(f){return runInOp(this, f);},
  4776. refresh: methodOp(function() {
  4777. var oldHeight = this.display.cachedTextHeight;
  4778. regChange(this);
  4779. this.curOp.forceUpdate = true;
  4780. clearCaches(this);
  4781. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  4782. updateGutterSpace(this);
  4783. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  4784. estimateLineHeights(this);
  4785. signal(this, "refresh", this);
  4786. }),
  4787. swapDoc: methodOp(function(doc) {
  4788. var old = this.doc;
  4789. old.cm = null;
  4790. attachDoc(this, doc);
  4791. clearCaches(this);
  4792. this.display.input.reset();
  4793. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  4794. this.curOp.forceScroll = true;
  4795. signalLater(this, "swapDoc", this, old);
  4796. return old;
  4797. }),
  4798. getInputField: function(){return this.display.input.getField();},
  4799. getWrapperElement: function(){return this.display.wrapper;},
  4800. getScrollerElement: function(){return this.display.scroller;},
  4801. getGutterElement: function(){return this.display.gutters;}
  4802. };
  4803. eventMixin(CodeMirror);
  4804. // OPTION DEFAULTS
  4805. // The default configuration options.
  4806. var defaults = CodeMirror.defaults = {};
  4807. // Functions to run when options are changed.
  4808. var optionHandlers = CodeMirror.optionHandlers = {};
  4809. function option(name, deflt, handle, notOnInit) {
  4810. CodeMirror.defaults[name] = deflt;
  4811. if (handle) optionHandlers[name] =
  4812. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  4813. }
  4814. // Passed to option handlers when there is no old value.
  4815. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  4816. // These two are, on init, called from the constructor because they
  4817. // have to be initialized before the editor can start at all.
  4818. option("value", "", function(cm, val) {
  4819. cm.setValue(val);
  4820. }, true);
  4821. option("mode", null, function(cm, val) {
  4822. cm.doc.modeOption = val;
  4823. loadMode(cm);
  4824. }, true);
  4825. option("indentUnit", 2, loadMode, true);
  4826. option("indentWithTabs", false);
  4827. option("smartIndent", true);
  4828. option("tabSize", 4, function(cm) {
  4829. resetModeState(cm);
  4830. clearCaches(cm);
  4831. regChange(cm);
  4832. }, true);
  4833. option("lineSeparator", null, function(cm, val) {
  4834. cm.doc.lineSep = val;
  4835. if (!val) return;
  4836. var newBreaks = [], lineNo = cm.doc.first;
  4837. cm.doc.iter(function(line) {
  4838. for (var pos = 0;;) {
  4839. var found = line.text.indexOf(val, pos);
  4840. if (found == -1) break;
  4841. pos = found + val.length;
  4842. newBreaks.push(Pos(lineNo, found));
  4843. }
  4844. lineNo++;
  4845. });
  4846. for (var i = newBreaks.length - 1; i >= 0; i--)
  4847. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  4848. });
  4849. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  4850. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  4851. if (old != CodeMirror.Init) cm.refresh();
  4852. });
  4853. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  4854. option("electricChars", true);
  4855. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  4856. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  4857. }, true);
  4858. option("rtlMoveVisually", !windows);
  4859. option("wholeLineUpdateBefore", true);
  4860. option("theme", "default", function(cm) {
  4861. themeChanged(cm);
  4862. guttersChanged(cm);
  4863. }, true);
  4864. option("keyMap", "default", function(cm, val, old) {
  4865. var next = getKeyMap(val);
  4866. var prev = old != CodeMirror.Init && getKeyMap(old);
  4867. if (prev && prev.detach) prev.detach(cm, next);
  4868. if (next.attach) next.attach(cm, prev || null);
  4869. });
  4870. option("extraKeys", null);
  4871. option("lineWrapping", false, wrappingChanged, true);
  4872. option("gutters", [], function(cm) {
  4873. setGuttersForLineNumbers(cm.options);
  4874. guttersChanged(cm);
  4875. }, true);
  4876. option("fixedGutter", true, function(cm, val) {
  4877. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  4878. cm.refresh();
  4879. }, true);
  4880. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  4881. option("scrollbarStyle", "native", function(cm) {
  4882. initScrollbars(cm);
  4883. updateScrollbars(cm);
  4884. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  4885. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  4886. }, true);
  4887. option("lineNumbers", false, function(cm) {
  4888. setGuttersForLineNumbers(cm.options);
  4889. guttersChanged(cm);
  4890. }, true);
  4891. option("firstLineNumber", 1, guttersChanged, true);
  4892. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  4893. option("showCursorWhenSelecting", false, updateSelection, true);
  4894. option("resetSelectionOnContextMenu", true);
  4895. option("lineWiseCopyCut", true);
  4896. option("readOnly", false, function(cm, val) {
  4897. if (val == "nocursor") {
  4898. onBlur(cm);
  4899. cm.display.input.blur();
  4900. cm.display.disabled = true;
  4901. } else {
  4902. cm.display.disabled = false;
  4903. }
  4904. cm.display.input.readOnlyChanged(val)
  4905. });
  4906. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  4907. option("dragDrop", true, dragDropChanged);
  4908. option("allowDropFileTypes", null);
  4909. option("cursorBlinkRate", 530);
  4910. option("cursorScrollMargin", 0);
  4911. option("cursorHeight", 1, updateSelection, true);
  4912. option("singleCursorHeightPerLine", true, updateSelection, true);
  4913. option("workTime", 100);
  4914. option("workDelay", 100);
  4915. option("flattenSpans", true, resetModeState, true);
  4916. option("addModeClass", false, resetModeState, true);
  4917. option("pollInterval", 100);
  4918. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  4919. option("historyEventDelay", 1250);
  4920. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  4921. option("maxHighlightLength", 10000, resetModeState, true);
  4922. option("moveInputWithCursor", true, function(cm, val) {
  4923. if (!val) cm.display.input.resetPosition();
  4924. });
  4925. option("tabindex", null, function(cm, val) {
  4926. cm.display.input.getField().tabIndex = val || "";
  4927. });
  4928. option("autofocus", null);
  4929. // MODE DEFINITION AND QUERYING
  4930. // Known modes, by name and by MIME
  4931. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  4932. // Extra arguments are stored as the mode's dependencies, which is
  4933. // used by (legacy) mechanisms like loadmode.js to automatically
  4934. // load a mode. (Preferred mechanism is the require/define calls.)
  4935. CodeMirror.defineMode = function(name, mode) {
  4936. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  4937. if (arguments.length > 2)
  4938. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  4939. modes[name] = mode;
  4940. };
  4941. CodeMirror.defineMIME = function(mime, spec) {
  4942. mimeModes[mime] = spec;
  4943. };
  4944. // Given a MIME type, a {name, ...options} config object, or a name
  4945. // string, return a mode config object.
  4946. CodeMirror.resolveMode = function(spec) {
  4947. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  4948. spec = mimeModes[spec];
  4949. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  4950. var found = mimeModes[spec.name];
  4951. if (typeof found == "string") found = {name: found};
  4952. spec = createObj(found, spec);
  4953. spec.name = found.name;
  4954. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  4955. return CodeMirror.resolveMode("application/xml");
  4956. }
  4957. if (typeof spec == "string") return {name: spec};
  4958. else return spec || {name: "null"};
  4959. };
  4960. // Given a mode spec (anything that resolveMode accepts), find and
  4961. // initialize an actual mode object.
  4962. CodeMirror.getMode = function(options, spec) {
  4963. var spec = CodeMirror.resolveMode(spec);
  4964. var mfactory = modes[spec.name];
  4965. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  4966. var modeObj = mfactory(options, spec);
  4967. if (modeExtensions.hasOwnProperty(spec.name)) {
  4968. var exts = modeExtensions[spec.name];
  4969. for (var prop in exts) {
  4970. if (!exts.hasOwnProperty(prop)) continue;
  4971. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4972. modeObj[prop] = exts[prop];
  4973. }
  4974. }
  4975. modeObj.name = spec.name;
  4976. if (spec.helperType) modeObj.helperType = spec.helperType;
  4977. if (spec.modeProps) for (var prop in spec.modeProps)
  4978. modeObj[prop] = spec.modeProps[prop];
  4979. return modeObj;
  4980. };
  4981. // Minimal default mode.
  4982. CodeMirror.defineMode("null", function() {
  4983. return {token: function(stream) {stream.skipToEnd();}};
  4984. });
  4985. CodeMirror.defineMIME("text/plain", "null");
  4986. // This can be used to attach properties to mode objects from
  4987. // outside the actual mode definition.
  4988. var modeExtensions = CodeMirror.modeExtensions = {};
  4989. CodeMirror.extendMode = function(mode, properties) {
  4990. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4991. copyObj(properties, exts);
  4992. };
  4993. // EXTENSIONS
  4994. CodeMirror.defineExtension = function(name, func) {
  4995. CodeMirror.prototype[name] = func;
  4996. };
  4997. CodeMirror.defineDocExtension = function(name, func) {
  4998. Doc.prototype[name] = func;
  4999. };
  5000. CodeMirror.defineOption = option;
  5001. var initHooks = [];
  5002. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  5003. var helpers = CodeMirror.helpers = {};
  5004. CodeMirror.registerHelper = function(type, name, value) {
  5005. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  5006. helpers[type][name] = value;
  5007. };
  5008. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  5009. CodeMirror.registerHelper(type, name, value);
  5010. helpers[type]._global.push({pred: predicate, val: value});
  5011. };
  5012. // MODE STATE HANDLING
  5013. // Utility functions for working with state. Exported because nested
  5014. // modes need to do this for their inner modes.
  5015. var copyState = CodeMirror.copyState = function(mode, state) {
  5016. if (state === true) return state;
  5017. if (mode.copyState) return mode.copyState(state);
  5018. var nstate = {};
  5019. for (var n in state) {
  5020. var val = state[n];
  5021. if (val instanceof Array) val = val.concat([]);
  5022. nstate[n] = val;
  5023. }
  5024. return nstate;
  5025. };
  5026. var startState = CodeMirror.startState = function(mode, a1, a2) {
  5027. return mode.startState ? mode.startState(a1, a2) : true;
  5028. };
  5029. // Given a mode and a state (for that mode), find the inner mode and
  5030. // state at the position that the state refers to.
  5031. CodeMirror.innerMode = function(mode, state) {
  5032. while (mode.innerMode) {
  5033. var info = mode.innerMode(state);
  5034. if (!info || info.mode == mode) break;
  5035. state = info.state;
  5036. mode = info.mode;
  5037. }
  5038. return info || {mode: mode, state: state};
  5039. };
  5040. // STANDARD COMMANDS
  5041. // Commands are parameter-less actions that can be performed on an
  5042. // editor, mostly used for keybindings.
  5043. var commands = CodeMirror.commands = {
  5044. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  5045. singleSelection: function(cm) {
  5046. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  5047. },
  5048. killLine: function(cm) {
  5049. deleteNearSelection(cm, function(range) {
  5050. if (range.empty()) {
  5051. var len = getLine(cm.doc, range.head.line).text.length;
  5052. if (range.head.ch == len && range.head.line < cm.lastLine())
  5053. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  5054. else
  5055. return {from: range.head, to: Pos(range.head.line, len)};
  5056. } else {
  5057. return {from: range.from(), to: range.to()};
  5058. }
  5059. });
  5060. },
  5061. deleteLine: function(cm) {
  5062. deleteNearSelection(cm, function(range) {
  5063. return {from: Pos(range.from().line, 0),
  5064. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  5065. });
  5066. },
  5067. delLineLeft: function(cm) {
  5068. deleteNearSelection(cm, function(range) {
  5069. return {from: Pos(range.from().line, 0), to: range.from()};
  5070. });
  5071. },
  5072. delWrappedLineLeft: function(cm) {
  5073. deleteNearSelection(cm, function(range) {
  5074. var top = cm.charCoords(range.head, "div").top + 5;
  5075. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  5076. return {from: leftPos, to: range.from()};
  5077. });
  5078. },
  5079. delWrappedLineRight: function(cm) {
  5080. deleteNearSelection(cm, function(range) {
  5081. var top = cm.charCoords(range.head, "div").top + 5;
  5082. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5083. return {from: range.from(), to: rightPos };
  5084. });
  5085. },
  5086. undo: function(cm) {cm.undo();},
  5087. redo: function(cm) {cm.redo();},
  5088. undoSelection: function(cm) {cm.undoSelection();},
  5089. redoSelection: function(cm) {cm.redoSelection();},
  5090. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  5091. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  5092. goLineStart: function(cm) {
  5093. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  5094. {origin: "+move", bias: 1});
  5095. },
  5096. goLineStartSmart: function(cm) {
  5097. cm.extendSelectionsBy(function(range) {
  5098. return lineStartSmart(cm, range.head);
  5099. }, {origin: "+move", bias: 1});
  5100. },
  5101. goLineEnd: function(cm) {
  5102. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  5103. {origin: "+move", bias: -1});
  5104. },
  5105. goLineRight: function(cm) {
  5106. cm.extendSelectionsBy(function(range) {
  5107. var top = cm.charCoords(range.head, "div").top + 5;
  5108. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  5109. }, sel_move);
  5110. },
  5111. goLineLeft: function(cm) {
  5112. cm.extendSelectionsBy(function(range) {
  5113. var top = cm.charCoords(range.head, "div").top + 5;
  5114. return cm.coordsChar({left: 0, top: top}, "div");
  5115. }, sel_move);
  5116. },
  5117. goLineLeftSmart: function(cm) {
  5118. cm.extendSelectionsBy(function(range) {
  5119. var top = cm.charCoords(range.head, "div").top + 5;
  5120. var pos = cm.coordsChar({left: 0, top: top}, "div");
  5121. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  5122. return pos;
  5123. }, sel_move);
  5124. },
  5125. goLineUp: function(cm) {cm.moveV(-1, "line");},
  5126. goLineDown: function(cm) {cm.moveV(1, "line");},
  5127. goPageUp: function(cm) {cm.moveV(-1, "page");},
  5128. goPageDown: function(cm) {cm.moveV(1, "page");},
  5129. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  5130. goCharRight: function(cm) {cm.moveH(1, "char");},
  5131. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  5132. goColumnRight: function(cm) {cm.moveH(1, "column");},
  5133. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  5134. goGroupRight: function(cm) {cm.moveH(1, "group");},
  5135. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  5136. goWordRight: function(cm) {cm.moveH(1, "word");},
  5137. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  5138. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  5139. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  5140. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  5141. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  5142. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  5143. indentAuto: function(cm) {cm.indentSelection("smart");},
  5144. indentMore: function(cm) {cm.indentSelection("add");},
  5145. indentLess: function(cm) {cm.indentSelection("subtract");},
  5146. insertTab: function(cm) {cm.replaceSelection("\t");},
  5147. insertSoftTab: function(cm) {
  5148. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  5149. for (var i = 0; i < ranges.length; i++) {
  5150. var pos = ranges[i].from();
  5151. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  5152. spaces.push(spaceStr(tabSize - col % tabSize));
  5153. }
  5154. cm.replaceSelections(spaces);
  5155. },
  5156. defaultTab: function(cm) {
  5157. if (cm.somethingSelected()) cm.indentSelection("add");
  5158. else cm.execCommand("insertTab");
  5159. },
  5160. transposeChars: function(cm) {
  5161. runInOp(cm, function() {
  5162. var ranges = cm.listSelections(), newSel = [];
  5163. for (var i = 0; i < ranges.length; i++) {
  5164. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  5165. if (line) {
  5166. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  5167. if (cur.ch > 0) {
  5168. cur = new Pos(cur.line, cur.ch + 1);
  5169. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  5170. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  5171. } else if (cur.line > cm.doc.first) {
  5172. var prev = getLine(cm.doc, cur.line - 1).text;
  5173. if (prev)
  5174. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  5175. prev.charAt(prev.length - 1),
  5176. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  5177. }
  5178. }
  5179. newSel.push(new Range(cur, cur));
  5180. }
  5181. cm.setSelections(newSel);
  5182. });
  5183. },
  5184. newlineAndIndent: function(cm) {
  5185. runInOp(cm, function() {
  5186. var len = cm.listSelections().length;
  5187. for (var i = 0; i < len; i++) {
  5188. var range = cm.listSelections()[i];
  5189. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  5190. cm.indentLine(range.from().line + 1, null, true);
  5191. }
  5192. ensureCursorVisible(cm);
  5193. });
  5194. },
  5195. openLine: function(cm) {cm.replaceSelection("\n", "start")},
  5196. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  5197. };
  5198. // STANDARD KEYMAPS
  5199. var keyMap = CodeMirror.keyMap = {};
  5200. keyMap.basic = {
  5201. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5202. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5203. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5204. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5205. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5206. "Esc": "singleSelection"
  5207. };
  5208. // Note that the save and find-related commands aren't defined by
  5209. // default. User code or addons can define them. Unknown commands
  5210. // are simply ignored.
  5211. keyMap.pcDefault = {
  5212. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5213. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5214. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5215. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5216. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5217. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5218. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5219. fallthrough: "basic"
  5220. };
  5221. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5222. keyMap.emacsy = {
  5223. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5224. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5225. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5226. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5227. "Ctrl-O": "openLine"
  5228. };
  5229. keyMap.macDefault = {
  5230. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5231. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5232. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5233. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5234. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5235. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5236. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5237. fallthrough: ["basic", "emacsy"]
  5238. };
  5239. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5240. // KEYMAP DISPATCH
  5241. function normalizeKeyName(name) {
  5242. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  5243. var alt, ctrl, shift, cmd;
  5244. for (var i = 0; i < parts.length - 1; i++) {
  5245. var mod = parts[i];
  5246. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  5247. else if (/^a(lt)?$/i.test(mod)) alt = true;
  5248. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  5249. else if (/^s(hift)$/i.test(mod)) shift = true;
  5250. else throw new Error("Unrecognized modifier name: " + mod);
  5251. }
  5252. if (alt) name = "Alt-" + name;
  5253. if (ctrl) name = "Ctrl-" + name;
  5254. if (cmd) name = "Cmd-" + name;
  5255. if (shift) name = "Shift-" + name;
  5256. return name;
  5257. }
  5258. // This is a kludge to keep keymaps mostly working as raw objects
  5259. // (backwards compatibility) while at the same time support features
  5260. // like normalization and multi-stroke key bindings. It compiles a
  5261. // new normalized keymap, and then updates the old object to reflect
  5262. // this.
  5263. CodeMirror.normalizeKeyMap = function(keymap) {
  5264. var copy = {};
  5265. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  5266. var value = keymap[keyname];
  5267. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  5268. if (value == "...") { delete keymap[keyname]; continue; }
  5269. var keys = map(keyname.split(" "), normalizeKeyName);
  5270. for (var i = 0; i < keys.length; i++) {
  5271. var val, name;
  5272. if (i == keys.length - 1) {
  5273. name = keys.join(" ");
  5274. val = value;
  5275. } else {
  5276. name = keys.slice(0, i + 1).join(" ");
  5277. val = "...";
  5278. }
  5279. var prev = copy[name];
  5280. if (!prev) copy[name] = val;
  5281. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  5282. }
  5283. delete keymap[keyname];
  5284. }
  5285. for (var prop in copy) keymap[prop] = copy[prop];
  5286. return keymap;
  5287. };
  5288. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  5289. map = getKeyMap(map);
  5290. var found = map.call ? map.call(key, context) : map[key];
  5291. if (found === false) return "nothing";
  5292. if (found === "...") return "multi";
  5293. if (found != null && handle(found)) return "handled";
  5294. if (map.fallthrough) {
  5295. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  5296. return lookupKey(key, map.fallthrough, handle, context);
  5297. for (var i = 0; i < map.fallthrough.length; i++) {
  5298. var result = lookupKey(key, map.fallthrough[i], handle, context);
  5299. if (result) return result;
  5300. }
  5301. }
  5302. };
  5303. // Modifier key presses don't count as 'real' key presses for the
  5304. // purpose of keymap fallthrough.
  5305. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  5306. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  5307. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  5308. };
  5309. // Look up the name of a key as indicated by an event object.
  5310. var keyName = CodeMirror.keyName = function(event, noShift) {
  5311. if (presto && event.keyCode == 34 && event["char"]) return false;
  5312. var base = keyNames[event.keyCode], name = base;
  5313. if (name == null || event.altGraphKey) return false;
  5314. if (event.altKey && base != "Alt") name = "Alt-" + name;
  5315. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  5316. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  5317. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  5318. return name;
  5319. };
  5320. function getKeyMap(val) {
  5321. return typeof val == "string" ? keyMap[val] : val;
  5322. }
  5323. // FROMTEXTAREA
  5324. CodeMirror.fromTextArea = function(textarea, options) {
  5325. options = options ? copyObj(options) : {};
  5326. options.value = textarea.value;
  5327. if (!options.tabindex && textarea.tabIndex)
  5328. options.tabindex = textarea.tabIndex;
  5329. if (!options.placeholder && textarea.placeholder)
  5330. options.placeholder = textarea.placeholder;
  5331. // Set autofocus to true if this textarea is focused, or if it has
  5332. // autofocus and no other element is focused.
  5333. if (options.autofocus == null) {
  5334. var hasFocus = activeElt();
  5335. options.autofocus = hasFocus == textarea ||
  5336. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  5337. }
  5338. function save() {textarea.value = cm.getValue();}
  5339. if (textarea.form) {
  5340. on(textarea.form, "submit", save);
  5341. // Deplorable hack to make the submit method do the right thing.
  5342. if (!options.leaveSubmitMethodAlone) {
  5343. var form = textarea.form, realSubmit = form.submit;
  5344. try {
  5345. var wrappedSubmit = form.submit = function() {
  5346. save();
  5347. form.submit = realSubmit;
  5348. form.submit();
  5349. form.submit = wrappedSubmit;
  5350. };
  5351. } catch(e) {}
  5352. }
  5353. }
  5354. options.finishInit = function(cm) {
  5355. cm.save = save;
  5356. cm.getTextArea = function() { return textarea; };
  5357. cm.toTextArea = function() {
  5358. cm.toTextArea = isNaN; // Prevent this from being ran twice
  5359. save();
  5360. textarea.parentNode.removeChild(cm.getWrapperElement());
  5361. textarea.style.display = "";
  5362. if (textarea.form) {
  5363. off(textarea.form, "submit", save);
  5364. if (typeof textarea.form.submit == "function")
  5365. textarea.form.submit = realSubmit;
  5366. }
  5367. };
  5368. };
  5369. textarea.style.display = "none";
  5370. var cm = CodeMirror(function(node) {
  5371. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  5372. }, options);
  5373. return cm;
  5374. };
  5375. // STRING STREAM
  5376. // Fed to the mode parsers, provides helper functions to make
  5377. // parsers more succinct.
  5378. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  5379. this.pos = this.start = 0;
  5380. this.string = string;
  5381. this.tabSize = tabSize || 8;
  5382. this.lastColumnPos = this.lastColumnValue = 0;
  5383. this.lineStart = 0;
  5384. };
  5385. StringStream.prototype = {
  5386. eol: function() {return this.pos >= this.string.length;},
  5387. sol: function() {return this.pos == this.lineStart;},
  5388. peek: function() {return this.string.charAt(this.pos) || undefined;},
  5389. next: function() {
  5390. if (this.pos < this.string.length)
  5391. return this.string.charAt(this.pos++);
  5392. },
  5393. eat: function(match) {
  5394. var ch = this.string.charAt(this.pos);
  5395. if (typeof match == "string") var ok = ch == match;
  5396. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  5397. if (ok) {++this.pos; return ch;}
  5398. },
  5399. eatWhile: function(match) {
  5400. var start = this.pos;
  5401. while (this.eat(match)){}
  5402. return this.pos > start;
  5403. },
  5404. eatSpace: function() {
  5405. var start = this.pos;
  5406. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  5407. return this.pos > start;
  5408. },
  5409. skipToEnd: function() {this.pos = this.string.length;},
  5410. skipTo: function(ch) {
  5411. var found = this.string.indexOf(ch, this.pos);
  5412. if (found > -1) {this.pos = found; return true;}
  5413. },
  5414. backUp: function(n) {this.pos -= n;},
  5415. column: function() {
  5416. if (this.lastColumnPos < this.start) {
  5417. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  5418. this.lastColumnPos = this.start;
  5419. }
  5420. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5421. },
  5422. indentation: function() {
  5423. return countColumn(this.string, null, this.tabSize) -
  5424. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  5425. },
  5426. match: function(pattern, consume, caseInsensitive) {
  5427. if (typeof pattern == "string") {
  5428. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  5429. var substr = this.string.substr(this.pos, pattern.length);
  5430. if (cased(substr) == cased(pattern)) {
  5431. if (consume !== false) this.pos += pattern.length;
  5432. return true;
  5433. }
  5434. } else {
  5435. var match = this.string.slice(this.pos).match(pattern);
  5436. if (match && match.index > 0) return null;
  5437. if (match && consume !== false) this.pos += match[0].length;
  5438. return match;
  5439. }
  5440. },
  5441. current: function(){return this.string.slice(this.start, this.pos);},
  5442. hideFirstChars: function(n, inner) {
  5443. this.lineStart += n;
  5444. try { return inner(); }
  5445. finally { this.lineStart -= n; }
  5446. }
  5447. };
  5448. // TEXTMARKERS
  5449. // Created with markText and setBookmark methods. A TextMarker is a
  5450. // handle that can be used to clear or find a marked position in the
  5451. // document. Line objects hold arrays (markedSpans) containing
  5452. // {from, to, marker} object pointing to such marker objects, and
  5453. // indicating that such a marker is present on that line. Multiple
  5454. // lines may point to the same marker when it spans across lines.
  5455. // The spans will have null for their from/to properties when the
  5456. // marker continues beyond the start/end of the line. Markers have
  5457. // links back to the lines they currently touch.
  5458. var nextMarkerId = 0;
  5459. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  5460. this.lines = [];
  5461. this.type = type;
  5462. this.doc = doc;
  5463. this.id = ++nextMarkerId;
  5464. };
  5465. eventMixin(TextMarker);
  5466. // Clear the marker.
  5467. TextMarker.prototype.clear = function() {
  5468. if (this.explicitlyCleared) return;
  5469. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5470. if (withOp) startOperation(cm);
  5471. if (hasHandler(this, "clear")) {
  5472. var found = this.find();
  5473. if (found) signalLater(this, "clear", found.from, found.to);
  5474. }
  5475. var min = null, max = null;
  5476. for (var i = 0; i < this.lines.length; ++i) {
  5477. var line = this.lines[i];
  5478. var span = getMarkedSpanFor(line.markedSpans, this);
  5479. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  5480. else if (cm) {
  5481. if (span.to != null) max = lineNo(line);
  5482. if (span.from != null) min = lineNo(line);
  5483. }
  5484. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5485. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5486. updateLineHeight(line, textHeight(cm.display));
  5487. }
  5488. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  5489. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  5490. if (len > cm.display.maxLineLength) {
  5491. cm.display.maxLine = visual;
  5492. cm.display.maxLineLength = len;
  5493. cm.display.maxLineChanged = true;
  5494. }
  5495. }
  5496. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  5497. this.lines.length = 0;
  5498. this.explicitlyCleared = true;
  5499. if (this.atomic && this.doc.cantEdit) {
  5500. this.doc.cantEdit = false;
  5501. if (cm) reCheckSelection(cm.doc);
  5502. }
  5503. if (cm) signalLater(cm, "markerCleared", cm, this);
  5504. if (withOp) endOperation(cm);
  5505. if (this.parent) this.parent.clear();
  5506. };
  5507. // Find the position of the marker in the document. Returns a {from,
  5508. // to} object by default. Side can be passed to get a specific side
  5509. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5510. // Pos objects returned contain a line object, rather than a line
  5511. // number (used to prevent looking up the same line twice).
  5512. TextMarker.prototype.find = function(side, lineObj) {
  5513. if (side == null && this.type == "bookmark") side = 1;
  5514. var from, to;
  5515. for (var i = 0; i < this.lines.length; ++i) {
  5516. var line = this.lines[i];
  5517. var span = getMarkedSpanFor(line.markedSpans, this);
  5518. if (span.from != null) {
  5519. from = Pos(lineObj ? line : lineNo(line), span.from);
  5520. if (side == -1) return from;
  5521. }
  5522. if (span.to != null) {
  5523. to = Pos(lineObj ? line : lineNo(line), span.to);
  5524. if (side == 1) return to;
  5525. }
  5526. }
  5527. return from && {from: from, to: to};
  5528. };
  5529. // Signals that the marker's widget changed, and surrounding layout
  5530. // should be recomputed.
  5531. TextMarker.prototype.changed = function() {
  5532. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5533. if (!pos || !cm) return;
  5534. runInOp(cm, function() {
  5535. var line = pos.line, lineN = lineNo(pos.line);
  5536. var view = findViewForLine(cm, lineN);
  5537. if (view) {
  5538. clearLineMeasurementCacheFor(view);
  5539. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5540. }
  5541. cm.curOp.updateMaxLine = true;
  5542. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5543. var oldHeight = widget.height;
  5544. widget.height = null;
  5545. var dHeight = widgetHeight(widget) - oldHeight;
  5546. if (dHeight)
  5547. updateLineHeight(line, line.height + dHeight);
  5548. }
  5549. });
  5550. };
  5551. TextMarker.prototype.attachLine = function(line) {
  5552. if (!this.lines.length && this.doc.cm) {
  5553. var op = this.doc.cm.curOp;
  5554. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5555. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  5556. }
  5557. this.lines.push(line);
  5558. };
  5559. TextMarker.prototype.detachLine = function(line) {
  5560. this.lines.splice(indexOf(this.lines, line), 1);
  5561. if (!this.lines.length && this.doc.cm) {
  5562. var op = this.doc.cm.curOp;
  5563. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5564. }
  5565. };
  5566. // Collapsed markers have unique ids, in order to be able to order
  5567. // them, which is needed for uniquely determining an outer marker
  5568. // when they overlap (they may nest, but not partially overlap).
  5569. var nextMarkerId = 0;
  5570. // Create a marker, wire it up to the right lines, and
  5571. function markText(doc, from, to, options, type) {
  5572. // Shared markers (across linked documents) are handled separately
  5573. // (markTextShared will call out to this again, once per
  5574. // document).
  5575. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  5576. // Ensure we are in an operation.
  5577. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  5578. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5579. if (options) copyObj(options, marker, false);
  5580. // Don't connect empty markers unless clearWhenEmpty is false
  5581. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5582. return marker;
  5583. if (marker.replacedWith) {
  5584. // Showing up as a widget implies collapsed (widget replaces text)
  5585. marker.collapsed = true;
  5586. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  5587. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  5588. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  5589. }
  5590. if (marker.collapsed) {
  5591. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5592. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5593. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  5594. sawCollapsedSpans = true;
  5595. }
  5596. if (marker.addToHistory)
  5597. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  5598. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5599. doc.iter(curLine, to.line + 1, function(line) {
  5600. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5601. updateMaxLine = true;
  5602. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  5603. addMarkedSpan(line, new MarkedSpan(marker,
  5604. curLine == from.line ? from.ch : null,
  5605. curLine == to.line ? to.ch : null));
  5606. ++curLine;
  5607. });
  5608. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5609. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  5610. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  5611. });
  5612. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  5613. if (marker.readOnly) {
  5614. sawReadOnlySpans = true;
  5615. if (doc.history.done.length || doc.history.undone.length)
  5616. doc.clearHistory();
  5617. }
  5618. if (marker.collapsed) {
  5619. marker.id = ++nextMarkerId;
  5620. marker.atomic = true;
  5621. }
  5622. if (cm) {
  5623. // Sync editor state
  5624. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  5625. if (marker.collapsed)
  5626. regChange(cm, from.line, to.line + 1);
  5627. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5628. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  5629. if (marker.atomic) reCheckSelection(cm.doc);
  5630. signalLater(cm, "markerAdded", cm, marker);
  5631. }
  5632. return marker;
  5633. }
  5634. // SHARED TEXTMARKERS
  5635. // A shared marker spans multiple linked documents. It is
  5636. // implemented as a meta-marker-object controlling multiple normal
  5637. // markers.
  5638. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  5639. this.markers = markers;
  5640. this.primary = primary;
  5641. for (var i = 0; i < markers.length; ++i)
  5642. markers[i].parent = this;
  5643. };
  5644. eventMixin(SharedTextMarker);
  5645. SharedTextMarker.prototype.clear = function() {
  5646. if (this.explicitlyCleared) return;
  5647. this.explicitlyCleared = true;
  5648. for (var i = 0; i < this.markers.length; ++i)
  5649. this.markers[i].clear();
  5650. signalLater(this, "clear");
  5651. };
  5652. SharedTextMarker.prototype.find = function(side, lineObj) {
  5653. return this.primary.find(side, lineObj);
  5654. };
  5655. function markTextShared(doc, from, to, options, type) {
  5656. options = copyObj(options);
  5657. options.shared = false;
  5658. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5659. var widget = options.widgetNode;
  5660. linkedDocs(doc, function(doc) {
  5661. if (widget) options.widgetNode = widget.cloneNode(true);
  5662. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5663. for (var i = 0; i < doc.linked.length; ++i)
  5664. if (doc.linked[i].isParent) return;
  5665. primary = lst(markers);
  5666. });
  5667. return new SharedTextMarker(markers, primary);
  5668. }
  5669. function findSharedMarkers(doc) {
  5670. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  5671. function(m) { return m.parent; });
  5672. }
  5673. function copySharedMarkers(doc, markers) {
  5674. for (var i = 0; i < markers.length; i++) {
  5675. var marker = markers[i], pos = marker.find();
  5676. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5677. if (cmp(mFrom, mTo)) {
  5678. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5679. marker.markers.push(subMark);
  5680. subMark.parent = marker;
  5681. }
  5682. }
  5683. }
  5684. function detachSharedMarkers(markers) {
  5685. for (var i = 0; i < markers.length; i++) {
  5686. var marker = markers[i], linked = [marker.primary.doc];;
  5687. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  5688. for (var j = 0; j < marker.markers.length; j++) {
  5689. var subMarker = marker.markers[j];
  5690. if (indexOf(linked, subMarker.doc) == -1) {
  5691. subMarker.parent = null;
  5692. marker.markers.splice(j--, 1);
  5693. }
  5694. }
  5695. }
  5696. }
  5697. // TEXTMARKER SPANS
  5698. function MarkedSpan(marker, from, to) {
  5699. this.marker = marker;
  5700. this.from = from; this.to = to;
  5701. }
  5702. // Search an array of spans for a span matching the given marker.
  5703. function getMarkedSpanFor(spans, marker) {
  5704. if (spans) for (var i = 0; i < spans.length; ++i) {
  5705. var span = spans[i];
  5706. if (span.marker == marker) return span;
  5707. }
  5708. }
  5709. // Remove a span from an array, returning undefined if no spans are
  5710. // left (we don't store arrays for lines without spans).
  5711. function removeMarkedSpan(spans, span) {
  5712. for (var r, i = 0; i < spans.length; ++i)
  5713. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  5714. return r;
  5715. }
  5716. // Add a span to a line.
  5717. function addMarkedSpan(line, span) {
  5718. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  5719. span.marker.attachLine(line);
  5720. }
  5721. // Used for the algorithm that adjusts markers for a change in the
  5722. // document. These functions cut an array of spans at a given
  5723. // character position, returning an array of remaining chunks (or
  5724. // undefined if nothing remains).
  5725. function markedSpansBefore(old, startCh, isInsert) {
  5726. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5727. var span = old[i], marker = span.marker;
  5728. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  5729. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  5730. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  5731. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  5732. }
  5733. }
  5734. return nw;
  5735. }
  5736. function markedSpansAfter(old, endCh, isInsert) {
  5737. if (old) for (var i = 0, nw; i < old.length; ++i) {
  5738. var span = old[i], marker = span.marker;
  5739. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  5740. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  5741. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  5742. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  5743. span.to == null ? null : span.to - endCh));
  5744. }
  5745. }
  5746. return nw;
  5747. }
  5748. // Given a change object, compute the new set of marker spans that
  5749. // cover the line in which the change took place. Removes spans
  5750. // entirely within the change, reconnects spans belonging to the
  5751. // same marker that appear on both sides of the change, and cuts off
  5752. // spans partially within the change. Returns an array of span
  5753. // arrays with one element for each line in (after) the change.
  5754. function stretchSpansOverChange(doc, change) {
  5755. if (change.full) return null;
  5756. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  5757. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  5758. if (!oldFirst && !oldLast) return null;
  5759. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  5760. // Get the spans that 'stick out' on both sides
  5761. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  5762. var last = markedSpansAfter(oldLast, endCh, isInsert);
  5763. // Next, merge those two ends
  5764. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  5765. if (first) {
  5766. // Fix up .to properties of first
  5767. for (var i = 0; i < first.length; ++i) {
  5768. var span = first[i];
  5769. if (span.to == null) {
  5770. var found = getMarkedSpanFor(last, span.marker);
  5771. if (!found) span.to = startCh;
  5772. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  5773. }
  5774. }
  5775. }
  5776. if (last) {
  5777. // Fix up .from in last (or move them into first in case of sameLine)
  5778. for (var i = 0; i < last.length; ++i) {
  5779. var span = last[i];
  5780. if (span.to != null) span.to += offset;
  5781. if (span.from == null) {
  5782. var found = getMarkedSpanFor(first, span.marker);
  5783. if (!found) {
  5784. span.from = offset;
  5785. if (sameLine) (first || (first = [])).push(span);
  5786. }
  5787. } else {
  5788. span.from += offset;
  5789. if (sameLine) (first || (first = [])).push(span);
  5790. }
  5791. }
  5792. }
  5793. // Make sure we didn't create any zero-length spans
  5794. if (first) first = clearEmptySpans(first);
  5795. if (last && last != first) last = clearEmptySpans(last);
  5796. var newMarkers = [first];
  5797. if (!sameLine) {
  5798. // Fill gap with whole-line-spans
  5799. var gap = change.text.length - 2, gapMarkers;
  5800. if (gap > 0 && first)
  5801. for (var i = 0; i < first.length; ++i)
  5802. if (first[i].to == null)
  5803. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  5804. for (var i = 0; i < gap; ++i)
  5805. newMarkers.push(gapMarkers);
  5806. newMarkers.push(last);
  5807. }
  5808. return newMarkers;
  5809. }
  5810. // Remove spans that are empty and don't have a clearWhenEmpty
  5811. // option of false.
  5812. function clearEmptySpans(spans) {
  5813. for (var i = 0; i < spans.length; ++i) {
  5814. var span = spans[i];
  5815. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  5816. spans.splice(i--, 1);
  5817. }
  5818. if (!spans.length) return null;
  5819. return spans;
  5820. }
  5821. // Used for un/re-doing changes from the history. Combines the
  5822. // result of computing the existing spans with the set of spans that
  5823. // existed in the history (so that deleting around a span and then
  5824. // undoing brings back the span).
  5825. function mergeOldSpans(doc, change) {
  5826. var old = getOldSpans(doc, change);
  5827. var stretched = stretchSpansOverChange(doc, change);
  5828. if (!old) return stretched;
  5829. if (!stretched) return old;
  5830. for (var i = 0; i < old.length; ++i) {
  5831. var oldCur = old[i], stretchCur = stretched[i];
  5832. if (oldCur && stretchCur) {
  5833. spans: for (var j = 0; j < stretchCur.length; ++j) {
  5834. var span = stretchCur[j];
  5835. for (var k = 0; k < oldCur.length; ++k)
  5836. if (oldCur[k].marker == span.marker) continue spans;
  5837. oldCur.push(span);
  5838. }
  5839. } else if (stretchCur) {
  5840. old[i] = stretchCur;
  5841. }
  5842. }
  5843. return old;
  5844. }
  5845. // Used to 'clip' out readOnly ranges when making a change.
  5846. function removeReadOnlyRanges(doc, from, to) {
  5847. var markers = null;
  5848. doc.iter(from.line, to.line + 1, function(line) {
  5849. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  5850. var mark = line.markedSpans[i].marker;
  5851. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  5852. (markers || (markers = [])).push(mark);
  5853. }
  5854. });
  5855. if (!markers) return null;
  5856. var parts = [{from: from, to: to}];
  5857. for (var i = 0; i < markers.length; ++i) {
  5858. var mk = markers[i], m = mk.find(0);
  5859. for (var j = 0; j < parts.length; ++j) {
  5860. var p = parts[j];
  5861. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  5862. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  5863. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  5864. newParts.push({from: p.from, to: m.from});
  5865. if (dto > 0 || !mk.inclusiveRight && !dto)
  5866. newParts.push({from: m.to, to: p.to});
  5867. parts.splice.apply(parts, newParts);
  5868. j += newParts.length - 1;
  5869. }
  5870. }
  5871. return parts;
  5872. }
  5873. // Connect or disconnect spans from a line.
  5874. function detachMarkedSpans(line) {
  5875. var spans = line.markedSpans;
  5876. if (!spans) return;
  5877. for (var i = 0; i < spans.length; ++i)
  5878. spans[i].marker.detachLine(line);
  5879. line.markedSpans = null;
  5880. }
  5881. function attachMarkedSpans(line, spans) {
  5882. if (!spans) return;
  5883. for (var i = 0; i < spans.length; ++i)
  5884. spans[i].marker.attachLine(line);
  5885. line.markedSpans = spans;
  5886. }
  5887. // Helpers used when computing which overlapping collapsed span
  5888. // counts as the larger one.
  5889. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  5890. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  5891. // Returns a number indicating which of two overlapping collapsed
  5892. // spans is larger (and thus includes the other). Falls back to
  5893. // comparing ids when the spans cover exactly the same range.
  5894. function compareCollapsedMarkers(a, b) {
  5895. var lenDiff = a.lines.length - b.lines.length;
  5896. if (lenDiff != 0) return lenDiff;
  5897. var aPos = a.find(), bPos = b.find();
  5898. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  5899. if (fromCmp) return -fromCmp;
  5900. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  5901. if (toCmp) return toCmp;
  5902. return b.id - a.id;
  5903. }
  5904. // Find out whether a line ends or starts in a collapsed span. If
  5905. // so, return the marker for that span.
  5906. function collapsedSpanAtSide(line, start) {
  5907. var sps = sawCollapsedSpans && line.markedSpans, found;
  5908. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5909. sp = sps[i];
  5910. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  5911. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  5912. found = sp.marker;
  5913. }
  5914. return found;
  5915. }
  5916. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  5917. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  5918. // Test whether there exists a collapsed span that partially
  5919. // overlaps (covers the start or end, but not both) of a new span.
  5920. // Such overlap is not allowed.
  5921. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  5922. var line = getLine(doc, lineNo);
  5923. var sps = sawCollapsedSpans && line.markedSpans;
  5924. if (sps) for (var i = 0; i < sps.length; ++i) {
  5925. var sp = sps[i];
  5926. if (!sp.marker.collapsed) continue;
  5927. var found = sp.marker.find(0);
  5928. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  5929. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  5930. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  5931. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  5932. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  5933. return true;
  5934. }
  5935. }
  5936. // A visual line is a line as drawn on the screen. Folding, for
  5937. // example, can cause multiple logical lines to appear on the same
  5938. // visual line. This finds the start of the visual line that the
  5939. // given line is part of (usually that is the line itself).
  5940. function visualLine(line) {
  5941. var merged;
  5942. while (merged = collapsedSpanAtStart(line))
  5943. line = merged.find(-1, true).line;
  5944. return line;
  5945. }
  5946. // Returns an array of logical lines that continue the visual line
  5947. // started by the argument, or undefined if there are no such lines.
  5948. function visualLineContinued(line) {
  5949. var merged, lines;
  5950. while (merged = collapsedSpanAtEnd(line)) {
  5951. line = merged.find(1, true).line;
  5952. (lines || (lines = [])).push(line);
  5953. }
  5954. return lines;
  5955. }
  5956. // Get the line number of the start of the visual line that the
  5957. // given line number is part of.
  5958. function visualLineNo(doc, lineN) {
  5959. var line = getLine(doc, lineN), vis = visualLine(line);
  5960. if (line == vis) return lineN;
  5961. return lineNo(vis);
  5962. }
  5963. // Get the line number of the start of the next visual line after
  5964. // the given line.
  5965. function visualLineEndNo(doc, lineN) {
  5966. if (lineN > doc.lastLine()) return lineN;
  5967. var line = getLine(doc, lineN), merged;
  5968. if (!lineIsHidden(doc, line)) return lineN;
  5969. while (merged = collapsedSpanAtEnd(line))
  5970. line = merged.find(1, true).line;
  5971. return lineNo(line) + 1;
  5972. }
  5973. // Compute whether a line is hidden. Lines count as hidden when they
  5974. // are part of a visual line that starts with another line, or when
  5975. // they are entirely covered by collapsed, non-widget span.
  5976. function lineIsHidden(doc, line) {
  5977. var sps = sawCollapsedSpans && line.markedSpans;
  5978. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  5979. sp = sps[i];
  5980. if (!sp.marker.collapsed) continue;
  5981. if (sp.from == null) return true;
  5982. if (sp.marker.widgetNode) continue;
  5983. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  5984. return true;
  5985. }
  5986. }
  5987. function lineIsHiddenInner(doc, line, span) {
  5988. if (span.to == null) {
  5989. var end = span.marker.find(1, true);
  5990. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  5991. }
  5992. if (span.marker.inclusiveRight && span.to == line.text.length)
  5993. return true;
  5994. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  5995. sp = line.markedSpans[i];
  5996. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  5997. (sp.to == null || sp.to != span.from) &&
  5998. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  5999. lineIsHiddenInner(doc, line, sp)) return true;
  6000. }
  6001. }
  6002. // LINE WIDGETS
  6003. // Line widgets are block elements displayed above or below a line.
  6004. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  6005. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  6006. this[opt] = options[opt];
  6007. this.doc = doc;
  6008. this.node = node;
  6009. };
  6010. eventMixin(LineWidget);
  6011. function adjustScrollWhenAboveVisible(cm, line, diff) {
  6012. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  6013. addToScrollPos(cm, null, diff);
  6014. }
  6015. LineWidget.prototype.clear = function() {
  6016. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  6017. if (no == null || !ws) return;
  6018. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  6019. if (!ws.length) line.widgets = null;
  6020. var height = widgetHeight(this);
  6021. updateLineHeight(line, Math.max(0, line.height - height));
  6022. if (cm) runInOp(cm, function() {
  6023. adjustScrollWhenAboveVisible(cm, line, -height);
  6024. regLineChange(cm, no, "widget");
  6025. });
  6026. };
  6027. LineWidget.prototype.changed = function() {
  6028. var oldH = this.height, cm = this.doc.cm, line = this.line;
  6029. this.height = null;
  6030. var diff = widgetHeight(this) - oldH;
  6031. if (!diff) return;
  6032. updateLineHeight(line, line.height + diff);
  6033. if (cm) runInOp(cm, function() {
  6034. cm.curOp.forceUpdate = true;
  6035. adjustScrollWhenAboveVisible(cm, line, diff);
  6036. });
  6037. };
  6038. function widgetHeight(widget) {
  6039. if (widget.height != null) return widget.height;
  6040. var cm = widget.doc.cm;
  6041. if (!cm) return 0;
  6042. if (!contains(document.body, widget.node)) {
  6043. var parentStyle = "position: relative;";
  6044. if (widget.coverGutter)
  6045. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  6046. if (widget.noHScroll)
  6047. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  6048. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  6049. }
  6050. return widget.height = widget.node.parentNode.offsetHeight;
  6051. }
  6052. function addLineWidget(doc, handle, node, options) {
  6053. var widget = new LineWidget(doc, node, options);
  6054. var cm = doc.cm;
  6055. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  6056. changeLine(doc, handle, "widget", function(line) {
  6057. var widgets = line.widgets || (line.widgets = []);
  6058. if (widget.insertAt == null) widgets.push(widget);
  6059. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  6060. widget.line = line;
  6061. if (cm && !lineIsHidden(doc, line)) {
  6062. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  6063. updateLineHeight(line, line.height + widgetHeight(widget));
  6064. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  6065. cm.curOp.forceUpdate = true;
  6066. }
  6067. return true;
  6068. });
  6069. return widget;
  6070. }
  6071. // LINE DATA STRUCTURE
  6072. // Line objects. These hold state related to a line, including
  6073. // highlighting info (the styles array).
  6074. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  6075. this.text = text;
  6076. attachMarkedSpans(this, markedSpans);
  6077. this.height = estimateHeight ? estimateHeight(this) : 1;
  6078. };
  6079. eventMixin(Line);
  6080. Line.prototype.lineNo = function() { return lineNo(this); };
  6081. // Change the content (text, markers) of a line. Automatically
  6082. // invalidates cached information and tries to re-estimate the
  6083. // line's height.
  6084. function updateLine(line, text, markedSpans, estimateHeight) {
  6085. line.text = text;
  6086. if (line.stateAfter) line.stateAfter = null;
  6087. if (line.styles) line.styles = null;
  6088. if (line.order != null) line.order = null;
  6089. detachMarkedSpans(line);
  6090. attachMarkedSpans(line, markedSpans);
  6091. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  6092. if (estHeight != line.height) updateLineHeight(line, estHeight);
  6093. }
  6094. // Detach a line from the document tree and its markers.
  6095. function cleanUpLine(line) {
  6096. line.parent = null;
  6097. detachMarkedSpans(line);
  6098. }
  6099. function extractLineClasses(type, output) {
  6100. if (type) for (;;) {
  6101. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  6102. if (!lineClass) break;
  6103. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  6104. var prop = lineClass[1] ? "bgClass" : "textClass";
  6105. if (output[prop] == null)
  6106. output[prop] = lineClass[2];
  6107. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  6108. output[prop] += " " + lineClass[2];
  6109. }
  6110. return type;
  6111. }
  6112. function callBlankLine(mode, state) {
  6113. if (mode.blankLine) return mode.blankLine(state);
  6114. if (!mode.innerMode) return;
  6115. var inner = CodeMirror.innerMode(mode, state);
  6116. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  6117. }
  6118. function readToken(mode, stream, state, inner) {
  6119. for (var i = 0; i < 10; i++) {
  6120. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  6121. var style = mode.token(stream, state);
  6122. if (stream.pos > stream.start) return style;
  6123. }
  6124. throw new Error("Mode " + mode.name + " failed to advance stream.");
  6125. }
  6126. // Utility for getTokenAt and getLineTokens
  6127. function takeToken(cm, pos, precise, asArray) {
  6128. function getObj(copy) {
  6129. return {start: stream.start, end: stream.pos,
  6130. string: stream.current(),
  6131. type: style || null,
  6132. state: copy ? copyState(doc.mode, state) : state};
  6133. }
  6134. var doc = cm.doc, mode = doc.mode, style;
  6135. pos = clipPos(doc, pos);
  6136. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  6137. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  6138. if (asArray) tokens = [];
  6139. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  6140. stream.start = stream.pos;
  6141. style = readToken(mode, stream, state);
  6142. if (asArray) tokens.push(getObj(true));
  6143. }
  6144. return asArray ? tokens : getObj();
  6145. }
  6146. // Run the given mode's parser over a line, calling f for each token.
  6147. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  6148. var flattenSpans = mode.flattenSpans;
  6149. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  6150. var curStart = 0, curStyle = null;
  6151. var stream = new StringStream(text, cm.options.tabSize), style;
  6152. var inner = cm.options.addModeClass && [null];
  6153. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  6154. while (!stream.eol()) {
  6155. if (stream.pos > cm.options.maxHighlightLength) {
  6156. flattenSpans = false;
  6157. if (forceToEnd) processLine(cm, text, state, stream.pos);
  6158. stream.pos = text.length;
  6159. style = null;
  6160. } else {
  6161. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  6162. }
  6163. if (inner) {
  6164. var mName = inner[0].name;
  6165. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  6166. }
  6167. if (!flattenSpans || curStyle != style) {
  6168. while (curStart < stream.start) {
  6169. curStart = Math.min(stream.start, curStart + 50000);
  6170. f(curStart, curStyle);
  6171. }
  6172. curStyle = style;
  6173. }
  6174. stream.start = stream.pos;
  6175. }
  6176. while (curStart < stream.pos) {
  6177. // Webkit seems to refuse to render text nodes longer than 57444 characters
  6178. var pos = Math.min(stream.pos, curStart + 50000);
  6179. f(pos, curStyle);
  6180. curStart = pos;
  6181. }
  6182. }
  6183. // Compute a style array (an array starting with a mode generation
  6184. // -- for invalidation -- followed by pairs of end positions and
  6185. // style strings), which is used to highlight the tokens on the
  6186. // line.
  6187. function highlightLine(cm, line, state, forceToEnd) {
  6188. // A styles array always starts with a number identifying the
  6189. // mode/overlays that it is based on (for easy invalidation).
  6190. var st = [cm.state.modeGen], lineClasses = {};
  6191. // Compute the base array of styles
  6192. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  6193. st.push(end, style);
  6194. }, lineClasses, forceToEnd);
  6195. // Run overlays, adjust style array.
  6196. for (var o = 0; o < cm.state.overlays.length; ++o) {
  6197. var overlay = cm.state.overlays[o], i = 1, at = 0;
  6198. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  6199. var start = i;
  6200. // Ensure there's a token end at the current position, and that i points at it
  6201. while (at < end) {
  6202. var i_end = st[i];
  6203. if (i_end > end)
  6204. st.splice(i, 1, end, st[i+1], i_end);
  6205. i += 2;
  6206. at = Math.min(end, i_end);
  6207. }
  6208. if (!style) return;
  6209. if (overlay.opaque) {
  6210. st.splice(start, i - start, end, "cm-overlay " + style);
  6211. i = start + 2;
  6212. } else {
  6213. for (; start < i; start += 2) {
  6214. var cur = st[start+1];
  6215. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  6216. }
  6217. }
  6218. }, lineClasses);
  6219. }
  6220. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  6221. }
  6222. function getLineStyles(cm, line, updateFrontier) {
  6223. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  6224. var state = getStateBefore(cm, lineNo(line));
  6225. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  6226. line.stateAfter = state;
  6227. line.styles = result.styles;
  6228. if (result.classes) line.styleClasses = result.classes;
  6229. else if (line.styleClasses) line.styleClasses = null;
  6230. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  6231. }
  6232. return line.styles;
  6233. }
  6234. // Lightweight form of highlight -- proceed over this line and
  6235. // update state, but don't save a style array. Used for lines that
  6236. // aren't currently visible.
  6237. function processLine(cm, text, state, startAt) {
  6238. var mode = cm.doc.mode;
  6239. var stream = new StringStream(text, cm.options.tabSize);
  6240. stream.start = stream.pos = startAt || 0;
  6241. if (text == "") callBlankLine(mode, state);
  6242. while (!stream.eol()) {
  6243. readToken(mode, stream, state);
  6244. stream.start = stream.pos;
  6245. }
  6246. }
  6247. // Convert a style as returned by a mode (either null, or a string
  6248. // containing one or more styles) to a CSS style. This is cached,
  6249. // and also looks for line-wide styles.
  6250. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  6251. function interpretTokenStyle(style, options) {
  6252. if (!style || /^\s*$/.test(style)) return null;
  6253. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  6254. return cache[style] ||
  6255. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  6256. }
  6257. // Render the DOM representation of the text of a line. Also builds
  6258. // up a 'line map', which points at the DOM nodes that represent
  6259. // specific stretches of text, and is used by the measuring code.
  6260. // The returned object contains the DOM node, this map, and
  6261. // information about line-wide styles that were set by the mode.
  6262. function buildLineContent(cm, lineView) {
  6263. // The padding-right forces the element to have a 'border', which
  6264. // is needed on Webkit to be able to get line-level bounding
  6265. // rectangles for it (in measureChar).
  6266. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  6267. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  6268. col: 0, pos: 0, cm: cm,
  6269. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  6270. lineView.measure = {};
  6271. // Iterate over the logical lines that make up this visual line.
  6272. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  6273. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  6274. builder.pos = 0;
  6275. builder.addToken = buildToken;
  6276. // Optionally wire in some hacks into the token-rendering
  6277. // algorithm, to deal with browser quirks.
  6278. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  6279. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  6280. builder.map = [];
  6281. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  6282. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  6283. if (line.styleClasses) {
  6284. if (line.styleClasses.bgClass)
  6285. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  6286. if (line.styleClasses.textClass)
  6287. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  6288. }
  6289. // Ensure at least a single node is present, for measuring.
  6290. if (builder.map.length == 0)
  6291. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  6292. // Store the map and a cache object for the current logical line
  6293. if (i == 0) {
  6294. lineView.measure.map = builder.map;
  6295. lineView.measure.cache = {};
  6296. } else {
  6297. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  6298. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  6299. }
  6300. }
  6301. // See issue #2901
  6302. if (webkit) {
  6303. var last = builder.content.lastChild
  6304. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  6305. builder.content.className = "cm-tab-wrap-hack";
  6306. }
  6307. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  6308. if (builder.pre.className)
  6309. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  6310. return builder;
  6311. }
  6312. function defaultSpecialCharPlaceholder(ch) {
  6313. var token = elt("span", "\u2022", "cm-invalidchar");
  6314. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  6315. token.setAttribute("aria-label", token.title);
  6316. return token;
  6317. }
  6318. // Build up the DOM representation for a single token, and add it to
  6319. // the line map. Takes care to render special characters separately.
  6320. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  6321. if (!text) return;
  6322. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  6323. var special = builder.cm.state.specialChars, mustWrap = false;
  6324. if (!special.test(text)) {
  6325. builder.col += text.length;
  6326. var content = document.createTextNode(displayText);
  6327. builder.map.push(builder.pos, builder.pos + text.length, content);
  6328. if (ie && ie_version < 9) mustWrap = true;
  6329. builder.pos += text.length;
  6330. } else {
  6331. var content = document.createDocumentFragment(), pos = 0;
  6332. while (true) {
  6333. special.lastIndex = pos;
  6334. var m = special.exec(text);
  6335. var skipped = m ? m.index - pos : text.length - pos;
  6336. if (skipped) {
  6337. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  6338. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6339. else content.appendChild(txt);
  6340. builder.map.push(builder.pos, builder.pos + skipped, txt);
  6341. builder.col += skipped;
  6342. builder.pos += skipped;
  6343. }
  6344. if (!m) break;
  6345. pos += skipped + 1;
  6346. if (m[0] == "\t") {
  6347. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  6348. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  6349. txt.setAttribute("role", "presentation");
  6350. txt.setAttribute("cm-text", "\t");
  6351. builder.col += tabWidth;
  6352. } else if (m[0] == "\r" || m[0] == "\n") {
  6353. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  6354. txt.setAttribute("cm-text", m[0]);
  6355. builder.col += 1;
  6356. } else {
  6357. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  6358. txt.setAttribute("cm-text", m[0]);
  6359. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  6360. else content.appendChild(txt);
  6361. builder.col += 1;
  6362. }
  6363. builder.map.push(builder.pos, builder.pos + 1, txt);
  6364. builder.pos++;
  6365. }
  6366. }
  6367. if (style || startStyle || endStyle || mustWrap || css) {
  6368. var fullStyle = style || "";
  6369. if (startStyle) fullStyle += startStyle;
  6370. if (endStyle) fullStyle += endStyle;
  6371. var token = elt("span", [content], fullStyle, css);
  6372. if (title) token.title = title;
  6373. return builder.content.appendChild(token);
  6374. }
  6375. builder.content.appendChild(content);
  6376. }
  6377. function splitSpaces(old) {
  6378. var out = " ";
  6379. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  6380. out += " ";
  6381. return out;
  6382. }
  6383. // Work around nonsense dimensions being reported for stretches of
  6384. // right-to-left text.
  6385. function buildTokenBadBidi(inner, order) {
  6386. return function(builder, text, style, startStyle, endStyle, title, css) {
  6387. style = style ? style + " cm-force-border" : "cm-force-border";
  6388. var start = builder.pos, end = start + text.length;
  6389. for (;;) {
  6390. // Find the part that overlaps with the start of this text
  6391. for (var i = 0; i < order.length; i++) {
  6392. var part = order[i];
  6393. if (part.to > start && part.from <= start) break;
  6394. }
  6395. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  6396. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  6397. startStyle = null;
  6398. text = text.slice(part.to - start);
  6399. start = part.to;
  6400. }
  6401. };
  6402. }
  6403. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  6404. var widget = !ignoreWidget && marker.widgetNode;
  6405. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  6406. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  6407. if (!widget)
  6408. widget = builder.content.appendChild(document.createElement("span"));
  6409. widget.setAttribute("cm-marker", marker.id);
  6410. }
  6411. if (widget) {
  6412. builder.cm.display.input.setUneditable(widget);
  6413. builder.content.appendChild(widget);
  6414. }
  6415. builder.pos += size;
  6416. }
  6417. // Outputs a number of spans to make up a line, taking highlighting
  6418. // and marked text into account.
  6419. function insertLineContent(line, builder, styles) {
  6420. var spans = line.markedSpans, allText = line.text, at = 0;
  6421. if (!spans) {
  6422. for (var i = 1; i < styles.length; i+=2)
  6423. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  6424. return;
  6425. }
  6426. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  6427. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  6428. for (;;) {
  6429. if (nextChange == pos) { // Update current marker set
  6430. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  6431. collapsed = null; nextChange = Infinity;
  6432. var foundBookmarks = [], endStyles
  6433. for (var j = 0; j < spans.length; ++j) {
  6434. var sp = spans[j], m = sp.marker;
  6435. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  6436. foundBookmarks.push(m);
  6437. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  6438. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  6439. nextChange = sp.to;
  6440. spanEndStyle = "";
  6441. }
  6442. if (m.className) spanStyle += " " + m.className;
  6443. if (m.css) css = (css ? css + ";" : "") + m.css;
  6444. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  6445. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  6446. if (m.title && !title) title = m.title;
  6447. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  6448. collapsed = sp;
  6449. } else if (sp.from > pos && nextChange > sp.from) {
  6450. nextChange = sp.from;
  6451. }
  6452. }
  6453. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  6454. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  6455. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  6456. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  6457. if (collapsed && (collapsed.from || 0) == pos) {
  6458. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  6459. collapsed.marker, collapsed.from == null);
  6460. if (collapsed.to == null) return;
  6461. if (collapsed.to == pos) collapsed = false;
  6462. }
  6463. }
  6464. if (pos >= len) break;
  6465. var upto = Math.min(len, nextChange);
  6466. while (true) {
  6467. if (text) {
  6468. var end = pos + text.length;
  6469. if (!collapsed) {
  6470. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  6471. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  6472. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  6473. }
  6474. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  6475. pos = end;
  6476. spanStartStyle = "";
  6477. }
  6478. text = allText.slice(at, at = styles[i++]);
  6479. style = interpretTokenStyle(styles[i++], builder.cm.options);
  6480. }
  6481. }
  6482. }
  6483. // DOCUMENT DATA STRUCTURE
  6484. // By default, updates that start and end at the beginning of a line
  6485. // are treated specially, in order to make the association of line
  6486. // widgets and marker elements with the text behave more intuitive.
  6487. function isWholeLineUpdate(doc, change) {
  6488. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6489. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  6490. }
  6491. // Perform a change on the document data structure.
  6492. function updateDoc(doc, change, markedSpans, estimateHeight) {
  6493. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  6494. function update(line, text, spans) {
  6495. updateLine(line, text, spans, estimateHeight);
  6496. signalLater(line, "change", line, change);
  6497. }
  6498. function linesFor(start, end) {
  6499. for (var i = start, result = []; i < end; ++i)
  6500. result.push(new Line(text[i], spansFor(i), estimateHeight));
  6501. return result;
  6502. }
  6503. var from = change.from, to = change.to, text = change.text;
  6504. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6505. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6506. // Adjust the line structure
  6507. if (change.full) {
  6508. doc.insert(0, linesFor(0, text.length));
  6509. doc.remove(text.length, doc.size - text.length);
  6510. } else if (isWholeLineUpdate(doc, change)) {
  6511. // This is a whole-line replace. Treated specially to make
  6512. // sure line objects move the way they are supposed to.
  6513. var added = linesFor(0, text.length - 1);
  6514. update(lastLine, lastLine.text, lastSpans);
  6515. if (nlines) doc.remove(from.line, nlines);
  6516. if (added.length) doc.insert(from.line, added);
  6517. } else if (firstLine == lastLine) {
  6518. if (text.length == 1) {
  6519. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6520. } else {
  6521. var added = linesFor(1, text.length - 1);
  6522. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  6523. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6524. doc.insert(from.line + 1, added);
  6525. }
  6526. } else if (text.length == 1) {
  6527. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6528. doc.remove(from.line + 1, nlines);
  6529. } else {
  6530. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6531. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6532. var added = linesFor(1, text.length - 1);
  6533. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  6534. doc.insert(from.line + 1, added);
  6535. }
  6536. signalLater(doc, "change", doc, change);
  6537. }
  6538. // The document is represented as a BTree consisting of leaves, with
  6539. // chunk of lines in them, and branches, with up to ten leaves or
  6540. // other branch nodes below them. The top node is always a branch
  6541. // node, and is the document object itself (meaning it has
  6542. // additional methods and properties).
  6543. //
  6544. // All nodes have parent links. The tree is used both to go from
  6545. // line numbers to line objects, and to go from objects to numbers.
  6546. // It also indexes by height, and is used to convert between height
  6547. // and line object, and to find the total height of the document.
  6548. //
  6549. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6550. function LeafChunk(lines) {
  6551. this.lines = lines;
  6552. this.parent = null;
  6553. for (var i = 0, height = 0; i < lines.length; ++i) {
  6554. lines[i].parent = this;
  6555. height += lines[i].height;
  6556. }
  6557. this.height = height;
  6558. }
  6559. LeafChunk.prototype = {
  6560. chunkSize: function() { return this.lines.length; },
  6561. // Remove the n lines at offset 'at'.
  6562. removeInner: function(at, n) {
  6563. for (var i = at, e = at + n; i < e; ++i) {
  6564. var line = this.lines[i];
  6565. this.height -= line.height;
  6566. cleanUpLine(line);
  6567. signalLater(line, "delete");
  6568. }
  6569. this.lines.splice(at, n);
  6570. },
  6571. // Helper used to collapse a small branch into a single leaf.
  6572. collapse: function(lines) {
  6573. lines.push.apply(lines, this.lines);
  6574. },
  6575. // Insert the given array of lines at offset 'at', count them as
  6576. // having the given height.
  6577. insertInner: function(at, lines, height) {
  6578. this.height += height;
  6579. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6580. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  6581. },
  6582. // Used to iterate over a part of the tree.
  6583. iterN: function(at, n, op) {
  6584. for (var e = at + n; at < e; ++at)
  6585. if (op(this.lines[at])) return true;
  6586. }
  6587. };
  6588. function BranchChunk(children) {
  6589. this.children = children;
  6590. var size = 0, height = 0;
  6591. for (var i = 0; i < children.length; ++i) {
  6592. var ch = children[i];
  6593. size += ch.chunkSize(); height += ch.height;
  6594. ch.parent = this;
  6595. }
  6596. this.size = size;
  6597. this.height = height;
  6598. this.parent = null;
  6599. }
  6600. BranchChunk.prototype = {
  6601. chunkSize: function() { return this.size; },
  6602. removeInner: function(at, n) {
  6603. this.size -= n;
  6604. for (var i = 0; i < this.children.length; ++i) {
  6605. var child = this.children[i], sz = child.chunkSize();
  6606. if (at < sz) {
  6607. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6608. child.removeInner(at, rm);
  6609. this.height -= oldHeight - child.height;
  6610. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  6611. if ((n -= rm) == 0) break;
  6612. at = 0;
  6613. } else at -= sz;
  6614. }
  6615. // If the result is smaller than 25 lines, ensure that it is a
  6616. // single leaf node.
  6617. if (this.size - n < 25 &&
  6618. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6619. var lines = [];
  6620. this.collapse(lines);
  6621. this.children = [new LeafChunk(lines)];
  6622. this.children[0].parent = this;
  6623. }
  6624. },
  6625. collapse: function(lines) {
  6626. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  6627. },
  6628. insertInner: function(at, lines, height) {
  6629. this.size += lines.length;
  6630. this.height += height;
  6631. for (var i = 0; i < this.children.length; ++i) {
  6632. var child = this.children[i], sz = child.chunkSize();
  6633. if (at <= sz) {
  6634. child.insertInner(at, lines, height);
  6635. if (child.lines && child.lines.length > 50) {
  6636. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  6637. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  6638. var remaining = child.lines.length % 25 + 25
  6639. for (var pos = remaining; pos < child.lines.length;) {
  6640. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  6641. child.height -= leaf.height;
  6642. this.children.splice(++i, 0, leaf);
  6643. leaf.parent = this;
  6644. }
  6645. child.lines = child.lines.slice(0, remaining);
  6646. this.maybeSpill();
  6647. }
  6648. break;
  6649. }
  6650. at -= sz;
  6651. }
  6652. },
  6653. // When a node has grown, check whether it should be split.
  6654. maybeSpill: function() {
  6655. if (this.children.length <= 10) return;
  6656. var me = this;
  6657. do {
  6658. var spilled = me.children.splice(me.children.length - 5, 5);
  6659. var sibling = new BranchChunk(spilled);
  6660. if (!me.parent) { // Become the parent node
  6661. var copy = new BranchChunk(me.children);
  6662. copy.parent = me;
  6663. me.children = [copy, sibling];
  6664. me = copy;
  6665. } else {
  6666. me.size -= sibling.size;
  6667. me.height -= sibling.height;
  6668. var myIndex = indexOf(me.parent.children, me);
  6669. me.parent.children.splice(myIndex + 1, 0, sibling);
  6670. }
  6671. sibling.parent = me.parent;
  6672. } while (me.children.length > 10);
  6673. me.parent.maybeSpill();
  6674. },
  6675. iterN: function(at, n, op) {
  6676. for (var i = 0; i < this.children.length; ++i) {
  6677. var child = this.children[i], sz = child.chunkSize();
  6678. if (at < sz) {
  6679. var used = Math.min(n, sz - at);
  6680. if (child.iterN(at, used, op)) return true;
  6681. if ((n -= used) == 0) break;
  6682. at = 0;
  6683. } else at -= sz;
  6684. }
  6685. }
  6686. };
  6687. var nextDocId = 0;
  6688. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  6689. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  6690. if (firstLine == null) firstLine = 0;
  6691. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  6692. this.first = firstLine;
  6693. this.scrollTop = this.scrollLeft = 0;
  6694. this.cantEdit = false;
  6695. this.cleanGeneration = 1;
  6696. this.frontier = firstLine;
  6697. var start = Pos(firstLine, 0);
  6698. this.sel = simpleSelection(start);
  6699. this.history = new History(null);
  6700. this.id = ++nextDocId;
  6701. this.modeOption = mode;
  6702. this.lineSep = lineSep;
  6703. this.extend = false;
  6704. if (typeof text == "string") text = this.splitLines(text);
  6705. updateDoc(this, {from: start, to: start, text: text});
  6706. setSelection(this, simpleSelection(start), sel_dontScroll);
  6707. };
  6708. Doc.prototype = createObj(BranchChunk.prototype, {
  6709. constructor: Doc,
  6710. // Iterate over the document. Supports two forms -- with only one
  6711. // argument, it calls that for each line in the document. With
  6712. // three, it iterates over the range given by the first two (with
  6713. // the second being non-inclusive).
  6714. iter: function(from, to, op) {
  6715. if (op) this.iterN(from - this.first, to - from, op);
  6716. else this.iterN(this.first, this.first + this.size, from);
  6717. },
  6718. // Non-public interface for adding and removing lines.
  6719. insert: function(at, lines) {
  6720. var height = 0;
  6721. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  6722. this.insertInner(at - this.first, lines, height);
  6723. },
  6724. remove: function(at, n) { this.removeInner(at - this.first, n); },
  6725. // From here, the methods are part of the public interface. Most
  6726. // are also available from CodeMirror (editor) instances.
  6727. getValue: function(lineSep) {
  6728. var lines = getLines(this, this.first, this.first + this.size);
  6729. if (lineSep === false) return lines;
  6730. return lines.join(lineSep || this.lineSeparator());
  6731. },
  6732. setValue: docMethodOp(function(code) {
  6733. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  6734. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  6735. text: this.splitLines(code), origin: "setValue", full: true}, true);
  6736. setSelection(this, simpleSelection(top));
  6737. }),
  6738. replaceRange: function(code, from, to, origin) {
  6739. from = clipPos(this, from);
  6740. to = to ? clipPos(this, to) : from;
  6741. replaceRange(this, code, from, to, origin);
  6742. },
  6743. getRange: function(from, to, lineSep) {
  6744. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  6745. if (lineSep === false) return lines;
  6746. return lines.join(lineSep || this.lineSeparator());
  6747. },
  6748. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  6749. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  6750. getLineNumber: function(line) {return lineNo(line);},
  6751. getLineHandleVisualStart: function(line) {
  6752. if (typeof line == "number") line = getLine(this, line);
  6753. return visualLine(line);
  6754. },
  6755. lineCount: function() {return this.size;},
  6756. firstLine: function() {return this.first;},
  6757. lastLine: function() {return this.first + this.size - 1;},
  6758. clipPos: function(pos) {return clipPos(this, pos);},
  6759. getCursor: function(start) {
  6760. var range = this.sel.primary(), pos;
  6761. if (start == null || start == "head") pos = range.head;
  6762. else if (start == "anchor") pos = range.anchor;
  6763. else if (start == "end" || start == "to" || start === false) pos = range.to();
  6764. else pos = range.from();
  6765. return pos;
  6766. },
  6767. listSelections: function() { return this.sel.ranges; },
  6768. somethingSelected: function() {return this.sel.somethingSelected();},
  6769. setCursor: docMethodOp(function(line, ch, options) {
  6770. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  6771. }),
  6772. setSelection: docMethodOp(function(anchor, head, options) {
  6773. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  6774. }),
  6775. extendSelection: docMethodOp(function(head, other, options) {
  6776. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  6777. }),
  6778. extendSelections: docMethodOp(function(heads, options) {
  6779. extendSelections(this, clipPosArray(this, heads), options);
  6780. }),
  6781. extendSelectionsBy: docMethodOp(function(f, options) {
  6782. var heads = map(this.sel.ranges, f);
  6783. extendSelections(this, clipPosArray(this, heads), options);
  6784. }),
  6785. setSelections: docMethodOp(function(ranges, primary, options) {
  6786. if (!ranges.length) return;
  6787. for (var i = 0, out = []; i < ranges.length; i++)
  6788. out[i] = new Range(clipPos(this, ranges[i].anchor),
  6789. clipPos(this, ranges[i].head));
  6790. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  6791. setSelection(this, normalizeSelection(out, primary), options);
  6792. }),
  6793. addSelection: docMethodOp(function(anchor, head, options) {
  6794. var ranges = this.sel.ranges.slice(0);
  6795. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  6796. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  6797. }),
  6798. getSelection: function(lineSep) {
  6799. var ranges = this.sel.ranges, lines;
  6800. for (var i = 0; i < ranges.length; i++) {
  6801. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6802. lines = lines ? lines.concat(sel) : sel;
  6803. }
  6804. if (lineSep === false) return lines;
  6805. else return lines.join(lineSep || this.lineSeparator());
  6806. },
  6807. getSelections: function(lineSep) {
  6808. var parts = [], ranges = this.sel.ranges;
  6809. for (var i = 0; i < ranges.length; i++) {
  6810. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  6811. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  6812. parts[i] = sel;
  6813. }
  6814. return parts;
  6815. },
  6816. replaceSelection: function(code, collapse, origin) {
  6817. var dup = [];
  6818. for (var i = 0; i < this.sel.ranges.length; i++)
  6819. dup[i] = code;
  6820. this.replaceSelections(dup, collapse, origin || "+input");
  6821. },
  6822. replaceSelections: docMethodOp(function(code, collapse, origin) {
  6823. var changes = [], sel = this.sel;
  6824. for (var i = 0; i < sel.ranges.length; i++) {
  6825. var range = sel.ranges[i];
  6826. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  6827. }
  6828. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  6829. for (var i = changes.length - 1; i >= 0; i--)
  6830. makeChange(this, changes[i]);
  6831. if (newSel) setSelectionReplaceHistory(this, newSel);
  6832. else if (this.cm) ensureCursorVisible(this.cm);
  6833. }),
  6834. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  6835. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  6836. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  6837. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  6838. setExtending: function(val) {this.extend = val;},
  6839. getExtending: function() {return this.extend;},
  6840. historySize: function() {
  6841. var hist = this.history, done = 0, undone = 0;
  6842. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  6843. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  6844. return {undo: done, redo: undone};
  6845. },
  6846. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  6847. markClean: function() {
  6848. this.cleanGeneration = this.changeGeneration(true);
  6849. },
  6850. changeGeneration: function(forceSplit) {
  6851. if (forceSplit)
  6852. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  6853. return this.history.generation;
  6854. },
  6855. isClean: function (gen) {
  6856. return this.history.generation == (gen || this.cleanGeneration);
  6857. },
  6858. getHistory: function() {
  6859. return {done: copyHistoryArray(this.history.done),
  6860. undone: copyHistoryArray(this.history.undone)};
  6861. },
  6862. setHistory: function(histData) {
  6863. var hist = this.history = new History(this.history.maxGeneration);
  6864. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  6865. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  6866. },
  6867. addLineClass: docMethodOp(function(handle, where, cls) {
  6868. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6869. var prop = where == "text" ? "textClass"
  6870. : where == "background" ? "bgClass"
  6871. : where == "gutter" ? "gutterClass" : "wrapClass";
  6872. if (!line[prop]) line[prop] = cls;
  6873. else if (classTest(cls).test(line[prop])) return false;
  6874. else line[prop] += " " + cls;
  6875. return true;
  6876. });
  6877. }),
  6878. removeLineClass: docMethodOp(function(handle, where, cls) {
  6879. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  6880. var prop = where == "text" ? "textClass"
  6881. : where == "background" ? "bgClass"
  6882. : where == "gutter" ? "gutterClass" : "wrapClass";
  6883. var cur = line[prop];
  6884. if (!cur) return false;
  6885. else if (cls == null) line[prop] = null;
  6886. else {
  6887. var found = cur.match(classTest(cls));
  6888. if (!found) return false;
  6889. var end = found.index + found[0].length;
  6890. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  6891. }
  6892. return true;
  6893. });
  6894. }),
  6895. addLineWidget: docMethodOp(function(handle, node, options) {
  6896. return addLineWidget(this, handle, node, options);
  6897. }),
  6898. removeLineWidget: function(widget) { widget.clear(); },
  6899. markText: function(from, to, options) {
  6900. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  6901. },
  6902. setBookmark: function(pos, options) {
  6903. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  6904. insertLeft: options && options.insertLeft,
  6905. clearWhenEmpty: false, shared: options && options.shared,
  6906. handleMouseEvents: options && options.handleMouseEvents};
  6907. pos = clipPos(this, pos);
  6908. return markText(this, pos, pos, realOpts, "bookmark");
  6909. },
  6910. findMarksAt: function(pos) {
  6911. pos = clipPos(this, pos);
  6912. var markers = [], spans = getLine(this, pos.line).markedSpans;
  6913. if (spans) for (var i = 0; i < spans.length; ++i) {
  6914. var span = spans[i];
  6915. if ((span.from == null || span.from <= pos.ch) &&
  6916. (span.to == null || span.to >= pos.ch))
  6917. markers.push(span.marker.parent || span.marker);
  6918. }
  6919. return markers;
  6920. },
  6921. findMarks: function(from, to, filter) {
  6922. from = clipPos(this, from); to = clipPos(this, to);
  6923. var found = [], lineNo = from.line;
  6924. this.iter(from.line, to.line + 1, function(line) {
  6925. var spans = line.markedSpans;
  6926. if (spans) for (var i = 0; i < spans.length; i++) {
  6927. var span = spans[i];
  6928. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  6929. span.from == null && lineNo != from.line ||
  6930. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  6931. (!filter || filter(span.marker)))
  6932. found.push(span.marker.parent || span.marker);
  6933. }
  6934. ++lineNo;
  6935. });
  6936. return found;
  6937. },
  6938. getAllMarks: function() {
  6939. var markers = [];
  6940. this.iter(function(line) {
  6941. var sps = line.markedSpans;
  6942. if (sps) for (var i = 0; i < sps.length; ++i)
  6943. if (sps[i].from != null) markers.push(sps[i].marker);
  6944. });
  6945. return markers;
  6946. },
  6947. posFromIndex: function(off) {
  6948. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  6949. this.iter(function(line) {
  6950. var sz = line.text.length + sepSize;
  6951. if (sz > off) { ch = off; return true; }
  6952. off -= sz;
  6953. ++lineNo;
  6954. });
  6955. return clipPos(this, Pos(lineNo, ch));
  6956. },
  6957. indexFromPos: function (coords) {
  6958. coords = clipPos(this, coords);
  6959. var index = coords.ch;
  6960. if (coords.line < this.first || coords.ch < 0) return 0;
  6961. var sepSize = this.lineSeparator().length;
  6962. this.iter(this.first, coords.line, function (line) {
  6963. index += line.text.length + sepSize;
  6964. });
  6965. return index;
  6966. },
  6967. copy: function(copyHistory) {
  6968. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  6969. this.modeOption, this.first, this.lineSep);
  6970. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  6971. doc.sel = this.sel;
  6972. doc.extend = false;
  6973. if (copyHistory) {
  6974. doc.history.undoDepth = this.history.undoDepth;
  6975. doc.setHistory(this.getHistory());
  6976. }
  6977. return doc;
  6978. },
  6979. linkedDoc: function(options) {
  6980. if (!options) options = {};
  6981. var from = this.first, to = this.first + this.size;
  6982. if (options.from != null && options.from > from) from = options.from;
  6983. if (options.to != null && options.to < to) to = options.to;
  6984. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  6985. if (options.sharedHist) copy.history = this.history;
  6986. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  6987. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  6988. copySharedMarkers(copy, findSharedMarkers(this));
  6989. return copy;
  6990. },
  6991. unlinkDoc: function(other) {
  6992. if (other instanceof CodeMirror) other = other.doc;
  6993. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  6994. var link = this.linked[i];
  6995. if (link.doc != other) continue;
  6996. this.linked.splice(i, 1);
  6997. other.unlinkDoc(this);
  6998. detachSharedMarkers(findSharedMarkers(this));
  6999. break;
  7000. }
  7001. // If the histories were shared, split them again
  7002. if (other.history == this.history) {
  7003. var splitIds = [other.id];
  7004. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  7005. other.history = new History(null);
  7006. other.history.done = copyHistoryArray(this.history.done, splitIds);
  7007. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  7008. }
  7009. },
  7010. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  7011. getMode: function() {return this.mode;},
  7012. getEditor: function() {return this.cm;},
  7013. splitLines: function(str) {
  7014. if (this.lineSep) return str.split(this.lineSep);
  7015. return splitLinesAuto(str);
  7016. },
  7017. lineSeparator: function() { return this.lineSep || "\n"; }
  7018. });
  7019. // Public alias.
  7020. Doc.prototype.eachLine = Doc.prototype.iter;
  7021. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  7022. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  7023. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  7024. CodeMirror.prototype[prop] = (function(method) {
  7025. return function() {return method.apply(this.doc, arguments);};
  7026. })(Doc.prototype[prop]);
  7027. eventMixin(Doc);
  7028. // Call f for all linked documents.
  7029. function linkedDocs(doc, f, sharedHistOnly) {
  7030. function propagate(doc, skip, sharedHist) {
  7031. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  7032. var rel = doc.linked[i];
  7033. if (rel.doc == skip) continue;
  7034. var shared = sharedHist && rel.sharedHist;
  7035. if (sharedHistOnly && !shared) continue;
  7036. f(rel.doc, shared);
  7037. propagate(rel.doc, doc, shared);
  7038. }
  7039. }
  7040. propagate(doc, null, true);
  7041. }
  7042. // Attach a document to an editor.
  7043. function attachDoc(cm, doc) {
  7044. if (doc.cm) throw new Error("This document is already in use.");
  7045. cm.doc = doc;
  7046. doc.cm = cm;
  7047. estimateLineHeights(cm);
  7048. loadMode(cm);
  7049. if (!cm.options.lineWrapping) findMaxLine(cm);
  7050. cm.options.mode = doc.modeOption;
  7051. regChange(cm);
  7052. }
  7053. // LINE UTILITIES
  7054. // Find the line object corresponding to the given line number.
  7055. function getLine(doc, n) {
  7056. n -= doc.first;
  7057. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  7058. for (var chunk = doc; !chunk.lines;) {
  7059. for (var i = 0;; ++i) {
  7060. var child = chunk.children[i], sz = child.chunkSize();
  7061. if (n < sz) { chunk = child; break; }
  7062. n -= sz;
  7063. }
  7064. }
  7065. return chunk.lines[n];
  7066. }
  7067. // Get the part of a document between two positions, as an array of
  7068. // strings.
  7069. function getBetween(doc, start, end) {
  7070. var out = [], n = start.line;
  7071. doc.iter(start.line, end.line + 1, function(line) {
  7072. var text = line.text;
  7073. if (n == end.line) text = text.slice(0, end.ch);
  7074. if (n == start.line) text = text.slice(start.ch);
  7075. out.push(text);
  7076. ++n;
  7077. });
  7078. return out;
  7079. }
  7080. // Get the lines between from and to, as array of strings.
  7081. function getLines(doc, from, to) {
  7082. var out = [];
  7083. doc.iter(from, to, function(line) { out.push(line.text); });
  7084. return out;
  7085. }
  7086. // Update the height of a line, propagating the height change
  7087. // upwards to parent nodes.
  7088. function updateLineHeight(line, height) {
  7089. var diff = height - line.height;
  7090. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  7091. }
  7092. // Given a line object, find its line number by walking up through
  7093. // its parent links.
  7094. function lineNo(line) {
  7095. if (line.parent == null) return null;
  7096. var cur = line.parent, no = indexOf(cur.lines, line);
  7097. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  7098. for (var i = 0;; ++i) {
  7099. if (chunk.children[i] == cur) break;
  7100. no += chunk.children[i].chunkSize();
  7101. }
  7102. }
  7103. return no + cur.first;
  7104. }
  7105. // Find the line at the given vertical position, using the height
  7106. // information in the document tree.
  7107. function lineAtHeight(chunk, h) {
  7108. var n = chunk.first;
  7109. outer: do {
  7110. for (var i = 0; i < chunk.children.length; ++i) {
  7111. var child = chunk.children[i], ch = child.height;
  7112. if (h < ch) { chunk = child; continue outer; }
  7113. h -= ch;
  7114. n += child.chunkSize();
  7115. }
  7116. return n;
  7117. } while (!chunk.lines);
  7118. for (var i = 0; i < chunk.lines.length; ++i) {
  7119. var line = chunk.lines[i], lh = line.height;
  7120. if (h < lh) break;
  7121. h -= lh;
  7122. }
  7123. return n + i;
  7124. }
  7125. // Find the height above the given line.
  7126. function heightAtLine(lineObj) {
  7127. lineObj = visualLine(lineObj);
  7128. var h = 0, chunk = lineObj.parent;
  7129. for (var i = 0; i < chunk.lines.length; ++i) {
  7130. var line = chunk.lines[i];
  7131. if (line == lineObj) break;
  7132. else h += line.height;
  7133. }
  7134. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  7135. for (var i = 0; i < p.children.length; ++i) {
  7136. var cur = p.children[i];
  7137. if (cur == chunk) break;
  7138. else h += cur.height;
  7139. }
  7140. }
  7141. return h;
  7142. }
  7143. // Get the bidi ordering for the given line (and cache it). Returns
  7144. // false for lines that are fully left-to-right, and an array of
  7145. // BidiSpan objects otherwise.
  7146. function getOrder(line) {
  7147. var order = line.order;
  7148. if (order == null) order = line.order = bidiOrdering(line.text);
  7149. return order;
  7150. }
  7151. // HISTORY
  7152. function History(startGen) {
  7153. // Arrays of change events and selections. Doing something adds an
  7154. // event to done and clears undo. Undoing moves events from done
  7155. // to undone, redoing moves them in the other direction.
  7156. this.done = []; this.undone = [];
  7157. this.undoDepth = Infinity;
  7158. // Used to track when changes can be merged into a single undo
  7159. // event
  7160. this.lastModTime = this.lastSelTime = 0;
  7161. this.lastOp = this.lastSelOp = null;
  7162. this.lastOrigin = this.lastSelOrigin = null;
  7163. // Used by the isClean() method
  7164. this.generation = this.maxGeneration = startGen || 1;
  7165. }
  7166. // Create a history change event from an updateDoc-style change
  7167. // object.
  7168. function historyChangeFromChange(doc, change) {
  7169. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  7170. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  7171. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  7172. return histChange;
  7173. }
  7174. // Pop all selection events off the end of a history array. Stop at
  7175. // a change event.
  7176. function clearSelectionEvents(array) {
  7177. while (array.length) {
  7178. var last = lst(array);
  7179. if (last.ranges) array.pop();
  7180. else break;
  7181. }
  7182. }
  7183. // Find the top change event in the history. Pop off selection
  7184. // events that are in the way.
  7185. function lastChangeEvent(hist, force) {
  7186. if (force) {
  7187. clearSelectionEvents(hist.done);
  7188. return lst(hist.done);
  7189. } else if (hist.done.length && !lst(hist.done).ranges) {
  7190. return lst(hist.done);
  7191. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  7192. hist.done.pop();
  7193. return lst(hist.done);
  7194. }
  7195. }
  7196. // Register a change in the history. Merges changes that are within
  7197. // a single operation, ore are close together with an origin that
  7198. // allows merging (starting with "+") into a single event.
  7199. function addChangeToHistory(doc, change, selAfter, opId) {
  7200. var hist = doc.history;
  7201. hist.undone.length = 0;
  7202. var time = +new Date, cur;
  7203. if ((hist.lastOp == opId ||
  7204. hist.lastOrigin == change.origin && change.origin &&
  7205. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  7206. change.origin.charAt(0) == "*")) &&
  7207. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  7208. // Merge this change into the last event
  7209. var last = lst(cur.changes);
  7210. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  7211. // Optimized case for simple insertion -- don't want to add
  7212. // new changesets for every character typed
  7213. last.to = changeEnd(change);
  7214. } else {
  7215. // Add new sub-event
  7216. cur.changes.push(historyChangeFromChange(doc, change));
  7217. }
  7218. } else {
  7219. // Can not be merged, start a new event.
  7220. var before = lst(hist.done);
  7221. if (!before || !before.ranges)
  7222. pushSelectionToHistory(doc.sel, hist.done);
  7223. cur = {changes: [historyChangeFromChange(doc, change)],
  7224. generation: hist.generation};
  7225. hist.done.push(cur);
  7226. while (hist.done.length > hist.undoDepth) {
  7227. hist.done.shift();
  7228. if (!hist.done[0].ranges) hist.done.shift();
  7229. }
  7230. }
  7231. hist.done.push(selAfter);
  7232. hist.generation = ++hist.maxGeneration;
  7233. hist.lastModTime = hist.lastSelTime = time;
  7234. hist.lastOp = hist.lastSelOp = opId;
  7235. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  7236. if (!last) signal(doc, "historyAdded");
  7237. }
  7238. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  7239. var ch = origin.charAt(0);
  7240. return ch == "*" ||
  7241. ch == "+" &&
  7242. prev.ranges.length == sel.ranges.length &&
  7243. prev.somethingSelected() == sel.somethingSelected() &&
  7244. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  7245. }
  7246. // Called whenever the selection changes, sets the new selection as
  7247. // the pending selection in the history, and pushes the old pending
  7248. // selection into the 'done' array when it was significantly
  7249. // different (in number of selected ranges, emptiness, or time).
  7250. function addSelectionToHistory(doc, sel, opId, options) {
  7251. var hist = doc.history, origin = options && options.origin;
  7252. // A new event is started when the previous origin does not match
  7253. // the current, or the origins don't allow matching. Origins
  7254. // starting with * are always merged, those starting with + are
  7255. // merged when similar and close together in time.
  7256. if (opId == hist.lastSelOp ||
  7257. (origin && hist.lastSelOrigin == origin &&
  7258. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  7259. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  7260. hist.done[hist.done.length - 1] = sel;
  7261. else
  7262. pushSelectionToHistory(sel, hist.done);
  7263. hist.lastSelTime = +new Date;
  7264. hist.lastSelOrigin = origin;
  7265. hist.lastSelOp = opId;
  7266. if (options && options.clearRedo !== false)
  7267. clearSelectionEvents(hist.undone);
  7268. }
  7269. function pushSelectionToHistory(sel, dest) {
  7270. var top = lst(dest);
  7271. if (!(top && top.ranges && top.equals(sel)))
  7272. dest.push(sel);
  7273. }
  7274. // Used to store marked span information in the history.
  7275. function attachLocalSpans(doc, change, from, to) {
  7276. var existing = change["spans_" + doc.id], n = 0;
  7277. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  7278. if (line.markedSpans)
  7279. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  7280. ++n;
  7281. });
  7282. }
  7283. // When un/re-doing restores text containing marked spans, those
  7284. // that have been explicitly cleared should not be restored.
  7285. function removeClearedSpans(spans) {
  7286. if (!spans) return null;
  7287. for (var i = 0, out; i < spans.length; ++i) {
  7288. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  7289. else if (out) out.push(spans[i]);
  7290. }
  7291. return !out ? spans : out.length ? out : null;
  7292. }
  7293. // Retrieve and filter the old marked spans stored in a change event.
  7294. function getOldSpans(doc, change) {
  7295. var found = change["spans_" + doc.id];
  7296. if (!found) return null;
  7297. for (var i = 0, nw = []; i < change.text.length; ++i)
  7298. nw.push(removeClearedSpans(found[i]));
  7299. return nw;
  7300. }
  7301. // Used both to provide a JSON-safe object in .getHistory, and, when
  7302. // detaching a document, to split the history in two
  7303. function copyHistoryArray(events, newGroup, instantiateSel) {
  7304. for (var i = 0, copy = []; i < events.length; ++i) {
  7305. var event = events[i];
  7306. if (event.ranges) {
  7307. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  7308. continue;
  7309. }
  7310. var changes = event.changes, newChanges = [];
  7311. copy.push({changes: newChanges});
  7312. for (var j = 0; j < changes.length; ++j) {
  7313. var change = changes[j], m;
  7314. newChanges.push({from: change.from, to: change.to, text: change.text});
  7315. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  7316. if (indexOf(newGroup, Number(m[1])) > -1) {
  7317. lst(newChanges)[prop] = change[prop];
  7318. delete change[prop];
  7319. }
  7320. }
  7321. }
  7322. }
  7323. return copy;
  7324. }
  7325. // Rebasing/resetting history to deal with externally-sourced changes
  7326. function rebaseHistSelSingle(pos, from, to, diff) {
  7327. if (to < pos.line) {
  7328. pos.line += diff;
  7329. } else if (from < pos.line) {
  7330. pos.line = from;
  7331. pos.ch = 0;
  7332. }
  7333. }
  7334. // Tries to rebase an array of history events given a change in the
  7335. // document. If the change touches the same lines as the event, the
  7336. // event, and everything 'behind' it, is discarded. If the change is
  7337. // before the event, the event's positions are updated. Uses a
  7338. // copy-on-write scheme for the positions, to avoid having to
  7339. // reallocate them all on every rebase, but also avoid problems with
  7340. // shared position objects being unsafely updated.
  7341. function rebaseHistArray(array, from, to, diff) {
  7342. for (var i = 0; i < array.length; ++i) {
  7343. var sub = array[i], ok = true;
  7344. if (sub.ranges) {
  7345. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  7346. for (var j = 0; j < sub.ranges.length; j++) {
  7347. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  7348. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  7349. }
  7350. continue;
  7351. }
  7352. for (var j = 0; j < sub.changes.length; ++j) {
  7353. var cur = sub.changes[j];
  7354. if (to < cur.from.line) {
  7355. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  7356. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  7357. } else if (from <= cur.to.line) {
  7358. ok = false;
  7359. break;
  7360. }
  7361. }
  7362. if (!ok) {
  7363. array.splice(0, i + 1);
  7364. i = 0;
  7365. }
  7366. }
  7367. }
  7368. function rebaseHist(hist, change) {
  7369. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  7370. rebaseHistArray(hist.done, from, to, diff);
  7371. rebaseHistArray(hist.undone, from, to, diff);
  7372. }
  7373. // EVENT UTILITIES
  7374. // Due to the fact that we still support jurassic IE versions, some
  7375. // compatibility wrappers are needed.
  7376. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  7377. if (e.preventDefault) e.preventDefault();
  7378. else e.returnValue = false;
  7379. };
  7380. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  7381. if (e.stopPropagation) e.stopPropagation();
  7382. else e.cancelBubble = true;
  7383. };
  7384. function e_defaultPrevented(e) {
  7385. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  7386. }
  7387. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  7388. function e_target(e) {return e.target || e.srcElement;}
  7389. function e_button(e) {
  7390. var b = e.which;
  7391. if (b == null) {
  7392. if (e.button & 1) b = 1;
  7393. else if (e.button & 2) b = 3;
  7394. else if (e.button & 4) b = 2;
  7395. }
  7396. if (mac && e.ctrlKey && b == 1) b = 3;
  7397. return b;
  7398. }
  7399. // EVENT HANDLING
  7400. // Lightweight event framework. on/off also work on DOM nodes,
  7401. // registering native DOM handlers.
  7402. var on = CodeMirror.on = function(emitter, type, f) {
  7403. if (emitter.addEventListener)
  7404. emitter.addEventListener(type, f, false);
  7405. else if (emitter.attachEvent)
  7406. emitter.attachEvent("on" + type, f);
  7407. else {
  7408. var map = emitter._handlers || (emitter._handlers = {});
  7409. var arr = map[type] || (map[type] = []);
  7410. arr.push(f);
  7411. }
  7412. };
  7413. var noHandlers = []
  7414. function getHandlers(emitter, type, copy) {
  7415. var arr = emitter._handlers && emitter._handlers[type]
  7416. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  7417. else return arr || noHandlers
  7418. }
  7419. var off = CodeMirror.off = function(emitter, type, f) {
  7420. if (emitter.removeEventListener)
  7421. emitter.removeEventListener(type, f, false);
  7422. else if (emitter.detachEvent)
  7423. emitter.detachEvent("on" + type, f);
  7424. else {
  7425. var handlers = getHandlers(emitter, type, false)
  7426. for (var i = 0; i < handlers.length; ++i)
  7427. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  7428. }
  7429. };
  7430. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  7431. var handlers = getHandlers(emitter, type, true)
  7432. if (!handlers.length) return;
  7433. var args = Array.prototype.slice.call(arguments, 2);
  7434. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  7435. };
  7436. var orphanDelayedCallbacks = null;
  7437. // Often, we want to signal events at a point where we are in the
  7438. // middle of some work, but don't want the handler to start calling
  7439. // other methods on the editor, which might be in an inconsistent
  7440. // state or simply not expect any other events to happen.
  7441. // signalLater looks whether there are any handlers, and schedules
  7442. // them to be executed when the last operation ends, or, if no
  7443. // operation is active, when a timeout fires.
  7444. function signalLater(emitter, type /*, values...*/) {
  7445. var arr = getHandlers(emitter, type, false)
  7446. if (!arr.length) return;
  7447. var args = Array.prototype.slice.call(arguments, 2), list;
  7448. if (operationGroup) {
  7449. list = operationGroup.delayedCallbacks;
  7450. } else if (orphanDelayedCallbacks) {
  7451. list = orphanDelayedCallbacks;
  7452. } else {
  7453. list = orphanDelayedCallbacks = [];
  7454. setTimeout(fireOrphanDelayed, 0);
  7455. }
  7456. function bnd(f) {return function(){f.apply(null, args);};};
  7457. for (var i = 0; i < arr.length; ++i)
  7458. list.push(bnd(arr[i]));
  7459. }
  7460. function fireOrphanDelayed() {
  7461. var delayed = orphanDelayedCallbacks;
  7462. orphanDelayedCallbacks = null;
  7463. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  7464. }
  7465. // The DOM events that CodeMirror handles can be overridden by
  7466. // registering a (non-DOM) handler on the editor for the event name,
  7467. // and preventDefault-ing the event in that handler.
  7468. function signalDOMEvent(cm, e, override) {
  7469. if (typeof e == "string")
  7470. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  7471. signal(cm, override || e.type, cm, e);
  7472. return e_defaultPrevented(e) || e.codemirrorIgnore;
  7473. }
  7474. function signalCursorActivity(cm) {
  7475. var arr = cm._handlers && cm._handlers.cursorActivity;
  7476. if (!arr) return;
  7477. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7478. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  7479. set.push(arr[i]);
  7480. }
  7481. function hasHandler(emitter, type) {
  7482. return getHandlers(emitter, type).length > 0
  7483. }
  7484. // Add on and off methods to a constructor's prototype, to make
  7485. // registering events on such objects more convenient.
  7486. function eventMixin(ctor) {
  7487. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7488. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7489. }
  7490. // MISC UTILITIES
  7491. // Number of pixels added to scroller and sizer to hide scrollbar
  7492. var scrollerGap = 30;
  7493. // Returned or thrown by various protocols to signal 'I'm not
  7494. // handling this'.
  7495. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  7496. // Reused option objects for setSelection & friends
  7497. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  7498. function Delayed() {this.id = null;}
  7499. Delayed.prototype.set = function(ms, f) {
  7500. clearTimeout(this.id);
  7501. this.id = setTimeout(f, ms);
  7502. };
  7503. // Counts the column offset in a string, taking tabs into account.
  7504. // Used mostly to find indentation.
  7505. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  7506. if (end == null) {
  7507. end = string.search(/[^\s\u00a0]/);
  7508. if (end == -1) end = string.length;
  7509. }
  7510. for (var i = startIndex || 0, n = startValue || 0;;) {
  7511. var nextTab = string.indexOf("\t", i);
  7512. if (nextTab < 0 || nextTab >= end)
  7513. return n + (end - i);
  7514. n += nextTab - i;
  7515. n += tabSize - (n % tabSize);
  7516. i = nextTab + 1;
  7517. }
  7518. };
  7519. // The inverse of countColumn -- find the offset that corresponds to
  7520. // a particular column.
  7521. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  7522. for (var pos = 0, col = 0;;) {
  7523. var nextTab = string.indexOf("\t", pos);
  7524. if (nextTab == -1) nextTab = string.length;
  7525. var skipped = nextTab - pos;
  7526. if (nextTab == string.length || col + skipped >= goal)
  7527. return pos + Math.min(skipped, goal - col);
  7528. col += nextTab - pos;
  7529. col += tabSize - (col % tabSize);
  7530. pos = nextTab + 1;
  7531. if (col >= goal) return pos;
  7532. }
  7533. }
  7534. var spaceStrs = [""];
  7535. function spaceStr(n) {
  7536. while (spaceStrs.length <= n)
  7537. spaceStrs.push(lst(spaceStrs) + " ");
  7538. return spaceStrs[n];
  7539. }
  7540. function lst(arr) { return arr[arr.length-1]; }
  7541. var selectInput = function(node) { node.select(); };
  7542. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  7543. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  7544. else if (ie) // Suppress mysterious IE10 errors
  7545. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  7546. function indexOf(array, elt) {
  7547. for (var i = 0; i < array.length; ++i)
  7548. if (array[i] == elt) return i;
  7549. return -1;
  7550. }
  7551. function map(array, f) {
  7552. var out = [];
  7553. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  7554. return out;
  7555. }
  7556. function nothing() {}
  7557. function createObj(base, props) {
  7558. var inst;
  7559. if (Object.create) {
  7560. inst = Object.create(base);
  7561. } else {
  7562. nothing.prototype = base;
  7563. inst = new nothing();
  7564. }
  7565. if (props) copyObj(props, inst);
  7566. return inst;
  7567. };
  7568. function copyObj(obj, target, overwrite) {
  7569. if (!target) target = {};
  7570. for (var prop in obj)
  7571. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  7572. target[prop] = obj[prop];
  7573. return target;
  7574. }
  7575. function bind(f) {
  7576. var args = Array.prototype.slice.call(arguments, 1);
  7577. return function(){return f.apply(null, args);};
  7578. }
  7579. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  7580. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  7581. return /\w/.test(ch) || ch > "\x80" &&
  7582. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  7583. };
  7584. function isWordChar(ch, helper) {
  7585. if (!helper) return isWordCharBasic(ch);
  7586. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  7587. return helper.test(ch);
  7588. }
  7589. function isEmpty(obj) {
  7590. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  7591. return true;
  7592. }
  7593. // Extending unicode characters. A series of a non-extending char +
  7594. // any number of extending chars is treated as a single unit as far
  7595. // as editing and measuring is concerned. This is not fully correct,
  7596. // since some scripts/fonts/browsers also treat other configurations
  7597. // of code points as a group.
  7598. 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]/;
  7599. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  7600. // DOM UTILITIES
  7601. function elt(tag, content, className, style) {
  7602. var e = document.createElement(tag);
  7603. if (className) e.className = className;
  7604. if (style) e.style.cssText = style;
  7605. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  7606. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  7607. return e;
  7608. }
  7609. var range;
  7610. if (document.createRange) range = function(node, start, end, endNode) {
  7611. var r = document.createRange();
  7612. r.setEnd(endNode || node, end);
  7613. r.setStart(node, start);
  7614. return r;
  7615. };
  7616. else range = function(node, start, end) {
  7617. var r = document.body.createTextRange();
  7618. try { r.moveToElementText(node.parentNode); }
  7619. catch(e) { return r; }
  7620. r.collapse(true);
  7621. r.moveEnd("character", end);
  7622. r.moveStart("character", start);
  7623. return r;
  7624. };
  7625. function removeChildren(e) {
  7626. for (var count = e.childNodes.length; count > 0; --count)
  7627. e.removeChild(e.firstChild);
  7628. return e;
  7629. }
  7630. function removeChildrenAndAdd(parent, e) {
  7631. return removeChildren(parent).appendChild(e);
  7632. }
  7633. var contains = CodeMirror.contains = function(parent, child) {
  7634. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  7635. child = child.parentNode;
  7636. if (parent.contains)
  7637. return parent.contains(child);
  7638. do {
  7639. if (child.nodeType == 11) child = child.host;
  7640. if (child == parent) return true;
  7641. } while (child = child.parentNode);
  7642. };
  7643. function activeElt() {
  7644. var activeElement = document.activeElement;
  7645. while (activeElement && activeElement.root && activeElement.root.activeElement)
  7646. activeElement = activeElement.root.activeElement;
  7647. return activeElement;
  7648. }
  7649. // Older versions of IE throws unspecified error when touching
  7650. // document.activeElement in some cases (during loading, in iframe)
  7651. if (ie && ie_version < 11) activeElt = function() {
  7652. try { return document.activeElement; }
  7653. catch(e) { return document.body; }
  7654. };
  7655. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  7656. var rmClass = CodeMirror.rmClass = function(node, cls) {
  7657. var current = node.className;
  7658. var match = classTest(cls).exec(current);
  7659. if (match) {
  7660. var after = current.slice(match.index + match[0].length);
  7661. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  7662. }
  7663. };
  7664. var addClass = CodeMirror.addClass = function(node, cls) {
  7665. var current = node.className;
  7666. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  7667. };
  7668. function joinClasses(a, b) {
  7669. var as = a.split(" ");
  7670. for (var i = 0; i < as.length; i++)
  7671. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  7672. return b;
  7673. }
  7674. // WINDOW-WIDE EVENTS
  7675. // These must be handled carefully, because naively registering a
  7676. // handler for each editor will cause the editors to never be
  7677. // garbage collected.
  7678. function forEachCodeMirror(f) {
  7679. if (!document.body.getElementsByClassName) return;
  7680. var byClass = document.body.getElementsByClassName("CodeMirror");
  7681. for (var i = 0; i < byClass.length; i++) {
  7682. var cm = byClass[i].CodeMirror;
  7683. if (cm) f(cm);
  7684. }
  7685. }
  7686. var globalsRegistered = false;
  7687. function ensureGlobalHandlers() {
  7688. if (globalsRegistered) return;
  7689. registerGlobalHandlers();
  7690. globalsRegistered = true;
  7691. }
  7692. function registerGlobalHandlers() {
  7693. // When the window resizes, we need to refresh active editors.
  7694. var resizeTimer;
  7695. on(window, "resize", function() {
  7696. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  7697. resizeTimer = null;
  7698. forEachCodeMirror(onResize);
  7699. }, 100);
  7700. });
  7701. // When the window loses focus, we want to show the editor as blurred
  7702. on(window, "blur", function() {
  7703. forEachCodeMirror(onBlur);
  7704. });
  7705. }
  7706. // FEATURE DETECTION
  7707. // Detect drag-and-drop
  7708. var dragAndDrop = function() {
  7709. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7710. // couldn't get it to work yet.
  7711. if (ie && ie_version < 9) return false;
  7712. var div = elt('div');
  7713. return "draggable" in div || "dragDrop" in div;
  7714. }();
  7715. var zwspSupported;
  7716. function zeroWidthElement(measure) {
  7717. if (zwspSupported == null) {
  7718. var test = elt("span", "\u200b");
  7719. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7720. if (measure.firstChild.offsetHeight != 0)
  7721. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  7722. }
  7723. var node = zwspSupported ? elt("span", "\u200b") :
  7724. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7725. node.setAttribute("cm-text", "");
  7726. return node;
  7727. }
  7728. // Feature-detect IE's crummy client rect reporting for bidi text
  7729. var badBidiRects;
  7730. function hasBadBidiRects(measure) {
  7731. if (badBidiRects != null) return badBidiRects;
  7732. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7733. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7734. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  7735. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7736. return badBidiRects = (r1.right - r0.right < 3);
  7737. }
  7738. // See if "".split is the broken IE version, if so, provide an
  7739. // alternative way to split lines.
  7740. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  7741. var pos = 0, result = [], l = string.length;
  7742. while (pos <= l) {
  7743. var nl = string.indexOf("\n", pos);
  7744. if (nl == -1) nl = string.length;
  7745. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7746. var rt = line.indexOf("\r");
  7747. if (rt != -1) {
  7748. result.push(line.slice(0, rt));
  7749. pos += rt + 1;
  7750. } else {
  7751. result.push(line);
  7752. pos = nl + 1;
  7753. }
  7754. }
  7755. return result;
  7756. } : function(string){return string.split(/\r\n?|\n/);};
  7757. var hasSelection = window.getSelection ? function(te) {
  7758. try { return te.selectionStart != te.selectionEnd; }
  7759. catch(e) { return false; }
  7760. } : function(te) {
  7761. try {var range = te.ownerDocument.selection.createRange();}
  7762. catch(e) {}
  7763. if (!range || range.parentElement() != te) return false;
  7764. return range.compareEndPoints("StartToEnd", range) != 0;
  7765. };
  7766. var hasCopyEvent = (function() {
  7767. var e = elt("div");
  7768. if ("oncopy" in e) return true;
  7769. e.setAttribute("oncopy", "return;");
  7770. return typeof e.oncopy == "function";
  7771. })();
  7772. var badZoomedRects = null;
  7773. function hasBadZoomedRects(measure) {
  7774. if (badZoomedRects != null) return badZoomedRects;
  7775. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7776. var normal = node.getBoundingClientRect();
  7777. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7778. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  7779. }
  7780. // KEY NAMES
  7781. var keyNames = CodeMirror.keyNames = {
  7782. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7783. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7784. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7785. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7786. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7787. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7788. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7789. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7790. };
  7791. (function() {
  7792. // Number keys
  7793. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  7794. // Alphabetic keys
  7795. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  7796. // Function keys
  7797. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  7798. })();
  7799. // BIDI HELPERS
  7800. function iterateBidiSections(order, from, to, f) {
  7801. if (!order) return f(from, to, "ltr");
  7802. var found = false;
  7803. for (var i = 0; i < order.length; ++i) {
  7804. var part = order[i];
  7805. if (part.from < to && part.to > from || from == to && part.to == from) {
  7806. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  7807. found = true;
  7808. }
  7809. }
  7810. if (!found) f(from, to, "ltr");
  7811. }
  7812. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  7813. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  7814. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  7815. function lineRight(line) {
  7816. var order = getOrder(line);
  7817. if (!order) return line.text.length;
  7818. return bidiRight(lst(order));
  7819. }
  7820. function lineStart(cm, lineN) {
  7821. var line = getLine(cm.doc, lineN);
  7822. var visual = visualLine(line);
  7823. if (visual != line) lineN = lineNo(visual);
  7824. var order = getOrder(visual);
  7825. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  7826. return Pos(lineN, ch);
  7827. }
  7828. function lineEnd(cm, lineN) {
  7829. var merged, line = getLine(cm.doc, lineN);
  7830. while (merged = collapsedSpanAtEnd(line)) {
  7831. line = merged.find(1, true).line;
  7832. lineN = null;
  7833. }
  7834. var order = getOrder(line);
  7835. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  7836. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  7837. }
  7838. function lineStartSmart(cm, pos) {
  7839. var start = lineStart(cm, pos.line);
  7840. var line = getLine(cm.doc, start.line);
  7841. var order = getOrder(line);
  7842. if (!order || order[0].level == 0) {
  7843. var firstNonWS = Math.max(0, line.text.search(/\S/));
  7844. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  7845. return Pos(start.line, inWS ? 0 : firstNonWS);
  7846. }
  7847. return start;
  7848. }
  7849. function compareBidiLevel(order, a, b) {
  7850. var linedir = order[0].level;
  7851. if (a == linedir) return true;
  7852. if (b == linedir) return false;
  7853. return a < b;
  7854. }
  7855. var bidiOther;
  7856. function getBidiPartAt(order, pos) {
  7857. bidiOther = null;
  7858. for (var i = 0, found; i < order.length; ++i) {
  7859. var cur = order[i];
  7860. if (cur.from < pos && cur.to > pos) return i;
  7861. if ((cur.from == pos || cur.to == pos)) {
  7862. if (found == null) {
  7863. found = i;
  7864. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  7865. if (cur.from != cur.to) bidiOther = found;
  7866. return i;
  7867. } else {
  7868. if (cur.from != cur.to) bidiOther = i;
  7869. return found;
  7870. }
  7871. }
  7872. }
  7873. return found;
  7874. }
  7875. function moveInLine(line, pos, dir, byUnit) {
  7876. if (!byUnit) return pos + dir;
  7877. do pos += dir;
  7878. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  7879. return pos;
  7880. }
  7881. // This is needed in order to move 'visually' through bi-directional
  7882. // text -- i.e., pressing left should make the cursor go left, even
  7883. // when in RTL text. The tricky part is the 'jumps', where RTL and
  7884. // LTR text touch each other. This often requires the cursor offset
  7885. // to move more than one unit, in order to visually move one unit.
  7886. function moveVisually(line, start, dir, byUnit) {
  7887. var bidi = getOrder(line);
  7888. if (!bidi) return moveLogically(line, start, dir, byUnit);
  7889. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  7890. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  7891. for (;;) {
  7892. if (target > part.from && target < part.to) return target;
  7893. if (target == part.from || target == part.to) {
  7894. if (getBidiPartAt(bidi, target) == pos) return target;
  7895. part = bidi[pos += dir];
  7896. return (dir > 0) == part.level % 2 ? part.to : part.from;
  7897. } else {
  7898. part = bidi[pos += dir];
  7899. if (!part) return null;
  7900. if ((dir > 0) == part.level % 2)
  7901. target = moveInLine(line, part.to, -1, byUnit);
  7902. else
  7903. target = moveInLine(line, part.from, 1, byUnit);
  7904. }
  7905. }
  7906. }
  7907. function moveLogically(line, start, dir, byUnit) {
  7908. var target = start + dir;
  7909. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  7910. return target < 0 || target > line.text.length ? null : target;
  7911. }
  7912. // Bidirectional ordering algorithm
  7913. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  7914. // that this (partially) implements.
  7915. // One-char codes used for character types:
  7916. // L (L): Left-to-Right
  7917. // R (R): Right-to-Left
  7918. // r (AL): Right-to-Left Arabic
  7919. // 1 (EN): European Number
  7920. // + (ES): European Number Separator
  7921. // % (ET): European Number Terminator
  7922. // n (AN): Arabic Number
  7923. // , (CS): Common Number Separator
  7924. // m (NSM): Non-Spacing Mark
  7925. // b (BN): Boundary Neutral
  7926. // s (B): Paragraph Separator
  7927. // t (S): Segment Separator
  7928. // w (WS): Whitespace
  7929. // N (ON): Other Neutrals
  7930. // Returns null if characters are ordered as they appear
  7931. // (left-to-right), or an array of sections ({from, to, level}
  7932. // objects) in the order in which they occur visually.
  7933. var bidiOrdering = (function() {
  7934. // Character types for codepoints 0 to 0xff
  7935. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  7936. // Character types for codepoints 0x600 to 0x6ff
  7937. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  7938. function charType(code) {
  7939. if (code <= 0xf7) return lowTypes.charAt(code);
  7940. else if (0x590 <= code && code <= 0x5f4) return "R";
  7941. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  7942. else if (0x6ee <= code && code <= 0x8ac) return "r";
  7943. else if (0x2000 <= code && code <= 0x200b) return "w";
  7944. else if (code == 0x200c) return "b";
  7945. else return "L";
  7946. }
  7947. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  7948. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  7949. // Browsers seem to always treat the boundaries of block elements as being L.
  7950. var outerType = "L";
  7951. function BidiSpan(level, from, to) {
  7952. this.level = level;
  7953. this.from = from; this.to = to;
  7954. }
  7955. return function(str) {
  7956. if (!bidiRE.test(str)) return false;
  7957. var len = str.length, types = [];
  7958. for (var i = 0, type; i < len; ++i)
  7959. types.push(type = charType(str.charCodeAt(i)));
  7960. // W1. Examine each non-spacing mark (NSM) in the level run, and
  7961. // change the type of the NSM to the type of the previous
  7962. // character. If the NSM is at the start of the level run, it will
  7963. // get the type of sor.
  7964. for (var i = 0, prev = outerType; i < len; ++i) {
  7965. var type = types[i];
  7966. if (type == "m") types[i] = prev;
  7967. else prev = type;
  7968. }
  7969. // W2. Search backwards from each instance of a European number
  7970. // until the first strong type (R, L, AL, or sor) is found. If an
  7971. // AL is found, change the type of the European number to Arabic
  7972. // number.
  7973. // W3. Change all ALs to R.
  7974. for (var i = 0, cur = outerType; i < len; ++i) {
  7975. var type = types[i];
  7976. if (type == "1" && cur == "r") types[i] = "n";
  7977. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  7978. }
  7979. // W4. A single European separator between two European numbers
  7980. // changes to a European number. A single common separator between
  7981. // two numbers of the same type changes to that type.
  7982. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  7983. var type = types[i];
  7984. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  7985. else if (type == "," && prev == types[i+1] &&
  7986. (prev == "1" || prev == "n")) types[i] = prev;
  7987. prev = type;
  7988. }
  7989. // W5. A sequence of European terminators adjacent to European
  7990. // numbers changes to all European numbers.
  7991. // W6. Otherwise, separators and terminators change to Other
  7992. // Neutral.
  7993. for (var i = 0; i < len; ++i) {
  7994. var type = types[i];
  7995. if (type == ",") types[i] = "N";
  7996. else if (type == "%") {
  7997. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  7998. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  7999. for (var j = i; j < end; ++j) types[j] = replace;
  8000. i = end - 1;
  8001. }
  8002. }
  8003. // W7. Search backwards from each instance of a European number
  8004. // until the first strong type (R, L, or sor) is found. If an L is
  8005. // found, then change the type of the European number to L.
  8006. for (var i = 0, cur = outerType; i < len; ++i) {
  8007. var type = types[i];
  8008. if (cur == "L" && type == "1") types[i] = "L";
  8009. else if (isStrong.test(type)) cur = type;
  8010. }
  8011. // N1. A sequence of neutrals takes the direction of the
  8012. // surrounding strong text if the text on both sides has the same
  8013. // direction. European and Arabic numbers act as if they were R in
  8014. // terms of their influence on neutrals. Start-of-level-run (sor)
  8015. // and end-of-level-run (eor) are used at level run boundaries.
  8016. // N2. Any remaining neutrals take the embedding direction.
  8017. for (var i = 0; i < len; ++i) {
  8018. if (isNeutral.test(types[i])) {
  8019. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  8020. var before = (i ? types[i-1] : outerType) == "L";
  8021. var after = (end < len ? types[end] : outerType) == "L";
  8022. var replace = before || after ? "L" : "R";
  8023. for (var j = i; j < end; ++j) types[j] = replace;
  8024. i = end - 1;
  8025. }
  8026. }
  8027. // Here we depart from the documented algorithm, in order to avoid
  8028. // building up an actual levels array. Since there are only three
  8029. // levels (0, 1, 2) in an implementation that doesn't take
  8030. // explicit embedding into account, we can build up the order on
  8031. // the fly, without following the level-based algorithm.
  8032. var order = [], m;
  8033. for (var i = 0; i < len;) {
  8034. if (countsAsLeft.test(types[i])) {
  8035. var start = i;
  8036. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  8037. order.push(new BidiSpan(0, start, i));
  8038. } else {
  8039. var pos = i, at = order.length;
  8040. for (++i; i < len && types[i] != "L"; ++i) {}
  8041. for (var j = pos; j < i;) {
  8042. if (countsAsNum.test(types[j])) {
  8043. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  8044. var nstart = j;
  8045. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  8046. order.splice(at, 0, new BidiSpan(2, nstart, j));
  8047. pos = j;
  8048. } else ++j;
  8049. }
  8050. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  8051. }
  8052. }
  8053. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  8054. order[0].from = m[0].length;
  8055. order.unshift(new BidiSpan(0, 0, m[0].length));
  8056. }
  8057. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  8058. lst(order).to -= m[0].length;
  8059. order.push(new BidiSpan(0, len - m[0].length, len));
  8060. }
  8061. if (order[0].level == 2)
  8062. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  8063. if (order[0].level != lst(order).level)
  8064. order.push(new BidiSpan(order[0].level, len, len));
  8065. return order;
  8066. };
  8067. })();
  8068. // THE END
  8069. CodeMirror.version = "5.15.3";
  8070. return CodeMirror;
  8071. });