codemirror.js 294 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526
  1. // This is CodeMirror (http://codemirror.net), a code editor
  2. // implemented in JavaScript on top of the browser's DOM.
  3. //
  4. // You can find some technical background for some of the code below
  5. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  6. (function(mod) {
  7. if (typeof exports == "object" && typeof module == "object") // CommonJS
  8. module.exports = mod();
  9. else if (typeof define == "function" && define.amd) // AMD
  10. return define([], mod);
  11. else // Plain browser env
  12. this.CodeMirror = mod();
  13. })(function() {
  14. "use strict";
  15. // BROWSER SNIFFING
  16. // Kludges for bugs and behavior differences that can't be feature
  17. // detected are enabled based on userAgent etc sniffing.
  18. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  19. // ie_uptoN means Internet Explorer version N or lower
  20. var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
  21. var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8);
  22. var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9);
  23. var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10);
  24. var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
  25. var ie = ie_upto10 || ie_11up;
  26. var webkit = /WebKit\//.test(navigator.userAgent);
  27. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  28. var chrome = /Chrome\//.test(navigator.userAgent);
  29. var presto = /Opera\//.test(navigator.userAgent);
  30. var safari = /Apple Computer/.test(navigator.vendor);
  31. var khtml = /KHTML\//.test(navigator.userAgent);
  32. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  33. var phantom = /PhantomJS/.test(navigator.userAgent);
  34. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.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(navigator.userAgent);
  37. var mac = ios || /Mac/.test(navigator.platform);
  38. var windows = /win/i.test(navigator.platform);
  39. var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  40. if (presto_version) presto_version = Number(presto_version[1]);
  41. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  42. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  43. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  44. var captureRightClick = gecko || (ie && !ie_upto8);
  45. // Optimize some code when these features are not used.
  46. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  47. // EDITOR CONSTRUCTOR
  48. // A CodeMirror instance represents an editor. This is the object
  49. // that user code is usually dealing with.
  50. function CodeMirror(place, options) {
  51. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  52. this.options = options = options || {};
  53. // Determine effective options based on given values and defaults.
  54. copyObj(defaults, options, false);
  55. setGuttersForLineNumbers(options);
  56. var doc = options.value;
  57. if (typeof doc == "string") doc = new Doc(doc, options.mode);
  58. this.doc = doc;
  59. var display = this.display = new Display(place, doc);
  60. display.wrapper.CodeMirror = this;
  61. updateGutters(this);
  62. themeChanged(this);
  63. if (options.lineWrapping)
  64. this.display.wrapper.className += " CodeMirror-wrap";
  65. if (options.autofocus && !mobile) focusInput(this);
  66. this.state = {
  67. keyMaps: [], // stores maps added by addKeyMap
  68. overlays: [], // highlighting overlays, as added by addOverlay
  69. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  70. overwrite: false, focused: false,
  71. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  72. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
  73. draggingText: false,
  74. highlight: new Delayed() // stores highlight worker timeout
  75. };
  76. // Override magic textarea content restore that IE sometimes does
  77. // on our hidden textarea on reload
  78. if (ie_upto10) setTimeout(bind(resetInput, this, true), 20);
  79. registerEventHandlers(this);
  80. var cm = this;
  81. runInOp(this, function() {
  82. cm.curOp.forceUpdate = true;
  83. attachDoc(cm, doc);
  84. if ((options.autofocus && !mobile) || activeElt() == display.input)
  85. setTimeout(bind(onFocus, cm), 20);
  86. else
  87. onBlur(cm);
  88. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  89. optionHandlers[opt](cm, options[opt], Init);
  90. for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);
  91. });
  92. }
  93. // DISPLAY CONSTRUCTOR
  94. // The display handles the DOM integration, both for input reading
  95. // and content drawing. It holds references to DOM nodes and
  96. // display-related state.
  97. function Display(place, doc) {
  98. var d = this;
  99. // The semihidden textarea that is focused when the editor is
  100. // focused, and receives input.
  101. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  102. // The textarea is kept positioned near the cursor to prevent the
  103. // fact that it'll be scrolled into view on input from scrolling
  104. // our fake cursor out of view. On webkit, when wrap=off, paste is
  105. // very slow. So make the area wide instead.
  106. if (webkit) input.style.width = "1000px";
  107. else input.setAttribute("wrap", "off");
  108. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  109. if (ios) input.style.border = "1px solid black";
  110. input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
  111. // Wraps and hides input textarea
  112. d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  113. // The fake scrollbar elements.
  114. d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  115. d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  116. // Covers bottom-right square when both scrollbars are present.
  117. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  118. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  119. // and h scrollbar is present.
  120. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  121. // Will contain the actual code, positioned to cover the viewport.
  122. d.lineDiv = elt("div", null, "CodeMirror-code");
  123. // Elements are added to these to represent selection and cursors.
  124. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  125. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  126. // A visibility: hidden element used to find the size of things.
  127. d.measure = elt("div", null, "CodeMirror-measure");
  128. // When lines outside of the viewport are measured, they are drawn in this.
  129. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  130. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  131. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  132. null, "position: relative; outline: none");
  133. // Moved around its parent to cover visible view.
  134. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  135. // Set to the height of the document, allowing scrolling.
  136. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  137. // Behavior of elts with overflow: auto and padding is
  138. // inconsistent across browsers. This is used to ensure the
  139. // scrollable area is big enough.
  140. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
  141. // Will contain the gutters, if any.
  142. d.gutters = elt("div", null, "CodeMirror-gutters");
  143. d.lineGutter = null;
  144. // Actual scrollable element.
  145. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  146. d.scroller.setAttribute("tabIndex", "-1");
  147. // The element in which the editor lives.
  148. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
  149. d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  150. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  151. if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  152. // Needed to hide big blue blinking cursor on Mobile Safari
  153. if (ios) input.style.width = "0px";
  154. if (!webkit) d.scroller.draggable = true;
  155. // Needed to handle Tab key in KHTML
  156. if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
  157. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  158. if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px";
  159. if (place.appendChild) place.appendChild(d.wrapper);
  160. else place(d.wrapper);
  161. // Current rendered range (may be bigger than the view window).
  162. d.viewFrom = d.viewTo = doc.first;
  163. // Information about the rendered lines.
  164. d.view = [];
  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.lastSizeC = 0;
  171. d.updateLineNumbers = null;
  172. // Used to only resize the line number gutter when necessary (when
  173. // the amount of lines crosses a boundary that makes its width change)
  174. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  175. // See readInput and resetInput
  176. d.prevInput = "";
  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. // Flag that indicates whether we expect input to appear real soon
  182. // now (after some event like 'keypress' or 'input') and are
  183. // polling intensively.
  184. d.pollingFast = false;
  185. // Self-resetting timeout for the poller
  186. d.poll = new Delayed();
  187. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  188. // Tracks when resetInput has punted to just putting a short
  189. // string into the textarea instead of the full selection.
  190. d.inaccurateSelection = false;
  191. // Tracks the maximum line length so that the horizontal scrollbar
  192. // can be kept static when scrolling.
  193. d.maxLine = null;
  194. d.maxLineLength = 0;
  195. d.maxLineChanged = false;
  196. // Used for measuring wheel scrolling granularity
  197. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  198. // True when shift is held down.
  199. d.shift = false;
  200. }
  201. // STATE UPDATES
  202. // Used to get the editor into a consistent state again when options change.
  203. function loadMode(cm) {
  204. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  205. resetModeState(cm);
  206. }
  207. function resetModeState(cm) {
  208. cm.doc.iter(function(line) {
  209. if (line.stateAfter) line.stateAfter = null;
  210. if (line.styles) line.styles = null;
  211. });
  212. cm.doc.frontier = cm.doc.first;
  213. startWorker(cm, 100);
  214. cm.state.modeGen++;
  215. if (cm.curOp) regChange(cm);
  216. }
  217. function wrappingChanged(cm) {
  218. if (cm.options.lineWrapping) {
  219. addClass(cm.display.wrapper, "CodeMirror-wrap");
  220. cm.display.sizer.style.minWidth = "";
  221. } else {
  222. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  223. findMaxLine(cm);
  224. }
  225. estimateLineHeights(cm);
  226. regChange(cm);
  227. clearCaches(cm);
  228. setTimeout(function(){updateScrollbars(cm);}, 100);
  229. }
  230. // Returns a function that estimates the height of a line, to use as
  231. // first approximation until the line becomes visible (and is thus
  232. // properly measurable).
  233. function estimateHeight(cm) {
  234. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  235. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  236. return function(line) {
  237. if (lineIsHidden(cm.doc, line)) return 0;
  238. var widgetsHeight = 0;
  239. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  240. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  241. }
  242. if (wrapping)
  243. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  244. else
  245. return widgetsHeight + th;
  246. };
  247. }
  248. function estimateLineHeights(cm) {
  249. var doc = cm.doc, est = estimateHeight(cm);
  250. doc.iter(function(line) {
  251. var estHeight = est(line);
  252. if (estHeight != line.height) updateLineHeight(line, estHeight);
  253. });
  254. }
  255. function keyMapChanged(cm) {
  256. var map = keyMap[cm.options.keyMap], style = map.style;
  257. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
  258. (style ? " cm-keymap-" + style : "");
  259. }
  260. function themeChanged(cm) {
  261. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  262. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  263. clearCaches(cm);
  264. }
  265. function guttersChanged(cm) {
  266. updateGutters(cm);
  267. regChange(cm);
  268. setTimeout(function(){alignHorizontally(cm);}, 20);
  269. }
  270. // Rebuild the gutter elements, ensure the margin to the left of the
  271. // code matches their width.
  272. function updateGutters(cm) {
  273. var gutters = cm.display.gutters, specs = cm.options.gutters;
  274. removeChildren(gutters);
  275. for (var i = 0; i < specs.length; ++i) {
  276. var gutterClass = specs[i];
  277. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  278. if (gutterClass == "CodeMirror-linenumbers") {
  279. cm.display.lineGutter = gElt;
  280. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  281. }
  282. }
  283. gutters.style.display = i ? "" : "none";
  284. updateGutterSpace(cm);
  285. }
  286. function updateGutterSpace(cm) {
  287. var width = cm.display.gutters.offsetWidth;
  288. cm.display.sizer.style.marginLeft = width + "px";
  289. cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
  290. }
  291. // Compute the character length of a line, taking into account
  292. // collapsed ranges (see markText) that might hide parts, and join
  293. // other lines onto it.
  294. function lineLength(line) {
  295. if (line.height == 0) return 0;
  296. var len = line.text.length, merged, cur = line;
  297. while (merged = collapsedSpanAtStart(cur)) {
  298. var found = merged.find(0, true);
  299. cur = found.from.line;
  300. len += found.from.ch - found.to.ch;
  301. }
  302. cur = line;
  303. while (merged = collapsedSpanAtEnd(cur)) {
  304. var found = merged.find(0, true);
  305. len -= cur.text.length - found.from.ch;
  306. cur = found.to.line;
  307. len += cur.text.length - found.to.ch;
  308. }
  309. return len;
  310. }
  311. // Find the longest line in the document.
  312. function findMaxLine(cm) {
  313. var d = cm.display, doc = cm.doc;
  314. d.maxLine = getLine(doc, doc.first);
  315. d.maxLineLength = lineLength(d.maxLine);
  316. d.maxLineChanged = true;
  317. doc.iter(function(line) {
  318. var len = lineLength(line);
  319. if (len > d.maxLineLength) {
  320. d.maxLineLength = len;
  321. d.maxLine = line;
  322. }
  323. });
  324. }
  325. // Make sure the gutters options contains the element
  326. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  327. function setGuttersForLineNumbers(options) {
  328. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  329. if (found == -1 && options.lineNumbers) {
  330. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  331. } else if (found > -1 && !options.lineNumbers) {
  332. options.gutters = options.gutters.slice(0);
  333. options.gutters.splice(found, 1);
  334. }
  335. }
  336. // SCROLLBARS
  337. // Prepare DOM reads needed to update the scrollbars. Done in one
  338. // shot to minimize update/measure roundtrips.
  339. function measureForScrollbars(cm) {
  340. var scroll = cm.display.scroller;
  341. return {
  342. clientHeight: scroll.clientHeight,
  343. barHeight: cm.display.scrollbarV.clientHeight,
  344. scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,
  345. barWidth: cm.display.scrollbarH.clientWidth,
  346. docHeight: Math.round(cm.doc.height + paddingVert(cm.display))
  347. };
  348. }
  349. // Re-synchronize the fake scrollbars with the actual size of the
  350. // content.
  351. function updateScrollbars(cm, measure) {
  352. if (!measure) measure = measureForScrollbars(cm);
  353. var d = cm.display;
  354. var scrollHeight = measure.docHeight + scrollerCutOff;
  355. var needsH = measure.scrollWidth > measure.clientWidth;
  356. var needsV = scrollHeight > measure.clientHeight;
  357. if (needsV) {
  358. d.scrollbarV.style.display = "block";
  359. d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
  360. // A bug in IE8 can cause this value to be negative, so guard it.
  361. d.scrollbarV.firstChild.style.height =
  362. Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px";
  363. } else {
  364. d.scrollbarV.style.display = "";
  365. d.scrollbarV.firstChild.style.height = "0";
  366. }
  367. if (needsH) {
  368. d.scrollbarH.style.display = "block";
  369. d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
  370. d.scrollbarH.firstChild.style.width =
  371. (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px";
  372. } else {
  373. d.scrollbarH.style.display = "";
  374. d.scrollbarH.firstChild.style.width = "0";
  375. }
  376. if (needsH && needsV) {
  377. d.scrollbarFiller.style.display = "block";
  378. d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
  379. } else d.scrollbarFiller.style.display = "";
  380. if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  381. d.gutterFiller.style.display = "block";
  382. d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
  383. d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
  384. } else d.gutterFiller.style.display = "";
  385. if (!cm.state.checkedOverlayScrollbar && measure.clientHeight > 0) {
  386. if (scrollbarWidth(d.measure) === 0) {
  387. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  388. d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = w;
  389. var barMouseDown = function(e) {
  390. if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)
  391. operation(cm, onMouseDown)(e);
  392. };
  393. on(d.scrollbarV, "mousedown", barMouseDown);
  394. on(d.scrollbarH, "mousedown", barMouseDown);
  395. }
  396. cm.state.checkedOverlayScrollbar = true;
  397. }
  398. }
  399. // Compute the lines that are visible in a given viewport (defaults
  400. // the the current scroll position). viewPort may contain top,
  401. // height, and ensure (see op.scrollToPos) properties.
  402. function visibleLines(display, doc, viewPort) {
  403. var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller.scrollTop;
  404. top = Math.floor(top - paddingTop(display));
  405. var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight;
  406. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  407. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  408. // forces those lines into the viewport (if possible).
  409. if (viewPort && viewPort.ensure) {
  410. var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line;
  411. if (ensureFrom < from)
  412. return {from: ensureFrom,
  413. to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};
  414. if (Math.min(ensureTo, doc.lastLine()) >= to)
  415. return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),
  416. to: ensureTo};
  417. }
  418. return {from: from, to: to};
  419. }
  420. // LINE NUMBERS
  421. // Re-align line numbers and gutter marks to compensate for
  422. // horizontal scrolling.
  423. function alignHorizontally(cm) {
  424. var display = cm.display, view = display.view;
  425. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  426. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  427. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  428. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  429. if (cm.options.fixedGutter && view[i].gutter)
  430. view[i].gutter.style.left = left;
  431. var align = view[i].alignable;
  432. if (align) for (var j = 0; j < align.length; j++)
  433. align[j].style.left = left;
  434. }
  435. if (cm.options.fixedGutter)
  436. display.gutters.style.left = (comp + gutterW) + "px";
  437. }
  438. // Used to ensure that the line number gutter is still the right
  439. // size for the current document size. Returns true when an update
  440. // is needed.
  441. function maybeUpdateLineNumberWidth(cm) {
  442. if (!cm.options.lineNumbers) return false;
  443. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  444. if (last.length != display.lineNumChars) {
  445. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  446. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  447. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  448. display.lineGutter.style.width = "";
  449. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  450. display.lineNumWidth = display.lineNumInnerWidth + padding;
  451. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  452. display.lineGutter.style.width = display.lineNumWidth + "px";
  453. updateGutterSpace(cm);
  454. return true;
  455. }
  456. return false;
  457. }
  458. function lineNumberFor(options, i) {
  459. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  460. }
  461. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  462. // but using getBoundingClientRect to get a sub-pixel-accurate
  463. // result.
  464. function compensateForHScroll(display) {
  465. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  466. }
  467. // DISPLAY DRAWING
  468. // Updates the display, selection, and scrollbars, using the
  469. // information in display.view to find out which nodes are no longer
  470. // up-to-date. Tries to bail out early when no changes are needed,
  471. // unless forced is true.
  472. // Returns true if an actual update happened, false otherwise.
  473. function updateDisplay(cm, viewPort, forced) {
  474. var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated;
  475. var visible = visibleLines(cm.display, cm.doc, viewPort);
  476. for (var first = true;; first = false) {
  477. var oldWidth = cm.display.scroller.clientWidth;
  478. if (!updateDisplayInner(cm, visible, forced)) break;
  479. updated = true;
  480. // If the max line changed since it was last measured, measure it,
  481. // and ensure the document's width matches it.
  482. if (cm.display.maxLineChanged && !cm.options.lineWrapping)
  483. adjustContentWidth(cm);
  484. var barMeasure = measureForScrollbars(cm);
  485. updateSelection(cm);
  486. setDocumentHeight(cm, barMeasure);
  487. updateScrollbars(cm, barMeasure);
  488. if (webkit && cm.options.lineWrapping)
  489. checkForWebkitWidthBug(cm, barMeasure); // (Issue #2420)
  490. if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
  491. forced = true;
  492. continue;
  493. }
  494. forced = false;
  495. // Clip forced viewport to actual scrollable area.
  496. if (viewPort && viewPort.top != null)
  497. viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)};
  498. // Updated line heights might result in the drawn area not
  499. // actually covering the viewport. Keep looping until it does.
  500. visible = visibleLines(cm.display, cm.doc, viewPort);
  501. if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo)
  502. break;
  503. }
  504. cm.display.updateLineNumbers = null;
  505. if (updated) {
  506. signalLater(cm, "update", cm);
  507. if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo)
  508. signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  509. }
  510. return updated;
  511. }
  512. // Does the actual updating of the line display. Bails out
  513. // (returning false) when there is nothing to be done and forced is
  514. // false.
  515. function updateDisplayInner(cm, visible, forced) {
  516. var display = cm.display, doc = cm.doc;
  517. if (!display.wrapper.offsetWidth) {
  518. resetView(cm);
  519. return;
  520. }
  521. // Bail out if the visible area is already rendered and nothing changed.
  522. if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo &&
  523. countDirtyView(cm) == 0)
  524. return;
  525. if (maybeUpdateLineNumberWidth(cm))
  526. resetView(cm);
  527. var dims = getDimensions(cm);
  528. // Compute a suitable new viewport (from & to)
  529. var end = doc.first + doc.size;
  530. var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
  531. var to = Math.min(end, visible.to + cm.options.viewportMargin);
  532. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  533. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  534. if (sawCollapsedSpans) {
  535. from = visualLineNo(cm.doc, from);
  536. to = visualLineEndNo(cm.doc, to);
  537. }
  538. var different = from != display.viewFrom || to != display.viewTo ||
  539. display.lastSizeC != display.wrapper.clientHeight;
  540. adjustView(cm, from, to);
  541. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  542. // Position the mover div to align with the current scroll position
  543. cm.display.mover.style.top = display.viewOffset + "px";
  544. var toUpdate = countDirtyView(cm);
  545. if (!different && toUpdate == 0 && !forced) return;
  546. // For big changes, we hide the enclosing element during the
  547. // update, since that speeds up the operations on most browsers.
  548. var focused = activeElt();
  549. if (toUpdate > 4) display.lineDiv.style.display = "none";
  550. patchDisplay(cm, display.updateLineNumbers, dims);
  551. if (toUpdate > 4) display.lineDiv.style.display = "";
  552. // There might have been a widget with a focused element that got
  553. // hidden or updated, if so re-focus it.
  554. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  555. // Prevent selection and cursors from interfering with the scroll
  556. // width.
  557. removeChildren(display.cursorDiv);
  558. removeChildren(display.selectionDiv);
  559. if (different) {
  560. display.lastSizeC = display.wrapper.clientHeight;
  561. startWorker(cm, 400);
  562. }
  563. updateHeightsInViewport(cm);
  564. return true;
  565. }
  566. function adjustContentWidth(cm) {
  567. var display = cm.display;
  568. var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left;
  569. display.maxLineChanged = false;
  570. var minWidth = Math.max(0, width + 3);
  571. var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth);
  572. display.sizer.style.minWidth = minWidth + "px";
  573. if (maxScrollLeft < cm.doc.scrollLeft)
  574. setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
  575. }
  576. function setDocumentHeight(cm, measure) {
  577. cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px";
  578. cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px";
  579. }
  580. function checkForWebkitWidthBug(cm, measure) {
  581. // Work around Webkit bug where it sometimes reserves space for a
  582. // non-existing phantom scrollbar in the scroller (Issue #2420)
  583. if (cm.display.sizer.offsetWidth + cm.display.gutters.offsetWidth < cm.display.scroller.clientWidth - 1) {
  584. cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = "0px";
  585. cm.display.gutters.style.height = measure.docHeight + "px";
  586. }
  587. }
  588. // Read the actual heights of the rendered lines, and update their
  589. // stored heights to match.
  590. function updateHeightsInViewport(cm) {
  591. var display = cm.display;
  592. var prevBottom = display.lineDiv.offsetTop;
  593. for (var i = 0; i < display.view.length; i++) {
  594. var cur = display.view[i], height;
  595. if (cur.hidden) continue;
  596. if (ie_upto7) {
  597. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  598. height = bot - prevBottom;
  599. prevBottom = bot;
  600. } else {
  601. var box = cur.node.getBoundingClientRect();
  602. height = box.bottom - box.top;
  603. }
  604. var diff = cur.line.height - height;
  605. if (height < 2) height = textHeight(display);
  606. if (diff > .001 || diff < -.001) {
  607. updateLineHeight(cur.line, height);
  608. updateWidgetHeight(cur.line);
  609. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  610. updateWidgetHeight(cur.rest[j]);
  611. }
  612. }
  613. }
  614. // Read and store the height of line widgets associated with the
  615. // given line.
  616. function updateWidgetHeight(line) {
  617. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  618. line.widgets[i].height = line.widgets[i].node.offsetHeight;
  619. }
  620. // Do a bulk-read of the DOM positions and sizes needed to draw the
  621. // view, so that we don't interleave reading and writing to the DOM.
  622. function getDimensions(cm) {
  623. var d = cm.display, left = {}, width = {};
  624. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  625. left[cm.options.gutters[i]] = n.offsetLeft;
  626. width[cm.options.gutters[i]] = n.offsetWidth;
  627. }
  628. return {fixedPos: compensateForHScroll(d),
  629. gutterTotalWidth: d.gutters.offsetWidth,
  630. gutterLeft: left,
  631. gutterWidth: width,
  632. wrapperWidth: d.wrapper.clientWidth};
  633. }
  634. // Sync the actual display DOM structure with display.view, removing
  635. // nodes for lines that are no longer in view, and creating the ones
  636. // that are not there yet, and updating the ones that are out of
  637. // date.
  638. function patchDisplay(cm, updateNumbersFrom, dims) {
  639. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  640. var container = display.lineDiv, cur = container.firstChild;
  641. function rm(node) {
  642. var next = node.nextSibling;
  643. // Works around a throw-scroll bug in OS X Webkit
  644. if (webkit && mac && cm.display.currentWheelTarget == node)
  645. node.style.display = "none";
  646. else
  647. node.parentNode.removeChild(node);
  648. return next;
  649. }
  650. var view = display.view, lineN = display.viewFrom;
  651. // Loop over the elements in the view, syncing cur (the DOM nodes
  652. // in display.lineDiv) with the view as we go.
  653. for (var i = 0; i < view.length; i++) {
  654. var lineView = view[i];
  655. if (lineView.hidden) {
  656. } else if (!lineView.node) { // Not drawn yet
  657. var node = buildLineElement(cm, lineView, lineN, dims);
  658. container.insertBefore(node, cur);
  659. } else { // Already drawn
  660. while (cur != lineView.node) cur = rm(cur);
  661. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  662. updateNumbersFrom <= lineN && lineView.lineNumber;
  663. if (lineView.changes) {
  664. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  665. updateLineForChanges(cm, lineView, lineN, dims);
  666. }
  667. if (updateNumber) {
  668. removeChildren(lineView.lineNumber);
  669. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  670. }
  671. cur = lineView.node.nextSibling;
  672. }
  673. lineN += lineView.size;
  674. }
  675. while (cur) cur = rm(cur);
  676. }
  677. // When an aspect of a line changes, a string is added to
  678. // lineView.changes. This updates the relevant part of the line's
  679. // DOM structure.
  680. function updateLineForChanges(cm, lineView, lineN, dims) {
  681. for (var j = 0; j < lineView.changes.length; j++) {
  682. var type = lineView.changes[j];
  683. if (type == "text") updateLineText(cm, lineView);
  684. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  685. else if (type == "class") updateLineClasses(lineView);
  686. else if (type == "widget") updateLineWidgets(lineView, dims);
  687. }
  688. lineView.changes = null;
  689. }
  690. // Lines with gutter elements, widgets or a background class need to
  691. // be wrapped, and have the extra elements added to the wrapper div
  692. function ensureLineWrapped(lineView) {
  693. if (lineView.node == lineView.text) {
  694. lineView.node = elt("div", null, null, "position: relative");
  695. if (lineView.text.parentNode)
  696. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  697. lineView.node.appendChild(lineView.text);
  698. if (ie_upto7) lineView.node.style.zIndex = 2;
  699. }
  700. return lineView.node;
  701. }
  702. function updateLineBackground(lineView) {
  703. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  704. if (cls) cls += " CodeMirror-linebackground";
  705. if (lineView.background) {
  706. if (cls) lineView.background.className = cls;
  707. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  708. } else if (cls) {
  709. var wrap = ensureLineWrapped(lineView);
  710. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  711. }
  712. }
  713. // Wrapper around buildLineContent which will reuse the structure
  714. // in display.externalMeasured when possible.
  715. function getLineContent(cm, lineView) {
  716. var ext = cm.display.externalMeasured;
  717. if (ext && ext.line == lineView.line) {
  718. cm.display.externalMeasured = null;
  719. lineView.measure = ext.measure;
  720. return ext.built;
  721. }
  722. return buildLineContent(cm, lineView);
  723. }
  724. // Redraw the line's text. Interacts with the background and text
  725. // classes because the mode may output tokens that influence these
  726. // classes.
  727. function updateLineText(cm, lineView) {
  728. var cls = lineView.text.className;
  729. var built = getLineContent(cm, lineView);
  730. if (lineView.text == lineView.node) lineView.node = built.pre;
  731. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  732. lineView.text = built.pre;
  733. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  734. lineView.bgClass = built.bgClass;
  735. lineView.textClass = built.textClass;
  736. updateLineClasses(lineView);
  737. } else if (cls) {
  738. lineView.text.className = cls;
  739. }
  740. }
  741. function updateLineClasses(lineView) {
  742. updateLineBackground(lineView);
  743. if (lineView.line.wrapClass)
  744. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  745. else if (lineView.node != lineView.text)
  746. lineView.node.className = "";
  747. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  748. lineView.text.className = textClass || "";
  749. }
  750. function updateLineGutter(cm, lineView, lineN, dims) {
  751. if (lineView.gutter) {
  752. lineView.node.removeChild(lineView.gutter);
  753. lineView.gutter = null;
  754. }
  755. var markers = lineView.line.gutterMarkers;
  756. if (cm.options.lineNumbers || markers) {
  757. var wrap = ensureLineWrapped(lineView);
  758. var gutterWrap = lineView.gutter =
  759. wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
  760. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
  761. lineView.text);
  762. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  763. lineView.lineNumber = gutterWrap.appendChild(
  764. elt("div", lineNumberFor(cm.options, lineN),
  765. "CodeMirror-linenumber CodeMirror-gutter-elt",
  766. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  767. + cm.display.lineNumInnerWidth + "px"));
  768. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  769. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  770. if (found)
  771. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  772. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  773. }
  774. }
  775. }
  776. function updateLineWidgets(lineView, dims) {
  777. if (lineView.alignable) lineView.alignable = null;
  778. for (var node = lineView.node.firstChild, next; node; node = next) {
  779. var next = node.nextSibling;
  780. if (node.className == "CodeMirror-linewidget")
  781. lineView.node.removeChild(node);
  782. }
  783. insertLineWidgets(lineView, dims);
  784. }
  785. // Build a line's DOM representation from scratch
  786. function buildLineElement(cm, lineView, lineN, dims) {
  787. var built = getLineContent(cm, lineView);
  788. lineView.text = lineView.node = built.pre;
  789. if (built.bgClass) lineView.bgClass = built.bgClass;
  790. if (built.textClass) lineView.textClass = built.textClass;
  791. updateLineClasses(lineView);
  792. updateLineGutter(cm, lineView, lineN, dims);
  793. insertLineWidgets(lineView, dims);
  794. return lineView.node;
  795. }
  796. // A lineView may contain multiple logical lines (when merged by
  797. // collapsed spans). The widgets for all of them need to be drawn.
  798. function insertLineWidgets(lineView, dims) {
  799. insertLineWidgetsFor(lineView.line, lineView, dims, true);
  800. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  801. insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
  802. }
  803. function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
  804. if (!line.widgets) return;
  805. var wrap = ensureLineWrapped(lineView);
  806. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  807. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  808. if (!widget.handleMouseEvents) node.ignoreEvents = true;
  809. positionLineWidget(widget, node, lineView, dims);
  810. if (allowAbove && widget.above)
  811. wrap.insertBefore(node, lineView.gutter || lineView.text);
  812. else
  813. wrap.appendChild(node);
  814. signalLater(widget, "redraw");
  815. }
  816. }
  817. function positionLineWidget(widget, node, lineView, dims) {
  818. if (widget.noHScroll) {
  819. (lineView.alignable || (lineView.alignable = [])).push(node);
  820. var width = dims.wrapperWidth;
  821. node.style.left = dims.fixedPos + "px";
  822. if (!widget.coverGutter) {
  823. width -= dims.gutterTotalWidth;
  824. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  825. }
  826. node.style.width = width + "px";
  827. }
  828. if (widget.coverGutter) {
  829. node.style.zIndex = 5;
  830. node.style.position = "relative";
  831. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  832. }
  833. }
  834. // POSITION OBJECT
  835. // A Pos instance represents a position within the text.
  836. var Pos = CodeMirror.Pos = function(line, ch) {
  837. if (!(this instanceof Pos)) return new Pos(line, ch);
  838. this.line = line; this.ch = ch;
  839. };
  840. // Compare two positions, return 0 if they are the same, a negative
  841. // number when a is less, and a positive number otherwise.
  842. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  843. function copyPos(x) {return Pos(x.line, x.ch);}
  844. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  845. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  846. // SELECTION / CURSOR
  847. // Selection objects are immutable. A new one is created every time
  848. // the selection changes. A selection is one or more non-overlapping
  849. // (and non-touching) ranges, sorted, and an integer that indicates
  850. // which one is the primary selection (the one that's scrolled into
  851. // view, that getCursor returns, etc).
  852. function Selection(ranges, primIndex) {
  853. this.ranges = ranges;
  854. this.primIndex = primIndex;
  855. }
  856. Selection.prototype = {
  857. primary: function() { return this.ranges[this.primIndex]; },
  858. equals: function(other) {
  859. if (other == this) return true;
  860. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  861. for (var i = 0; i < this.ranges.length; i++) {
  862. var here = this.ranges[i], there = other.ranges[i];
  863. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  864. }
  865. return true;
  866. },
  867. deepCopy: function() {
  868. for (var out = [], i = 0; i < this.ranges.length; i++)
  869. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  870. return new Selection(out, this.primIndex);
  871. },
  872. somethingSelected: function() {
  873. for (var i = 0; i < this.ranges.length; i++)
  874. if (!this.ranges[i].empty()) return true;
  875. return false;
  876. },
  877. contains: function(pos, end) {
  878. if (!end) end = pos;
  879. for (var i = 0; i < this.ranges.length; i++) {
  880. var range = this.ranges[i];
  881. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  882. return i;
  883. }
  884. return -1;
  885. }
  886. };
  887. function Range(anchor, head) {
  888. this.anchor = anchor; this.head = head;
  889. }
  890. Range.prototype = {
  891. from: function() { return minPos(this.anchor, this.head); },
  892. to: function() { return maxPos(this.anchor, this.head); },
  893. empty: function() {
  894. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  895. }
  896. };
  897. // Take an unsorted, potentially overlapping set of ranges, and
  898. // build a selection out of it. 'Consumes' ranges array (modifying
  899. // it).
  900. function normalizeSelection(ranges, primIndex) {
  901. var prim = ranges[primIndex];
  902. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  903. primIndex = indexOf(ranges, prim);
  904. for (var i = 1; i < ranges.length; i++) {
  905. var cur = ranges[i], prev = ranges[i - 1];
  906. if (cmp(prev.to(), cur.from()) >= 0) {
  907. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  908. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  909. if (i <= primIndex) --primIndex;
  910. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  911. }
  912. }
  913. return new Selection(ranges, primIndex);
  914. }
  915. function simpleSelection(anchor, head) {
  916. return new Selection([new Range(anchor, head || anchor)], 0);
  917. }
  918. // Most of the external API clips given positions to make sure they
  919. // actually exist within the document.
  920. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  921. function clipPos(doc, pos) {
  922. if (pos.line < doc.first) return Pos(doc.first, 0);
  923. var last = doc.first + doc.size - 1;
  924. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  925. return clipToLen(pos, getLine(doc, pos.line).text.length);
  926. }
  927. function clipToLen(pos, linelen) {
  928. var ch = pos.ch;
  929. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  930. else if (ch < 0) return Pos(pos.line, 0);
  931. else return pos;
  932. }
  933. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  934. function clipPosArray(doc, array) {
  935. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  936. return out;
  937. }
  938. // SELECTION UPDATES
  939. // The 'scroll' parameter given to many of these indicated whether
  940. // the new cursor position should be scrolled into view after
  941. // modifying the selection.
  942. // If shift is held or the extend flag is set, extends a range to
  943. // include a given position (and optionally a second position).
  944. // Otherwise, simply returns the range between the given positions.
  945. // Used for cursor motion and such.
  946. function extendRange(doc, range, head, other) {
  947. if (doc.cm && doc.cm.display.shift || doc.extend) {
  948. var anchor = range.anchor;
  949. if (other) {
  950. var posBefore = cmp(head, anchor) < 0;
  951. if (posBefore != (cmp(other, anchor) < 0)) {
  952. anchor = head;
  953. head = other;
  954. } else if (posBefore != (cmp(head, other) < 0)) {
  955. head = other;
  956. }
  957. }
  958. return new Range(anchor, head);
  959. } else {
  960. return new Range(other || head, head);
  961. }
  962. }
  963. // Extend the primary selection range, discard the rest.
  964. function extendSelection(doc, head, other, options) {
  965. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  966. }
  967. // Extend all selections (pos is an array of selections with length
  968. // equal the number of selections)
  969. function extendSelections(doc, heads, options) {
  970. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  971. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  972. var newSel = normalizeSelection(out, doc.sel.primIndex);
  973. setSelection(doc, newSel, options);
  974. }
  975. // Updates a single range in the selection.
  976. function replaceOneSelection(doc, i, range, options) {
  977. var ranges = doc.sel.ranges.slice(0);
  978. ranges[i] = range;
  979. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  980. }
  981. // Reset the selection to a single range.
  982. function setSimpleSelection(doc, anchor, head, options) {
  983. setSelection(doc, simpleSelection(anchor, head), options);
  984. }
  985. // Give beforeSelectionChange handlers a change to influence a
  986. // selection update.
  987. function filterSelectionChange(doc, sel) {
  988. var obj = {
  989. ranges: sel.ranges,
  990. update: function(ranges) {
  991. this.ranges = [];
  992. for (var i = 0; i < ranges.length; i++)
  993. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  994. clipPos(doc, ranges[i].head));
  995. }
  996. };
  997. signal(doc, "beforeSelectionChange", doc, obj);
  998. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  999. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  1000. else return sel;
  1001. }
  1002. function setSelectionReplaceHistory(doc, sel, options) {
  1003. var done = doc.history.done, last = lst(done);
  1004. if (last && last.ranges) {
  1005. done[done.length - 1] = sel;
  1006. setSelectionNoUndo(doc, sel, options);
  1007. } else {
  1008. setSelection(doc, sel, options);
  1009. }
  1010. }
  1011. // Set a new selection.
  1012. function setSelection(doc, sel, options) {
  1013. setSelectionNoUndo(doc, sel, options);
  1014. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  1015. }
  1016. function setSelectionNoUndo(doc, sel, options) {
  1017. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  1018. sel = filterSelectionChange(doc, sel);
  1019. var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1;
  1020. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  1021. if (!(options && options.scroll === false) && doc.cm)
  1022. ensureCursorVisible(doc.cm);
  1023. }
  1024. function setSelectionInner(doc, sel) {
  1025. if (sel.equals(doc.sel)) return;
  1026. doc.sel = sel;
  1027. if (doc.cm) {
  1028. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  1029. signalCursorActivity(doc.cm);
  1030. }
  1031. signalLater(doc, "cursorActivity", doc);
  1032. }
  1033. // Verify that the selection does not partially select any atomic
  1034. // marked ranges.
  1035. function reCheckSelection(doc) {
  1036. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  1037. }
  1038. // Return a selection that does not partially select any atomic
  1039. // ranges.
  1040. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  1041. var out;
  1042. for (var i = 0; i < sel.ranges.length; i++) {
  1043. var range = sel.ranges[i];
  1044. var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
  1045. var newHead = skipAtomic(doc, range.head, bias, mayClear);
  1046. if (out || newAnchor != range.anchor || newHead != range.head) {
  1047. if (!out) out = sel.ranges.slice(0, i);
  1048. out[i] = new Range(newAnchor, newHead);
  1049. }
  1050. }
  1051. return out ? normalizeSelection(out, sel.primIndex) : sel;
  1052. }
  1053. // Ensure a given position is not inside an atomic range.
  1054. function skipAtomic(doc, pos, bias, mayClear) {
  1055. var flipped = false, curPos = pos;
  1056. var dir = bias || 1;
  1057. doc.cantEdit = false;
  1058. search: for (;;) {
  1059. var line = getLine(doc, curPos.line);
  1060. if (line.markedSpans) {
  1061. for (var i = 0; i < line.markedSpans.length; ++i) {
  1062. var sp = line.markedSpans[i], m = sp.marker;
  1063. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  1064. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  1065. if (mayClear) {
  1066. signal(m, "beforeCursorEnter");
  1067. if (m.explicitlyCleared) {
  1068. if (!line.markedSpans) break;
  1069. else {--i; continue;}
  1070. }
  1071. }
  1072. if (!m.atomic) continue;
  1073. var newPos = m.find(dir < 0 ? -1 : 1);
  1074. if (cmp(newPos, curPos) == 0) {
  1075. newPos.ch += dir;
  1076. if (newPos.ch < 0) {
  1077. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  1078. else newPos = null;
  1079. } else if (newPos.ch > line.text.length) {
  1080. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  1081. else newPos = null;
  1082. }
  1083. if (!newPos) {
  1084. if (flipped) {
  1085. // Driven in a corner -- no valid cursor position found at all
  1086. // -- try again *with* clearing, if we didn't already
  1087. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  1088. // Otherwise, turn off editing until further notice, and return the start of the doc
  1089. doc.cantEdit = true;
  1090. return Pos(doc.first, 0);
  1091. }
  1092. flipped = true; newPos = pos; dir = -dir;
  1093. }
  1094. }
  1095. curPos = newPos;
  1096. continue search;
  1097. }
  1098. }
  1099. }
  1100. return curPos;
  1101. }
  1102. }
  1103. // SELECTION DRAWING
  1104. // Redraw the selection and/or cursor
  1105. function updateSelection(cm) {
  1106. var display = cm.display, doc = cm.doc;
  1107. var curFragment = document.createDocumentFragment();
  1108. var selFragment = document.createDocumentFragment();
  1109. for (var i = 0; i < doc.sel.ranges.length; i++) {
  1110. var range = doc.sel.ranges[i];
  1111. var collapsed = range.empty();
  1112. if (collapsed || cm.options.showCursorWhenSelecting)
  1113. drawSelectionCursor(cm, range, curFragment);
  1114. if (!collapsed)
  1115. drawSelectionRange(cm, range, selFragment);
  1116. }
  1117. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  1118. if (cm.options.moveInputWithCursor) {
  1119. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  1120. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  1121. var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  1122. headPos.top + lineOff.top - wrapOff.top));
  1123. var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  1124. headPos.left + lineOff.left - wrapOff.left));
  1125. display.inputDiv.style.top = top + "px";
  1126. display.inputDiv.style.left = left + "px";
  1127. }
  1128. removeChildrenAndAdd(display.cursorDiv, curFragment);
  1129. removeChildrenAndAdd(display.selectionDiv, selFragment);
  1130. }
  1131. // Draws a cursor for the given range
  1132. function drawSelectionCursor(cm, range, output) {
  1133. var pos = cursorCoords(cm, range.head, "div");
  1134. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  1135. cursor.style.left = pos.left + "px";
  1136. cursor.style.top = pos.top + "px";
  1137. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  1138. if (pos.other) {
  1139. // Secondary cursor, shown when on a 'jump' in bi-directional text
  1140. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  1141. otherCursor.style.display = "";
  1142. otherCursor.style.left = pos.other.left + "px";
  1143. otherCursor.style.top = pos.other.top + "px";
  1144. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  1145. }
  1146. }
  1147. // Draws the given range as a highlighted selection
  1148. function drawSelectionRange(cm, range, output) {
  1149. var display = cm.display, doc = cm.doc;
  1150. var fragment = document.createDocumentFragment();
  1151. var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;
  1152. function add(left, top, width, bottom) {
  1153. if (top < 0) top = 0;
  1154. top = Math.round(top);
  1155. bottom = Math.round(bottom);
  1156. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  1157. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  1158. "px; height: " + (bottom - top) + "px"));
  1159. }
  1160. function drawForLine(line, fromArg, toArg) {
  1161. var lineObj = getLine(doc, line);
  1162. var lineLen = lineObj.text.length;
  1163. var start, end;
  1164. function coords(ch, bias) {
  1165. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  1166. }
  1167. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  1168. var leftPos = coords(from, "left"), rightPos, left, right;
  1169. if (from == to) {
  1170. rightPos = leftPos;
  1171. left = right = leftPos.left;
  1172. } else {
  1173. rightPos = coords(to - 1, "right");
  1174. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  1175. left = leftPos.left;
  1176. right = rightPos.right;
  1177. }
  1178. if (fromArg == null && from == 0) left = leftSide;
  1179. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  1180. add(left, leftPos.top, null, leftPos.bottom);
  1181. left = leftSide;
  1182. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  1183. }
  1184. if (toArg == null && to == lineLen) right = rightSide;
  1185. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  1186. start = leftPos;
  1187. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  1188. end = rightPos;
  1189. if (left < leftSide + 1) left = leftSide;
  1190. add(left, rightPos.top, right - left, rightPos.bottom);
  1191. });
  1192. return {start: start, end: end};
  1193. }
  1194. var sFrom = range.from(), sTo = range.to();
  1195. if (sFrom.line == sTo.line) {
  1196. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  1197. } else {
  1198. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  1199. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  1200. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  1201. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  1202. if (singleVLine) {
  1203. if (leftEnd.top < rightStart.top - 2) {
  1204. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  1205. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  1206. } else {
  1207. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  1208. }
  1209. }
  1210. if (leftEnd.bottom < rightStart.top)
  1211. add(leftSide, leftEnd.bottom, null, rightStart.top);
  1212. }
  1213. output.appendChild(fragment);
  1214. }
  1215. // Cursor-blinking
  1216. function restartBlink(cm) {
  1217. if (!cm.state.focused) return;
  1218. var display = cm.display;
  1219. clearInterval(display.blinker);
  1220. var on = true;
  1221. display.cursorDiv.style.visibility = "";
  1222. if (cm.options.cursorBlinkRate > 0)
  1223. display.blinker = setInterval(function() {
  1224. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  1225. }, cm.options.cursorBlinkRate);
  1226. }
  1227. // HIGHLIGHT WORKER
  1228. function startWorker(cm, time) {
  1229. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  1230. cm.state.highlight.set(time, bind(highlightWorker, cm));
  1231. }
  1232. function highlightWorker(cm) {
  1233. var doc = cm.doc;
  1234. if (doc.frontier < doc.first) doc.frontier = doc.first;
  1235. if (doc.frontier >= cm.display.viewTo) return;
  1236. var end = +new Date + cm.options.workTime;
  1237. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  1238. runInOp(cm, function() {
  1239. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  1240. if (doc.frontier >= cm.display.viewFrom) { // Visible
  1241. var oldStyles = line.styles;
  1242. var highlighted = highlightLine(cm, line, state, true);
  1243. line.styles = highlighted.styles;
  1244. if (highlighted.classes) line.styleClasses = highlighted.classes;
  1245. else if (line.styleClasses) line.styleClasses = null;
  1246. var ischange = !oldStyles || oldStyles.length != line.styles.length;
  1247. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  1248. if (ischange) regLineChange(cm, doc.frontier, "text");
  1249. line.stateAfter = copyState(doc.mode, state);
  1250. } else {
  1251. processLine(cm, line.text, state);
  1252. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  1253. }
  1254. ++doc.frontier;
  1255. if (+new Date > end) {
  1256. startWorker(cm, cm.options.workDelay);
  1257. return true;
  1258. }
  1259. });
  1260. });
  1261. }
  1262. // Finds the line to start with when starting a parse. Tries to
  1263. // find a line with a stateAfter, so that it can start with a
  1264. // valid state. If that fails, it returns the line with the
  1265. // smallest indentation, which tends to need the least context to
  1266. // parse correctly.
  1267. function findStartLine(cm, n, precise) {
  1268. var minindent, minline, doc = cm.doc;
  1269. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1270. for (var search = n; search > lim; --search) {
  1271. if (search <= doc.first) return doc.first;
  1272. var line = getLine(doc, search - 1);
  1273. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  1274. var indented = countColumn(line.text, null, cm.options.tabSize);
  1275. if (minline == null || minindent > indented) {
  1276. minline = search - 1;
  1277. minindent = indented;
  1278. }
  1279. }
  1280. return minline;
  1281. }
  1282. function getStateBefore(cm, n, precise) {
  1283. var doc = cm.doc, display = cm.display;
  1284. if (!doc.mode.startState) return true;
  1285. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  1286. if (!state) state = startState(doc.mode);
  1287. else state = copyState(doc.mode, state);
  1288. doc.iter(pos, n, function(line) {
  1289. processLine(cm, line.text, state);
  1290. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  1291. line.stateAfter = save ? copyState(doc.mode, state) : null;
  1292. ++pos;
  1293. });
  1294. if (precise) doc.frontier = pos;
  1295. return state;
  1296. }
  1297. // POSITION MEASUREMENT
  1298. function paddingTop(display) {return display.lineSpace.offsetTop;}
  1299. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  1300. function paddingH(display) {
  1301. if (display.cachedPaddingH) return display.cachedPaddingH;
  1302. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  1303. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  1304. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  1305. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  1306. return data;
  1307. }
  1308. // Ensure the lineView.wrapping.heights array is populated. This is
  1309. // an array of bottom offsets for the lines that make up a drawn
  1310. // line. When lineWrapping is on, there might be more than one
  1311. // height.
  1312. function ensureLineHeights(cm, lineView, rect) {
  1313. var wrapping = cm.options.lineWrapping;
  1314. var curWidth = wrapping && cm.display.scroller.clientWidth;
  1315. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  1316. var heights = lineView.measure.heights = [];
  1317. if (wrapping) {
  1318. lineView.measure.width = curWidth;
  1319. var rects = lineView.text.firstChild.getClientRects();
  1320. for (var i = 0; i < rects.length - 1; i++) {
  1321. var cur = rects[i], next = rects[i + 1];
  1322. if (Math.abs(cur.bottom - next.bottom) > 2)
  1323. heights.push((cur.bottom + next.top) / 2 - rect.top);
  1324. }
  1325. }
  1326. heights.push(rect.bottom - rect.top);
  1327. }
  1328. }
  1329. // Find a line map (mapping character offsets to text nodes) and a
  1330. // measurement cache for the given line number. (A line view might
  1331. // contain multiple lines when collapsed ranges are present.)
  1332. function mapFromLineView(lineView, line, lineN) {
  1333. if (lineView.line == line)
  1334. return {map: lineView.measure.map, cache: lineView.measure.cache};
  1335. for (var i = 0; i < lineView.rest.length; i++)
  1336. if (lineView.rest[i] == line)
  1337. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  1338. for (var i = 0; i < lineView.rest.length; i++)
  1339. if (lineNo(lineView.rest[i]) > lineN)
  1340. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  1341. }
  1342. // Render a line into the hidden node display.externalMeasured. Used
  1343. // when measurement is needed for a line that's not in the viewport.
  1344. function updateExternalMeasurement(cm, line) {
  1345. line = visualLine(line);
  1346. var lineN = lineNo(line);
  1347. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  1348. view.lineN = lineN;
  1349. var built = view.built = buildLineContent(cm, view);
  1350. view.text = built.pre;
  1351. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  1352. return view;
  1353. }
  1354. // Get a {top, bottom, left, right} box (in line-local coordinates)
  1355. // for a given character.
  1356. function measureChar(cm, line, ch, bias) {
  1357. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  1358. }
  1359. // Find a line view that corresponds to the given line number.
  1360. function findViewForLine(cm, lineN) {
  1361. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  1362. return cm.display.view[findViewIndex(cm, lineN)];
  1363. var ext = cm.display.externalMeasured;
  1364. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  1365. return ext;
  1366. }
  1367. // Measurement can be split in two steps, the set-up work that
  1368. // applies to the whole line, and the measurement of the actual
  1369. // character. Functions like coordsChar, that need to do a lot of
  1370. // measurements in a row, can thus ensure that the set-up work is
  1371. // only done once.
  1372. function prepareMeasureForLine(cm, line) {
  1373. var lineN = lineNo(line);
  1374. var view = findViewForLine(cm, lineN);
  1375. if (view && !view.text)
  1376. view = null;
  1377. else if (view && view.changes)
  1378. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  1379. if (!view)
  1380. view = updateExternalMeasurement(cm, line);
  1381. var info = mapFromLineView(view, line, lineN);
  1382. return {
  1383. line: line, view: view, rect: null,
  1384. map: info.map, cache: info.cache, before: info.before,
  1385. hasHeights: false
  1386. };
  1387. }
  1388. // Given a prepared measurement object, measures the position of an
  1389. // actual character (or fetches it from the cache).
  1390. function measureCharPrepared(cm, prepared, ch, bias) {
  1391. if (prepared.before) ch = -1;
  1392. var key = ch + (bias || ""), found;
  1393. if (prepared.cache.hasOwnProperty(key)) {
  1394. found = prepared.cache[key];
  1395. } else {
  1396. if (!prepared.rect)
  1397. prepared.rect = prepared.view.text.getBoundingClientRect();
  1398. if (!prepared.hasHeights) {
  1399. ensureLineHeights(cm, prepared.view, prepared.rect);
  1400. prepared.hasHeights = true;
  1401. }
  1402. found = measureCharInner(cm, prepared, ch, bias);
  1403. if (!found.bogus) prepared.cache[key] = found;
  1404. }
  1405. return {left: found.left, right: found.right, top: found.top, bottom: found.bottom};
  1406. }
  1407. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  1408. function measureCharInner(cm, prepared, ch, bias) {
  1409. var map = prepared.map;
  1410. var node, start, end, collapse;
  1411. // First, search the line map for the text node corresponding to,
  1412. // or closest to, the target character.
  1413. for (var i = 0; i < map.length; i += 3) {
  1414. var mStart = map[i], mEnd = map[i + 1];
  1415. if (ch < mStart) {
  1416. start = 0; end = 1;
  1417. collapse = "left";
  1418. } else if (ch < mEnd) {
  1419. start = ch - mStart;
  1420. end = start + 1;
  1421. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  1422. end = mEnd - mStart;
  1423. start = end - 1;
  1424. if (ch >= mEnd) collapse = "right";
  1425. }
  1426. if (start != null) {
  1427. node = map[i + 2];
  1428. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  1429. collapse = bias;
  1430. if (bias == "left" && start == 0)
  1431. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  1432. node = map[(i -= 3) + 2];
  1433. collapse = "left";
  1434. }
  1435. if (bias == "right" && start == mEnd - mStart)
  1436. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  1437. node = map[(i += 3) + 2];
  1438. collapse = "right";
  1439. }
  1440. break;
  1441. }
  1442. }
  1443. var rect;
  1444. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  1445. while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
  1446. while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
  1447. if (ie_upto8 && start == 0 && end == mEnd - mStart) {
  1448. rect = node.parentNode.getBoundingClientRect();
  1449. } else if (ie && cm.options.lineWrapping) {
  1450. var rects = range(node, start, end).getClientRects();
  1451. if (rects.length)
  1452. rect = rects[bias == "right" ? rects.length - 1 : 0];
  1453. else
  1454. rect = nullRect;
  1455. } else {
  1456. rect = range(node, start, end).getBoundingClientRect();
  1457. }
  1458. } else { // If it is a widget, simply get the box for the whole widget.
  1459. if (start > 0) collapse = bias = "right";
  1460. var rects;
  1461. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  1462. rect = rects[bias == "right" ? rects.length - 1 : 0];
  1463. else
  1464. rect = node.getBoundingClientRect();
  1465. }
  1466. if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) {
  1467. var rSpan = node.parentNode.getClientRects()[0];
  1468. if (rSpan)
  1469. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  1470. else
  1471. rect = nullRect;
  1472. }
  1473. var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top;
  1474. var heights = prepared.view.measure.heights;
  1475. for (var i = 0; i < heights.length - 1; i++)
  1476. if (bot < heights[i]) break;
  1477. top = i ? heights[i - 1] : 0; bot = heights[i];
  1478. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  1479. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  1480. top: top, bottom: bot};
  1481. if (!rect.left && !rect.right) result.bogus = true;
  1482. return result;
  1483. }
  1484. function clearLineMeasurementCacheFor(lineView) {
  1485. if (lineView.measure) {
  1486. lineView.measure.cache = {};
  1487. lineView.measure.heights = null;
  1488. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  1489. lineView.measure.caches[i] = {};
  1490. }
  1491. }
  1492. function clearLineMeasurementCache(cm) {
  1493. cm.display.externalMeasure = null;
  1494. removeChildren(cm.display.lineMeasure);
  1495. for (var i = 0; i < cm.display.view.length; i++)
  1496. clearLineMeasurementCacheFor(cm.display.view[i]);
  1497. }
  1498. function clearCaches(cm) {
  1499. clearLineMeasurementCache(cm);
  1500. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  1501. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  1502. cm.display.lineNumChars = null;
  1503. }
  1504. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  1505. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  1506. // Converts a {top, bottom, left, right} box from line-local
  1507. // coordinates into another coordinate system. Context may be one of
  1508. // "line", "div" (display.lineDiv), "local"/null (editor), or "page".
  1509. function intoCoordSystem(cm, lineObj, rect, context) {
  1510. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  1511. var size = widgetHeight(lineObj.widgets[i]);
  1512. rect.top += size; rect.bottom += size;
  1513. }
  1514. if (context == "line") return rect;
  1515. if (!context) context = "local";
  1516. var yOff = heightAtLine(lineObj);
  1517. if (context == "local") yOff += paddingTop(cm.display);
  1518. else yOff -= cm.display.viewOffset;
  1519. if (context == "page" || context == "window") {
  1520. var lOff = cm.display.lineSpace.getBoundingClientRect();
  1521. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  1522. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  1523. rect.left += xOff; rect.right += xOff;
  1524. }
  1525. rect.top += yOff; rect.bottom += yOff;
  1526. return rect;
  1527. }
  1528. // Coverts a box from "div" coords to another coordinate system.
  1529. // Context may be "window", "page", "div", or "local"/null.
  1530. function fromCoordSystem(cm, coords, context) {
  1531. if (context == "div") return coords;
  1532. var left = coords.left, top = coords.top;
  1533. // First move into "page" coordinate system
  1534. if (context == "page") {
  1535. left -= pageScrollX();
  1536. top -= pageScrollY();
  1537. } else if (context == "local" || !context) {
  1538. var localBox = cm.display.sizer.getBoundingClientRect();
  1539. left += localBox.left;
  1540. top += localBox.top;
  1541. }
  1542. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  1543. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  1544. }
  1545. function charCoords(cm, pos, context, lineObj, bias) {
  1546. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  1547. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  1548. }
  1549. // Returns a box for a given cursor position, which may have an
  1550. // 'other' property containing the position of the secondary cursor
  1551. // on a bidi boundary.
  1552. function cursorCoords(cm, pos, context, lineObj, preparedMeasure) {
  1553. lineObj = lineObj || getLine(cm.doc, pos.line);
  1554. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  1555. function get(ch, right) {
  1556. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left");
  1557. if (right) m.left = m.right; else m.right = m.left;
  1558. return intoCoordSystem(cm, lineObj, m, context);
  1559. }
  1560. function getBidi(ch, partPos) {
  1561. var part = order[partPos], right = part.level % 2;
  1562. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  1563. part = order[--partPos];
  1564. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  1565. right = true;
  1566. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  1567. part = order[++partPos];
  1568. ch = bidiLeft(part) - part.level % 2;
  1569. right = false;
  1570. }
  1571. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  1572. return get(ch, right);
  1573. }
  1574. var order = getOrder(lineObj), ch = pos.ch;
  1575. if (!order) return get(ch);
  1576. var partPos = getBidiPartAt(order, ch);
  1577. var val = getBidi(ch, partPos);
  1578. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  1579. return val;
  1580. }
  1581. // Used to cheaply estimate the coordinates for a position. Used for
  1582. // intermediate scroll updates.
  1583. function estimateCoords(cm, pos) {
  1584. var left = 0, pos = clipPos(cm.doc, pos);
  1585. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  1586. var lineObj = getLine(cm.doc, pos.line);
  1587. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  1588. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  1589. }
  1590. // Positions returned by coordsChar contain some extra information.
  1591. // xRel is the relative x position of the input coordinates compared
  1592. // to the found position (so xRel > 0 means the coordinates are to
  1593. // the right of the character position, for example). When outside
  1594. // is true, that means the coordinates lie outside the line's
  1595. // vertical range.
  1596. function PosWithInfo(line, ch, outside, xRel) {
  1597. var pos = Pos(line, ch);
  1598. pos.xRel = xRel;
  1599. if (outside) pos.outside = true;
  1600. return pos;
  1601. }
  1602. // Compute the character position closest to the given coordinates.
  1603. // Input must be lineSpace-local ("div" coordinate system).
  1604. function coordsChar(cm, x, y) {
  1605. var doc = cm.doc;
  1606. y += cm.display.viewOffset;
  1607. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  1608. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  1609. if (lineN > last)
  1610. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  1611. if (x < 0) x = 0;
  1612. var lineObj = getLine(doc, lineN);
  1613. for (;;) {
  1614. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  1615. var merged = collapsedSpanAtEnd(lineObj);
  1616. var mergedPos = merged && merged.find(0, true);
  1617. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  1618. lineN = lineNo(lineObj = mergedPos.to.line);
  1619. else
  1620. return found;
  1621. }
  1622. }
  1623. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  1624. var innerOff = y - heightAtLine(lineObj);
  1625. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  1626. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  1627. function getX(ch) {
  1628. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  1629. wrongLine = true;
  1630. if (innerOff > sp.bottom) return sp.left - adjust;
  1631. else if (innerOff < sp.top) return sp.left + adjust;
  1632. else wrongLine = false;
  1633. return sp.left;
  1634. }
  1635. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  1636. var from = lineLeft(lineObj), to = lineRight(lineObj);
  1637. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  1638. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  1639. // Do a binary search between these bounds.
  1640. for (;;) {
  1641. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  1642. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  1643. var xDiff = x - (ch == from ? fromX : toX);
  1644. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  1645. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  1646. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  1647. return pos;
  1648. }
  1649. var step = Math.ceil(dist / 2), middle = from + step;
  1650. if (bidi) {
  1651. middle = from;
  1652. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  1653. }
  1654. var middleX = getX(middle);
  1655. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  1656. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  1657. }
  1658. }
  1659. var measureText;
  1660. // Compute the default text height.
  1661. function textHeight(display) {
  1662. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  1663. if (measureText == null) {
  1664. measureText = elt("pre");
  1665. // Measure a bunch of lines, for browsers that compute
  1666. // fractional heights.
  1667. for (var i = 0; i < 49; ++i) {
  1668. measureText.appendChild(document.createTextNode("x"));
  1669. measureText.appendChild(elt("br"));
  1670. }
  1671. measureText.appendChild(document.createTextNode("x"));
  1672. }
  1673. removeChildrenAndAdd(display.measure, measureText);
  1674. var height = measureText.offsetHeight / 50;
  1675. if (height > 3) display.cachedTextHeight = height;
  1676. removeChildren(display.measure);
  1677. return height || 1;
  1678. }
  1679. // Compute the default character width.
  1680. function charWidth(display) {
  1681. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  1682. var anchor = elt("span", "xxxxxxxxxx");
  1683. var pre = elt("pre", [anchor]);
  1684. removeChildrenAndAdd(display.measure, pre);
  1685. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  1686. if (width > 2) display.cachedCharWidth = width;
  1687. return width || 10;
  1688. }
  1689. // OPERATIONS
  1690. // Operations are used to wrap a series of changes to the editor
  1691. // state in such a way that each change won't have to update the
  1692. // cursor and display (which would be awkward, slow, and
  1693. // error-prone). Instead, display updates are batched and then all
  1694. // combined and executed at once.
  1695. var nextOpId = 0;
  1696. // Start a new operation.
  1697. function startOperation(cm) {
  1698. cm.curOp = {
  1699. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  1700. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  1701. forceUpdate: false, // Used to force a redraw
  1702. updateInput: null, // Whether to reset the input textarea
  1703. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  1704. changeObjs: null, // Accumulated changes, for firing change events
  1705. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  1706. selectionChanged: false, // Whether the selection needs to be redrawn
  1707. updateMaxLine: false, // Set when the widest line needs to be determined anew
  1708. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  1709. scrollToPos: null, // Used to scroll to a specific position
  1710. id: ++nextOpId // Unique ID
  1711. };
  1712. if (!delayedCallbackDepth++) delayedCallbacks = [];
  1713. }
  1714. // Finish an operation, updating the display and signalling delayed events
  1715. function endOperation(cm) {
  1716. var op = cm.curOp, doc = cm.doc, display = cm.display;
  1717. cm.curOp = null;
  1718. if (op.updateMaxLine) findMaxLine(cm);
  1719. // If it looks like an update might be needed, call updateDisplay
  1720. if (op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  1721. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  1722. op.scrollToPos.to.line >= display.viewTo) ||
  1723. display.maxLineChanged && cm.options.lineWrapping) {
  1724. var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  1725. if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
  1726. }
  1727. // If no update was run, but the selection changed, redraw that.
  1728. if (!updated && op.selectionChanged) updateSelection(cm);
  1729. if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm);
  1730. // Propagate the scroll position to the actual DOM scroller
  1731. if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) {
  1732. var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  1733. display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
  1734. }
  1735. if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) {
  1736. var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  1737. display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
  1738. alignHorizontally(cm);
  1739. }
  1740. // If we need to scroll a specific position into view, do so.
  1741. if (op.scrollToPos) {
  1742. var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
  1743. clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
  1744. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  1745. }
  1746. if (op.selectionChanged) restartBlink(cm);
  1747. if (cm.state.focused && op.updateInput)
  1748. resetInput(cm, op.typing);
  1749. // Fire events for markers that are hidden/unidden by editing or
  1750. // undoing
  1751. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  1752. if (hidden) for (var i = 0; i < hidden.length; ++i)
  1753. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  1754. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  1755. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  1756. var delayed;
  1757. if (!--delayedCallbackDepth) {
  1758. delayed = delayedCallbacks;
  1759. delayedCallbacks = null;
  1760. }
  1761. // Fire change events, and delayed event handlers
  1762. if (op.changeObjs)
  1763. signal(cm, "changes", cm, op.changeObjs);
  1764. if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
  1765. if (op.cursorActivityHandlers)
  1766. for (var i = 0; i < op.cursorActivityHandlers.length; i++)
  1767. op.cursorActivityHandlers[i](cm);
  1768. }
  1769. // Run the given function in an operation
  1770. function runInOp(cm, f) {
  1771. if (cm.curOp) return f();
  1772. startOperation(cm);
  1773. try { return f(); }
  1774. finally { endOperation(cm); }
  1775. }
  1776. // Wraps a function in an operation. Returns the wrapped function.
  1777. function operation(cm, f) {
  1778. return function() {
  1779. if (cm.curOp) return f.apply(cm, arguments);
  1780. startOperation(cm);
  1781. try { return f.apply(cm, arguments); }
  1782. finally { endOperation(cm); }
  1783. };
  1784. }
  1785. // Used to add methods to editor and doc instances, wrapping them in
  1786. // operations.
  1787. function methodOp(f) {
  1788. return function() {
  1789. if (this.curOp) return f.apply(this, arguments);
  1790. startOperation(this);
  1791. try { return f.apply(this, arguments); }
  1792. finally { endOperation(this); }
  1793. };
  1794. }
  1795. function docMethodOp(f) {
  1796. return function() {
  1797. var cm = this.cm;
  1798. if (!cm || cm.curOp) return f.apply(this, arguments);
  1799. startOperation(cm);
  1800. try { return f.apply(this, arguments); }
  1801. finally { endOperation(cm); }
  1802. };
  1803. }
  1804. // VIEW TRACKING
  1805. // These objects are used to represent the visible (currently drawn)
  1806. // part of the document. A LineView may correspond to multiple
  1807. // logical lines, if those are connected by collapsed ranges.
  1808. function LineView(doc, line, lineN) {
  1809. // The starting line
  1810. this.line = line;
  1811. // Continuing lines, if any
  1812. this.rest = visualLineContinued(line);
  1813. // Number of logical lines in this visual line
  1814. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1815. this.node = this.text = null;
  1816. this.hidden = lineIsHidden(doc, line);
  1817. }
  1818. // Create a range of LineView objects for the given lines.
  1819. function buildViewArray(cm, from, to) {
  1820. var array = [], nextPos;
  1821. for (var pos = from; pos < to; pos = nextPos) {
  1822. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1823. nextPos = pos + view.size;
  1824. array.push(view);
  1825. }
  1826. return array;
  1827. }
  1828. // Updates the display.view data structure for a given change to the
  1829. // document. From and to are in pre-change coordinates. Lendiff is
  1830. // the amount of lines added or subtracted by the change. This is
  1831. // used for changes that span multiple lines, or change the way
  1832. // lines are divided into visual lines. regLineChange (below)
  1833. // registers single-line changes.
  1834. function regChange(cm, from, to, lendiff) {
  1835. if (from == null) from = cm.doc.first;
  1836. if (to == null) to = cm.doc.first + cm.doc.size;
  1837. if (!lendiff) lendiff = 0;
  1838. var display = cm.display;
  1839. if (lendiff && to < display.viewTo &&
  1840. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  1841. display.updateLineNumbers = from;
  1842. cm.curOp.viewChanged = true;
  1843. if (from >= display.viewTo) { // Change after
  1844. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  1845. resetView(cm);
  1846. } else if (to <= display.viewFrom) { // Change before
  1847. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  1848. resetView(cm);
  1849. } else {
  1850. display.viewFrom += lendiff;
  1851. display.viewTo += lendiff;
  1852. }
  1853. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  1854. resetView(cm);
  1855. } else if (from <= display.viewFrom) { // Top overlap
  1856. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  1857. if (cut) {
  1858. display.view = display.view.slice(cut.index);
  1859. display.viewFrom = cut.lineN;
  1860. display.viewTo += lendiff;
  1861. } else {
  1862. resetView(cm);
  1863. }
  1864. } else if (to >= display.viewTo) { // Bottom overlap
  1865. var cut = viewCuttingPoint(cm, from, from, -1);
  1866. if (cut) {
  1867. display.view = display.view.slice(0, cut.index);
  1868. display.viewTo = cut.lineN;
  1869. } else {
  1870. resetView(cm);
  1871. }
  1872. } else { // Gap in the middle
  1873. var cutTop = viewCuttingPoint(cm, from, from, -1);
  1874. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  1875. if (cutTop && cutBot) {
  1876. display.view = display.view.slice(0, cutTop.index)
  1877. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  1878. .concat(display.view.slice(cutBot.index));
  1879. display.viewTo += lendiff;
  1880. } else {
  1881. resetView(cm);
  1882. }
  1883. }
  1884. var ext = display.externalMeasured;
  1885. if (ext) {
  1886. if (to < ext.lineN)
  1887. ext.lineN += lendiff;
  1888. else if (from < ext.lineN + ext.size)
  1889. display.externalMeasured = null;
  1890. }
  1891. }
  1892. // Register a change to a single line. Type must be one of "text",
  1893. // "gutter", "class", "widget"
  1894. function regLineChange(cm, line, type) {
  1895. cm.curOp.viewChanged = true;
  1896. var display = cm.display, ext = cm.display.externalMeasured;
  1897. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  1898. display.externalMeasured = null;
  1899. if (line < display.viewFrom || line >= display.viewTo) return;
  1900. var lineView = display.view[findViewIndex(cm, line)];
  1901. if (lineView.node == null) return;
  1902. var arr = lineView.changes || (lineView.changes = []);
  1903. if (indexOf(arr, type) == -1) arr.push(type);
  1904. }
  1905. // Clear the view.
  1906. function resetView(cm) {
  1907. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  1908. cm.display.view = [];
  1909. cm.display.viewOffset = 0;
  1910. }
  1911. // Find the view element corresponding to a given line. Return null
  1912. // when the line isn't visible.
  1913. function findViewIndex(cm, n) {
  1914. if (n >= cm.display.viewTo) return null;
  1915. n -= cm.display.viewFrom;
  1916. if (n < 0) return null;
  1917. var view = cm.display.view;
  1918. for (var i = 0; i < view.length; i++) {
  1919. n -= view[i].size;
  1920. if (n < 0) return i;
  1921. }
  1922. }
  1923. function viewCuttingPoint(cm, oldN, newN, dir) {
  1924. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  1925. if (!sawCollapsedSpans) return {index: index, lineN: newN};
  1926. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  1927. n += view[i].size;
  1928. if (n != oldN) {
  1929. if (dir > 0) {
  1930. if (index == view.length - 1) return null;
  1931. diff = (n + view[index].size) - oldN;
  1932. index++;
  1933. } else {
  1934. diff = n - oldN;
  1935. }
  1936. oldN += diff; newN += diff;
  1937. }
  1938. while (visualLineNo(cm.doc, newN) != newN) {
  1939. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  1940. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  1941. index += dir;
  1942. }
  1943. return {index: index, lineN: newN};
  1944. }
  1945. // Force the view to cover a given range, adding empty view element
  1946. // or clipping off existing ones as needed.
  1947. function adjustView(cm, from, to) {
  1948. var display = cm.display, view = display.view;
  1949. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  1950. display.view = buildViewArray(cm, from, to);
  1951. display.viewFrom = from;
  1952. } else {
  1953. if (display.viewFrom > from)
  1954. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  1955. else if (display.viewFrom < from)
  1956. display.view = display.view.slice(findViewIndex(cm, from));
  1957. display.viewFrom = from;
  1958. if (display.viewTo < to)
  1959. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  1960. else if (display.viewTo > to)
  1961. display.view = display.view.slice(0, findViewIndex(cm, to));
  1962. }
  1963. display.viewTo = to;
  1964. }
  1965. // Count the number of lines in the view whose DOM representation is
  1966. // out of date (or nonexistent).
  1967. function countDirtyView(cm) {
  1968. var view = cm.display.view, dirty = 0;
  1969. for (var i = 0; i < view.length; i++) {
  1970. var lineView = view[i];
  1971. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  1972. }
  1973. return dirty;
  1974. }
  1975. // INPUT HANDLING
  1976. // Poll for input changes, using the normal rate of polling. This
  1977. // runs as long as the editor is focused.
  1978. function slowPoll(cm) {
  1979. if (cm.display.pollingFast) return;
  1980. cm.display.poll.set(cm.options.pollInterval, function() {
  1981. readInput(cm);
  1982. if (cm.state.focused) slowPoll(cm);
  1983. });
  1984. }
  1985. // When an event has just come in that is likely to add or change
  1986. // something in the input textarea, we poll faster, to ensure that
  1987. // the change appears on the screen quickly.
  1988. function fastPoll(cm) {
  1989. var missed = false;
  1990. cm.display.pollingFast = true;
  1991. function p() {
  1992. var changed = readInput(cm);
  1993. if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
  1994. else {cm.display.pollingFast = false; slowPoll(cm);}
  1995. }
  1996. cm.display.poll.set(20, p);
  1997. }
  1998. // Read input from the textarea, and update the document to match.
  1999. // When something is selected, it is present in the textarea, and
  2000. // selected (unless it is huge, in which case a placeholder is
  2001. // used). When nothing is selected, the cursor sits after previously
  2002. // seen text (can be empty), which is stored in prevInput (we must
  2003. // not reset the textarea when typing, because that breaks IME).
  2004. function readInput(cm) {
  2005. var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
  2006. // Since this is called a *lot*, try to bail out as cheaply as
  2007. // possible when it is clear that nothing happened. hasSelection
  2008. // will be the case when there is a lot of text in the textarea,
  2009. // in which case reading its value would be expensive.
  2010. if (!cm.state.focused || (hasSelection(input) && !prevInput) || isReadOnly(cm) || cm.options.disableInput)
  2011. return false;
  2012. // See paste handler for more on the fakedLastChar kludge
  2013. if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
  2014. input.value = input.value.substring(0, input.value.length - 1);
  2015. cm.state.fakedLastChar = false;
  2016. }
  2017. var text = input.value;
  2018. // If nothing changed, bail.
  2019. if (text == prevInput && !cm.somethingSelected()) return false;
  2020. // Work around nonsensical selection resetting in IE9/10
  2021. if (ie && !ie_upto8 && cm.display.inputHasSelection === text) {
  2022. resetInput(cm);
  2023. return false;
  2024. }
  2025. var withOp = !cm.curOp;
  2026. if (withOp) startOperation(cm);
  2027. cm.display.shift = false;
  2028. // Find the part of the input that is actually new
  2029. var same = 0, l = Math.min(prevInput.length, text.length);
  2030. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  2031. var inserted = text.slice(same), textLines = splitLines(inserted);
  2032. // When pasing N lines into N selections, insert one line per selection
  2033. var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length;
  2034. // Normal behavior is to insert the new text into every selection
  2035. for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
  2036. var range = doc.sel.ranges[i];
  2037. var from = range.from(), to = range.to();
  2038. // Handle deletion
  2039. if (same < prevInput.length)
  2040. from = Pos(from.line, from.ch - (prevInput.length - same));
  2041. // Handle overwrite
  2042. else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
  2043. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  2044. var updateInput = cm.curOp.updateInput;
  2045. var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines,
  2046. origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
  2047. makeChange(cm.doc, changeEvent);
  2048. signalLater(cm, "inputRead", cm, changeEvent);
  2049. // When an 'electric' character is inserted, immediately trigger a reindent
  2050. if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
  2051. cm.options.smartIndent && range.head.ch < 100 &&
  2052. (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
  2053. var mode = cm.getModeAt(range.head);
  2054. if (mode.electricChars) {
  2055. for (var j = 0; j < mode.electricChars.length; j++)
  2056. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  2057. indentLine(cm, range.head.line, "smart");
  2058. break;
  2059. }
  2060. } else if (mode.electricInput) {
  2061. var end = changeEnd(changeEvent);
  2062. if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
  2063. indentLine(cm, range.head.line, "smart");
  2064. }
  2065. }
  2066. }
  2067. ensureCursorVisible(cm);
  2068. cm.curOp.updateInput = updateInput;
  2069. cm.curOp.typing = true;
  2070. // Don't leave long text in the textarea, since it makes further polling slow
  2071. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
  2072. else cm.display.prevInput = text;
  2073. if (withOp) endOperation(cm);
  2074. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  2075. return true;
  2076. }
  2077. // Reset the input to correspond to the selection (or to be empty,
  2078. // when not typing and nothing is selected)
  2079. function resetInput(cm, typing) {
  2080. var minimal, selected, doc = cm.doc;
  2081. if (cm.somethingSelected()) {
  2082. cm.display.prevInput = "";
  2083. var range = doc.sel.primary();
  2084. minimal = hasCopyEvent &&
  2085. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  2086. var content = minimal ? "-" : selected || cm.getSelection();
  2087. cm.display.input.value = content;
  2088. if (cm.state.focused) selectInput(cm.display.input);
  2089. if (ie && !ie_upto8) cm.display.inputHasSelection = content;
  2090. } else if (!typing) {
  2091. cm.display.prevInput = cm.display.input.value = "";
  2092. if (ie && !ie_upto8) cm.display.inputHasSelection = null;
  2093. }
  2094. cm.display.inaccurateSelection = minimal;
  2095. }
  2096. function focusInput(cm) {
  2097. if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))
  2098. cm.display.input.focus();
  2099. }
  2100. function ensureFocus(cm) {
  2101. if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
  2102. }
  2103. function isReadOnly(cm) {
  2104. return cm.options.readOnly || cm.doc.cantEdit;
  2105. }
  2106. // EVENT HANDLERS
  2107. // Attach the necessary event handlers when initializing the editor
  2108. function registerEventHandlers(cm) {
  2109. var d = cm.display;
  2110. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  2111. // Older IE's will not fire a second mousedown for a double click
  2112. if (ie_upto10)
  2113. on(d.scroller, "dblclick", operation(cm, function(e) {
  2114. if (signalDOMEvent(cm, e)) return;
  2115. var pos = posFromMouse(cm, e);
  2116. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  2117. e_preventDefault(e);
  2118. var word = findWordAt(cm.doc, pos);
  2119. extendSelection(cm.doc, word.anchor, word.head);
  2120. }));
  2121. else
  2122. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  2123. // Prevent normal selection in the editor (we handle our own)
  2124. on(d.lineSpace, "selectstart", function(e) {
  2125. if (!eventInWidget(d, e)) e_preventDefault(e);
  2126. });
  2127. // Some browsers fire contextmenu *after* opening the menu, at
  2128. // which point we can't mess with it anymore. Context menu is
  2129. // handled in onMouseDown for these browsers.
  2130. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  2131. // Sync scrolling between fake scrollbars and real scrollable
  2132. // area, ensure viewport is updated when scrolling.
  2133. on(d.scroller, "scroll", function() {
  2134. if (d.scroller.clientHeight) {
  2135. setScrollTop(cm, d.scroller.scrollTop);
  2136. setScrollLeft(cm, d.scroller.scrollLeft, true);
  2137. signal(cm, "scroll", cm);
  2138. }
  2139. });
  2140. on(d.scrollbarV, "scroll", function() {
  2141. if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
  2142. });
  2143. on(d.scrollbarH, "scroll", function() {
  2144. if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
  2145. });
  2146. // Listen to wheel events in order to try and update the viewport on time.
  2147. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  2148. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  2149. // Prevent clicks in the scrollbars from killing focus
  2150. function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
  2151. on(d.scrollbarH, "mousedown", reFocus);
  2152. on(d.scrollbarV, "mousedown", reFocus);
  2153. // Prevent wrapper from ever scrolling
  2154. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  2155. // When the window resizes, we need to refresh active editors.
  2156. var resizeTimer;
  2157. function onResize() {
  2158. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  2159. resizeTimer = null;
  2160. // Might be a text scaling operation, clear size caches.
  2161. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = knownScrollbarWidth = null;
  2162. cm.setSize();
  2163. }, 100);
  2164. }
  2165. on(window, "resize", onResize);
  2166. // The above handler holds on to the editor and its data
  2167. // structures. Here we poll to unregister it when the editor is no
  2168. // longer in the document, so that it can be garbage-collected.
  2169. function unregister() {
  2170. if (contains(document.body, d.wrapper)) setTimeout(unregister, 5000);
  2171. else off(window, "resize", onResize);
  2172. }
  2173. setTimeout(unregister, 5000);
  2174. on(d.input, "keyup", operation(cm, onKeyUp));
  2175. on(d.input, "input", function() {
  2176. if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
  2177. fastPoll(cm);
  2178. });
  2179. on(d.input, "keydown", operation(cm, onKeyDown));
  2180. on(d.input, "keypress", operation(cm, onKeyPress));
  2181. on(d.input, "focus", bind(onFocus, cm));
  2182. on(d.input, "blur", bind(onBlur, cm));
  2183. function drag_(e) {
  2184. if (!signalDOMEvent(cm, e)) e_stop(e);
  2185. }
  2186. if (cm.options.dragDrop) {
  2187. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  2188. on(d.scroller, "dragenter", drag_);
  2189. on(d.scroller, "dragover", drag_);
  2190. on(d.scroller, "drop", operation(cm, onDrop));
  2191. }
  2192. on(d.scroller, "paste", function(e) {
  2193. if (eventInWidget(d, e)) return;
  2194. cm.state.pasteIncoming = true;
  2195. focusInput(cm);
  2196. fastPoll(cm);
  2197. });
  2198. on(d.input, "paste", function() {
  2199. // Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
  2200. // Add a char to the end of textarea before paste occur so that
  2201. // selection doesn't span to the end of textarea.
  2202. if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
  2203. var start = d.input.selectionStart, end = d.input.selectionEnd;
  2204. d.input.value += "$";
  2205. d.input.selectionStart = start;
  2206. d.input.selectionEnd = end;
  2207. cm.state.fakedLastChar = true;
  2208. }
  2209. cm.state.pasteIncoming = true;
  2210. fastPoll(cm);
  2211. });
  2212. function prepareCopyCut(e) {
  2213. if (cm.somethingSelected()) {
  2214. if (d.inaccurateSelection) {
  2215. d.prevInput = "";
  2216. d.inaccurateSelection = false;
  2217. d.input.value = cm.getSelection();
  2218. selectInput(d.input);
  2219. }
  2220. } else {
  2221. var text = "", ranges = [];
  2222. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  2223. var line = cm.doc.sel.ranges[i].head.line;
  2224. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  2225. ranges.push(lineRange);
  2226. text += cm.getRange(lineRange.anchor, lineRange.head);
  2227. }
  2228. if (e.type == "cut") {
  2229. cm.setSelections(ranges, null, sel_dontScroll);
  2230. } else {
  2231. d.prevInput = "";
  2232. d.input.value = text;
  2233. selectInput(d.input);
  2234. }
  2235. }
  2236. if (e.type == "cut") cm.state.cutIncoming = true;
  2237. }
  2238. on(d.input, "cut", prepareCopyCut);
  2239. on(d.input, "copy", prepareCopyCut);
  2240. // Needed to handle Tab key in KHTML
  2241. if (khtml) on(d.sizer, "mouseup", function() {
  2242. if (activeElt() == d.input) d.input.blur();
  2243. focusInput(cm);
  2244. });
  2245. }
  2246. // MOUSE EVENTS
  2247. // Return true when the given mouse event happened in a widget
  2248. function eventInWidget(display, e) {
  2249. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2250. if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
  2251. }
  2252. }
  2253. // Given a mouse event, find the corresponding position. If liberal
  2254. // is false, it checks whether a gutter or scrollbar was clicked,
  2255. // and returns null if it was. forRect is used by rectangular
  2256. // selections, and tries to estimate a character position even for
  2257. // coordinates beyond the right of the text.
  2258. function posFromMouse(cm, e, liberal, forRect) {
  2259. var display = cm.display;
  2260. if (!liberal) {
  2261. var target = e_target(e);
  2262. if (target == display.scrollbarH || target == display.scrollbarV ||
  2263. target == display.scrollbarFiller || target == display.gutterFiller) return null;
  2264. }
  2265. var x, y, space = display.lineSpace.getBoundingClientRect();
  2266. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2267. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2268. catch (e) { return null; }
  2269. var coords = coordsChar(cm, x, y), line;
  2270. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2271. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2272. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2273. }
  2274. return coords;
  2275. }
  2276. // A mouse down can be a single click, double click, triple click,
  2277. // start of selection drag, start of text drag, new cursor
  2278. // (ctrl-click), rectangle drag (alt-drag), or xwin
  2279. // middle-click-paste. Or it might be a click on something we should
  2280. // not interfere with, such as a scrollbar or widget.
  2281. function onMouseDown(e) {
  2282. if (signalDOMEvent(this, e)) return;
  2283. var cm = this, display = cm.display;
  2284. display.shift = e.shiftKey;
  2285. if (eventInWidget(display, e)) {
  2286. if (!webkit) {
  2287. // Briefly turn off draggability, to allow widgets to do
  2288. // normal dragging things.
  2289. display.scroller.draggable = false;
  2290. setTimeout(function(){display.scroller.draggable = true;}, 100);
  2291. }
  2292. return;
  2293. }
  2294. if (clickInGutter(cm, e)) return;
  2295. var start = posFromMouse(cm, e);
  2296. window.focus();
  2297. switch (e_button(e)) {
  2298. case 1:
  2299. if (start)
  2300. leftButtonDown(cm, e, start);
  2301. else if (e_target(e) == display.scroller)
  2302. e_preventDefault(e);
  2303. break;
  2304. case 2:
  2305. if (webkit) cm.state.lastMiddleDown = +new Date;
  2306. if (start) extendSelection(cm.doc, start);
  2307. setTimeout(bind(focusInput, cm), 20);
  2308. e_preventDefault(e);
  2309. break;
  2310. case 3:
  2311. if (captureRightClick) onContextMenu(cm, e);
  2312. break;
  2313. }
  2314. }
  2315. var lastClick, lastDoubleClick;
  2316. function leftButtonDown(cm, e, start) {
  2317. setTimeout(bind(ensureFocus, cm), 0);
  2318. var now = +new Date, type;
  2319. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  2320. type = "triple";
  2321. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  2322. type = "double";
  2323. lastDoubleClick = {time: now, pos: start};
  2324. } else {
  2325. type = "single";
  2326. lastClick = {time: now, pos: start};
  2327. }
  2328. var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey;
  2329. if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) &&
  2330. type == "single" && sel.contains(start) > -1 && sel.somethingSelected())
  2331. leftButtonStartDrag(cm, e, start);
  2332. else
  2333. leftButtonSelect(cm, e, start, type, addNew);
  2334. }
  2335. // Start a text drag. When it ends, see if any dragging actually
  2336. // happen, and treat as a click if it didn't.
  2337. function leftButtonStartDrag(cm, e, start) {
  2338. var display = cm.display;
  2339. var dragEnd = operation(cm, function(e2) {
  2340. if (webkit) display.scroller.draggable = false;
  2341. cm.state.draggingText = false;
  2342. off(document, "mouseup", dragEnd);
  2343. off(display.scroller, "drop", dragEnd);
  2344. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  2345. e_preventDefault(e2);
  2346. extendSelection(cm.doc, start);
  2347. focusInput(cm);
  2348. // Work around unexplainable focus problem in IE9 (#2127)
  2349. if (ie_upto10 && !ie_upto8)
  2350. setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
  2351. }
  2352. });
  2353. // Let the drag handler handle this.
  2354. if (webkit) display.scroller.draggable = true;
  2355. cm.state.draggingText = dragEnd;
  2356. // IE's approach to draggable
  2357. if (display.scroller.dragDrop) display.scroller.dragDrop();
  2358. on(document, "mouseup", dragEnd);
  2359. on(display.scroller, "drop", dragEnd);
  2360. }
  2361. // Normal selection, as opposed to text dragging.
  2362. function leftButtonSelect(cm, e, start, type, addNew) {
  2363. var display = cm.display, doc = cm.doc;
  2364. e_preventDefault(e);
  2365. var ourRange, ourIndex, startSel = doc.sel;
  2366. if (addNew && !e.shiftKey) {
  2367. ourIndex = doc.sel.contains(start);
  2368. if (ourIndex > -1)
  2369. ourRange = doc.sel.ranges[ourIndex];
  2370. else
  2371. ourRange = new Range(start, start);
  2372. } else {
  2373. ourRange = doc.sel.primary();
  2374. }
  2375. if (e.altKey) {
  2376. type = "rect";
  2377. if (!addNew) ourRange = new Range(start, start);
  2378. start = posFromMouse(cm, e, true, true);
  2379. ourIndex = -1;
  2380. } else if (type == "double") {
  2381. var word = findWordAt(doc, start);
  2382. if (cm.display.shift || doc.extend)
  2383. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  2384. else
  2385. ourRange = word;
  2386. } else if (type == "triple") {
  2387. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  2388. if (cm.display.shift || doc.extend)
  2389. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  2390. else
  2391. ourRange = line;
  2392. } else {
  2393. ourRange = extendRange(doc, ourRange, start);
  2394. }
  2395. if (!addNew) {
  2396. ourIndex = 0;
  2397. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  2398. startSel = doc.sel;
  2399. } else if (ourIndex > -1) {
  2400. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  2401. } else {
  2402. ourIndex = doc.sel.ranges.length;
  2403. setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),
  2404. {scroll: false, origin: "*mouse"});
  2405. }
  2406. var lastPos = start;
  2407. function extendTo(pos) {
  2408. if (cmp(lastPos, pos) == 0) return;
  2409. lastPos = pos;
  2410. if (type == "rect") {
  2411. var ranges = [], tabSize = cm.options.tabSize;
  2412. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  2413. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  2414. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  2415. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  2416. line <= end; line++) {
  2417. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  2418. if (left == right)
  2419. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  2420. else if (text.length > leftPos)
  2421. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  2422. }
  2423. if (!ranges.length) ranges.push(new Range(start, start));
  2424. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), sel_mouse);
  2425. } else {
  2426. var oldRange = ourRange;
  2427. var anchor = oldRange.anchor, head = pos;
  2428. if (type != "single") {
  2429. if (type == "double")
  2430. var range = findWordAt(doc, pos);
  2431. else
  2432. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  2433. if (cmp(range.anchor, anchor) > 0) {
  2434. head = range.head;
  2435. anchor = minPos(oldRange.from(), range.anchor);
  2436. } else {
  2437. head = range.anchor;
  2438. anchor = maxPos(oldRange.to(), range.head);
  2439. }
  2440. }
  2441. var ranges = startSel.ranges.slice(0);
  2442. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  2443. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  2444. }
  2445. }
  2446. var editorSize = display.wrapper.getBoundingClientRect();
  2447. // Used to ensure timeout re-tries don't fire when another extend
  2448. // happened in the meantime (clearTimeout isn't reliable -- at
  2449. // least on Chrome, the timeouts still happen even when cleared,
  2450. // if the clear happens after their scheduled firing time).
  2451. var counter = 0;
  2452. function extend(e) {
  2453. var curCount = ++counter;
  2454. var cur = posFromMouse(cm, e, true, type == "rect");
  2455. if (!cur) return;
  2456. if (cmp(cur, lastPos) != 0) {
  2457. ensureFocus(cm);
  2458. extendTo(cur);
  2459. var visible = visibleLines(display, doc);
  2460. if (cur.line >= visible.to || cur.line < visible.from)
  2461. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  2462. } else {
  2463. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  2464. if (outside) setTimeout(operation(cm, function() {
  2465. if (counter != curCount) return;
  2466. display.scroller.scrollTop += outside;
  2467. extend(e);
  2468. }), 50);
  2469. }
  2470. }
  2471. function done(e) {
  2472. counter = Infinity;
  2473. e_preventDefault(e);
  2474. focusInput(cm);
  2475. off(document, "mousemove", move);
  2476. off(document, "mouseup", up);
  2477. doc.history.lastSelOrigin = null;
  2478. }
  2479. var move = operation(cm, function(e) {
  2480. if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e);
  2481. else extend(e);
  2482. });
  2483. var up = operation(cm, done);
  2484. on(document, "mousemove", move);
  2485. on(document, "mouseup", up);
  2486. }
  2487. // Determines whether an event happened in the gutter, and fires the
  2488. // handlers for the corresponding event.
  2489. function gutterEvent(cm, e, type, prevent, signalfn) {
  2490. try { var mX = e.clientX, mY = e.clientY; }
  2491. catch(e) { return false; }
  2492. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  2493. if (prevent) e_preventDefault(e);
  2494. var display = cm.display;
  2495. var lineBox = display.lineDiv.getBoundingClientRect();
  2496. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  2497. mY -= lineBox.top - display.viewOffset;
  2498. for (var i = 0; i < cm.options.gutters.length; ++i) {
  2499. var g = display.gutters.childNodes[i];
  2500. if (g && g.getBoundingClientRect().right >= mX) {
  2501. var line = lineAtHeight(cm.doc, mY);
  2502. var gutter = cm.options.gutters[i];
  2503. signalfn(cm, type, cm, line, gutter, e);
  2504. return e_defaultPrevented(e);
  2505. }
  2506. }
  2507. }
  2508. function clickInGutter(cm, e) {
  2509. return gutterEvent(cm, e, "gutterClick", true, signalLater);
  2510. }
  2511. // Kludge to work around strange IE behavior where it'll sometimes
  2512. // re-fire a series of drag-related events right after the drop (#1551)
  2513. var lastDrop = 0;
  2514. function onDrop(e) {
  2515. var cm = this;
  2516. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  2517. return;
  2518. e_preventDefault(e);
  2519. if (ie) lastDrop = +new Date;
  2520. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  2521. if (!pos || isReadOnly(cm)) return;
  2522. // Might be a file drop, in which case we simply extract the text
  2523. // and insert it.
  2524. if (files && files.length && window.FileReader && window.File) {
  2525. var n = files.length, text = Array(n), read = 0;
  2526. var loadFile = function(file, i) {
  2527. var reader = new FileReader;
  2528. reader.onload = operation(cm, function() {
  2529. text[i] = reader.result;
  2530. if (++read == n) {
  2531. pos = clipPos(cm.doc, pos);
  2532. var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
  2533. makeChange(cm.doc, change);
  2534. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  2535. }
  2536. });
  2537. reader.readAsText(file);
  2538. };
  2539. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  2540. } else { // Normal drop
  2541. // Don't do a replace if the drop happened inside of the selected text.
  2542. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  2543. cm.state.draggingText(e);
  2544. // Ensure the editor is re-focused
  2545. setTimeout(bind(focusInput, cm), 20);
  2546. return;
  2547. }
  2548. try {
  2549. var text = e.dataTransfer.getData("Text");
  2550. if (text) {
  2551. var selected = cm.state.draggingText && cm.listSelections();
  2552. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  2553. if (selected) for (var i = 0; i < selected.length; ++i)
  2554. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  2555. cm.replaceSelection(text, "around", "paste");
  2556. focusInput(cm);
  2557. }
  2558. }
  2559. catch(e){}
  2560. }
  2561. }
  2562. function onDragStart(cm, e) {
  2563. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  2564. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  2565. e.dataTransfer.setData("Text", cm.getSelection());
  2566. // Use dummy image instead of default browsers image.
  2567. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  2568. if (e.dataTransfer.setDragImage && !safari) {
  2569. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  2570. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  2571. if (presto) {
  2572. img.width = img.height = 1;
  2573. cm.display.wrapper.appendChild(img);
  2574. // Force a relayout, or Opera won't use our image for some obscure reason
  2575. img._top = img.offsetTop;
  2576. }
  2577. e.dataTransfer.setDragImage(img, 0, 0);
  2578. if (presto) img.parentNode.removeChild(img);
  2579. }
  2580. }
  2581. // SCROLL EVENTS
  2582. // Sync the scrollable area and scrollbars, ensure the viewport
  2583. // covers the visible area.
  2584. function setScrollTop(cm, val) {
  2585. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  2586. cm.doc.scrollTop = val;
  2587. if (!gecko) updateDisplay(cm, {top: val});
  2588. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  2589. if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
  2590. if (gecko) updateDisplay(cm);
  2591. startWorker(cm, 100);
  2592. }
  2593. // Sync scroller and scrollbar, ensure the gutter elements are
  2594. // aligned.
  2595. function setScrollLeft(cm, val, isScroller) {
  2596. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  2597. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  2598. cm.doc.scrollLeft = val;
  2599. alignHorizontally(cm);
  2600. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  2601. if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
  2602. }
  2603. // Since the delta values reported on mouse wheel events are
  2604. // unstandardized between browsers and even browser versions, and
  2605. // generally horribly unpredictable, this code starts by measuring
  2606. // the scroll effect that the first few mouse wheel events have,
  2607. // and, from that, detects the way it can convert deltas to pixel
  2608. // offsets afterwards.
  2609. //
  2610. // The reason we want to know the amount a wheel event will scroll
  2611. // is that it gives us a chance to update the display before the
  2612. // actual scrolling happens, reducing flickering.
  2613. var wheelSamples = 0, wheelPixelsPerUnit = null;
  2614. // Fill in a browser-detected starting value on browsers where we
  2615. // know one. These don't have to be accurate -- the result of them
  2616. // being wrong would just be a slight flicker on the first wheel
  2617. // scroll (if it is large enough).
  2618. if (ie) wheelPixelsPerUnit = -.53;
  2619. else if (gecko) wheelPixelsPerUnit = 15;
  2620. else if (chrome) wheelPixelsPerUnit = -.7;
  2621. else if (safari) wheelPixelsPerUnit = -1/3;
  2622. function onScrollWheel(cm, e) {
  2623. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  2624. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  2625. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  2626. else if (dy == null) dy = e.wheelDelta;
  2627. var display = cm.display, scroll = display.scroller;
  2628. // Quit if there's nothing to scroll here
  2629. if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
  2630. dy && scroll.scrollHeight > scroll.clientHeight)) return;
  2631. // Webkit browsers on OS X abort momentum scrolls when the target
  2632. // of the scroll event is removed from the scrollable element.
  2633. // This hack (see related code in patchDisplay) makes sure the
  2634. // element is kept around.
  2635. if (dy && mac && webkit) {
  2636. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  2637. for (var i = 0; i < view.length; i++) {
  2638. if (view[i].node == cur) {
  2639. cm.display.currentWheelTarget = cur;
  2640. break outer;
  2641. }
  2642. }
  2643. }
  2644. }
  2645. // On some browsers, horizontal scrolling will cause redraws to
  2646. // happen before the gutter has been realigned, causing it to
  2647. // wriggle around in a most unseemly way. When we have an
  2648. // estimated pixels/delta value, we just handle horizontal
  2649. // scrolling entirely here. It'll be slightly off from native, but
  2650. // better than glitching out.
  2651. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  2652. if (dy)
  2653. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  2654. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  2655. e_preventDefault(e);
  2656. display.wheelStartX = null; // Abort measurement, if in progress
  2657. return;
  2658. }
  2659. // 'Project' the visible viewport to cover the area that is being
  2660. // scrolled into view (if we know enough to estimate it).
  2661. if (dy && wheelPixelsPerUnit != null) {
  2662. var pixels = dy * wheelPixelsPerUnit;
  2663. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  2664. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  2665. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  2666. updateDisplay(cm, {top: top, bottom: bot});
  2667. }
  2668. if (wheelSamples < 20) {
  2669. if (display.wheelStartX == null) {
  2670. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  2671. display.wheelDX = dx; display.wheelDY = dy;
  2672. setTimeout(function() {
  2673. if (display.wheelStartX == null) return;
  2674. var movedX = scroll.scrollLeft - display.wheelStartX;
  2675. var movedY = scroll.scrollTop - display.wheelStartY;
  2676. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  2677. (movedX && display.wheelDX && movedX / display.wheelDX);
  2678. display.wheelStartX = display.wheelStartY = null;
  2679. if (!sample) return;
  2680. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  2681. ++wheelSamples;
  2682. }, 200);
  2683. } else {
  2684. display.wheelDX += dx; display.wheelDY += dy;
  2685. }
  2686. }
  2687. }
  2688. // KEY EVENTS
  2689. // Run a handler that was bound to a key.
  2690. function doHandleBinding(cm, bound, dropShift) {
  2691. if (typeof bound == "string") {
  2692. bound = commands[bound];
  2693. if (!bound) return false;
  2694. }
  2695. // Ensure previous input has been read, so that the handler sees a
  2696. // consistent view of the document
  2697. if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
  2698. var prevShift = cm.display.shift, done = false;
  2699. try {
  2700. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  2701. if (dropShift) cm.display.shift = false;
  2702. done = bound(cm) != Pass;
  2703. } finally {
  2704. cm.display.shift = prevShift;
  2705. cm.state.suppressEdits = false;
  2706. }
  2707. return done;
  2708. }
  2709. // Collect the currently active keymaps.
  2710. function allKeyMaps(cm) {
  2711. var maps = cm.state.keyMaps.slice(0);
  2712. if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
  2713. maps.push(cm.options.keyMap);
  2714. return maps;
  2715. }
  2716. var maybeTransition;
  2717. // Handle a key from the keydown event.
  2718. function handleKeyBinding(cm, e) {
  2719. // Handle automatic keymap transitions
  2720. var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
  2721. clearTimeout(maybeTransition);
  2722. if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
  2723. if (getKeyMap(cm.options.keyMap) == startMap) {
  2724. cm.options.keyMap = (next.call ? next.call(null, cm) : next);
  2725. keyMapChanged(cm);
  2726. }
  2727. }, 50);
  2728. var name = keyName(e, true), handled = false;
  2729. if (!name) return false;
  2730. var keymaps = allKeyMaps(cm);
  2731. if (e.shiftKey) {
  2732. // First try to resolve full name (including 'Shift-'). Failing
  2733. // that, see if there is a cursor-motion command (starting with
  2734. // 'go') bound to the keyname without 'Shift-'.
  2735. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
  2736. || lookupKey(name, keymaps, function(b) {
  2737. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  2738. return doHandleBinding(cm, b);
  2739. });
  2740. } else {
  2741. handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
  2742. }
  2743. if (handled) {
  2744. e_preventDefault(e);
  2745. restartBlink(cm);
  2746. signalLater(cm, "keyHandled", cm, name, e);
  2747. }
  2748. return handled;
  2749. }
  2750. // Handle a key from the keypress event
  2751. function handleCharBinding(cm, e, ch) {
  2752. var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
  2753. function(b) { return doHandleBinding(cm, b, true); });
  2754. if (handled) {
  2755. e_preventDefault(e);
  2756. restartBlink(cm);
  2757. signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
  2758. }
  2759. return handled;
  2760. }
  2761. var lastStoppedKey = null;
  2762. function onKeyDown(e) {
  2763. var cm = this;
  2764. ensureFocus(cm);
  2765. if (signalDOMEvent(cm, e)) return;
  2766. // IE does strange things with escape.
  2767. if (ie_upto10 && e.keyCode == 27) e.returnValue = false;
  2768. var code = e.keyCode;
  2769. cm.display.shift = code == 16 || e.shiftKey;
  2770. var handled = handleKeyBinding(cm, e);
  2771. if (presto) {
  2772. lastStoppedKey = handled ? code : null;
  2773. // Opera has no cut event... we try to at least catch the key combo
  2774. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  2775. cm.replaceSelection("", null, "cut");
  2776. }
  2777. // Turn mouse into crosshair when Alt is held on Mac.
  2778. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  2779. showCrossHair(cm);
  2780. }
  2781. function showCrossHair(cm) {
  2782. var lineDiv = cm.display.lineDiv;
  2783. addClass(lineDiv, "CodeMirror-crosshair");
  2784. function up(e) {
  2785. if (e.keyCode == 18 || !e.altKey) {
  2786. rmClass(lineDiv, "CodeMirror-crosshair");
  2787. off(document, "keyup", up);
  2788. off(document, "mouseover", up);
  2789. }
  2790. }
  2791. on(document, "keyup", up);
  2792. on(document, "mouseover", up);
  2793. }
  2794. function onKeyUp(e) {
  2795. if (signalDOMEvent(this, e)) return;
  2796. if (e.keyCode == 16) this.doc.sel.shift = false;
  2797. }
  2798. function onKeyPress(e) {
  2799. var cm = this;
  2800. if (signalDOMEvent(cm, e)) return;
  2801. var keyCode = e.keyCode, charCode = e.charCode;
  2802. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  2803. if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
  2804. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  2805. if (handleCharBinding(cm, e, ch)) return;
  2806. if (ie && !ie_upto8) cm.display.inputHasSelection = null;
  2807. fastPoll(cm);
  2808. }
  2809. // FOCUS/BLUR EVENTS
  2810. function onFocus(cm) {
  2811. if (cm.options.readOnly == "nocursor") return;
  2812. if (!cm.state.focused) {
  2813. signal(cm, "focus", cm);
  2814. cm.state.focused = true;
  2815. addClass(cm.display.wrapper, "CodeMirror-focused");
  2816. // The prevInput test prevents this from firing when a context
  2817. // menu is closed (since the resetInput would kill the
  2818. // select-all detection hack)
  2819. if (!cm.curOp && cm.display.selForContextMenu == cm.doc.sel) {
  2820. resetInput(cm);
  2821. if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
  2822. }
  2823. }
  2824. slowPoll(cm);
  2825. restartBlink(cm);
  2826. }
  2827. function onBlur(cm) {
  2828. if (cm.state.focused) {
  2829. signal(cm, "blur", cm);
  2830. cm.state.focused = false;
  2831. rmClass(cm.display.wrapper, "CodeMirror-focused");
  2832. }
  2833. clearInterval(cm.display.blinker);
  2834. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  2835. }
  2836. // CONTEXT MENU HANDLING
  2837. var detectingSelectAll;
  2838. // To make the context menu work, we need to briefly unhide the
  2839. // textarea (making it as unobtrusive as possible) to let the
  2840. // right-click take effect on it.
  2841. function onContextMenu(cm, e) {
  2842. if (signalDOMEvent(cm, e, "contextmenu")) return;
  2843. var display = cm.display;
  2844. if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
  2845. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  2846. if (!pos || presto) return; // Opera is difficult.
  2847. // Reset the current text selection only if the click is done outside of the selection
  2848. // and 'resetSelectionOnContextMenu' option is true.
  2849. var reset = cm.options.resetSelectionOnContextMenu;
  2850. if (reset && cm.doc.sel.contains(pos) == -1)
  2851. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  2852. var oldCSS = display.input.style.cssText;
  2853. display.inputDiv.style.position = "absolute";
  2854. display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  2855. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
  2856. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  2857. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  2858. focusInput(cm);
  2859. resetInput(cm);
  2860. // Adds "Select all" to context menu in FF
  2861. if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
  2862. display.selForContextMenu = cm.doc.sel;
  2863. // Select-all will be greyed out if there's nothing to select, so
  2864. // this adds a zero-width space so that we can later check whether
  2865. // it got selected.
  2866. function prepareSelectAllHack() {
  2867. if (display.input.selectionStart != null) {
  2868. var selected = cm.somethingSelected();
  2869. var extval = display.input.value = "\u200b" + (selected ? display.input.value : "");
  2870. display.prevInput = selected ? "" : "\u200b";
  2871. display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
  2872. }
  2873. }
  2874. function rehide() {
  2875. display.inputDiv.style.position = "relative";
  2876. display.input.style.cssText = oldCSS;
  2877. if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
  2878. slowPoll(cm);
  2879. // Try to detect the user choosing select-all
  2880. if (display.input.selectionStart != null) {
  2881. if (!ie || ie_upto8) prepareSelectAllHack();
  2882. clearTimeout(detectingSelectAll);
  2883. var i = 0, poll = function() {
  2884. if (display.selForContextMenu == cm.doc.sel && display.input.selectionStart == 0)
  2885. operation(cm, commands.selectAll)(cm);
  2886. else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
  2887. else resetInput(cm);
  2888. };
  2889. detectingSelectAll = setTimeout(poll, 200);
  2890. }
  2891. }
  2892. if (ie && !ie_upto8) prepareSelectAllHack();
  2893. if (captureRightClick) {
  2894. e_stop(e);
  2895. var mouseup = function() {
  2896. off(window, "mouseup", mouseup);
  2897. setTimeout(rehide, 20);
  2898. };
  2899. on(window, "mouseup", mouseup);
  2900. } else {
  2901. setTimeout(rehide, 50);
  2902. }
  2903. }
  2904. function contextMenuInGutter(cm, e) {
  2905. if (!hasHandler(cm, "gutterContextMenu")) return false;
  2906. return gutterEvent(cm, e, "gutterContextMenu", false, signal);
  2907. }
  2908. // UPDATING
  2909. // Compute the position of the end of a change (its 'to' property
  2910. // refers to the pre-change end).
  2911. var changeEnd = CodeMirror.changeEnd = function(change) {
  2912. if (!change.text) return change.to;
  2913. return Pos(change.from.line + change.text.length - 1,
  2914. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  2915. };
  2916. // Adjust a position to refer to the post-change position of the
  2917. // same text, or the end of the change if the change covers it.
  2918. function adjustForChange(pos, change) {
  2919. if (cmp(pos, change.from) < 0) return pos;
  2920. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  2921. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  2922. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  2923. return Pos(line, ch);
  2924. }
  2925. function computeSelAfterChange(doc, change) {
  2926. var out = [];
  2927. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2928. var range = doc.sel.ranges[i];
  2929. out.push(new Range(adjustForChange(range.anchor, change),
  2930. adjustForChange(range.head, change)));
  2931. }
  2932. return normalizeSelection(out, doc.sel.primIndex);
  2933. }
  2934. function offsetPos(pos, old, nw) {
  2935. if (pos.line == old.line)
  2936. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  2937. else
  2938. return Pos(nw.line + (pos.line - old.line), pos.ch);
  2939. }
  2940. // Used by replaceSelections to allow moving the selection to the
  2941. // start or around the replaced test. Hint may be "start" or "around".
  2942. function computeReplacedSel(doc, changes, hint) {
  2943. var out = [];
  2944. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  2945. for (var i = 0; i < changes.length; i++) {
  2946. var change = changes[i];
  2947. var from = offsetPos(change.from, oldPrev, newPrev);
  2948. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  2949. oldPrev = change.to;
  2950. newPrev = to;
  2951. if (hint == "around") {
  2952. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  2953. out[i] = new Range(inv ? to : from, inv ? from : to);
  2954. } else {
  2955. out[i] = new Range(from, from);
  2956. }
  2957. }
  2958. return new Selection(out, doc.sel.primIndex);
  2959. }
  2960. // Allow "beforeChange" event handlers to influence a change
  2961. function filterChange(doc, change, update) {
  2962. var obj = {
  2963. canceled: false,
  2964. from: change.from,
  2965. to: change.to,
  2966. text: change.text,
  2967. origin: change.origin,
  2968. cancel: function() { this.canceled = true; }
  2969. };
  2970. if (update) obj.update = function(from, to, text, origin) {
  2971. if (from) this.from = clipPos(doc, from);
  2972. if (to) this.to = clipPos(doc, to);
  2973. if (text) this.text = text;
  2974. if (origin !== undefined) this.origin = origin;
  2975. };
  2976. signal(doc, "beforeChange", doc, obj);
  2977. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  2978. if (obj.canceled) return null;
  2979. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  2980. }
  2981. // Apply a change to a document, and add it to the document's
  2982. // history, and propagating it to all linked documents.
  2983. function makeChange(doc, change, ignoreReadOnly) {
  2984. if (doc.cm) {
  2985. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  2986. if (doc.cm.state.suppressEdits) return;
  2987. }
  2988. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  2989. change = filterChange(doc, change, true);
  2990. if (!change) return;
  2991. }
  2992. // Possibly split or suppress the update based on the presence
  2993. // of read-only spans in its range.
  2994. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  2995. if (split) {
  2996. for (var i = split.length - 1; i >= 0; --i)
  2997. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  2998. } else {
  2999. makeChangeInner(doc, change);
  3000. }
  3001. }
  3002. function makeChangeInner(doc, change) {
  3003. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  3004. var selAfter = computeSelAfterChange(doc, change);
  3005. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  3006. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  3007. var rebased = [];
  3008. linkedDocs(doc, function(doc, sharedHist) {
  3009. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3010. rebaseHist(doc.history, change);
  3011. rebased.push(doc.history);
  3012. }
  3013. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  3014. });
  3015. }
  3016. // Revert a change stored in a document's history.
  3017. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  3018. if (doc.cm && doc.cm.state.suppressEdits) return;
  3019. var hist = doc.history, event, selAfter = doc.sel;
  3020. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  3021. // Verify that there is a useable event (so that ctrl-z won't
  3022. // needlessly clear selection events)
  3023. for (var i = 0; i < source.length; i++) {
  3024. event = source[i];
  3025. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  3026. break;
  3027. }
  3028. if (i == source.length) return;
  3029. hist.lastOrigin = hist.lastSelOrigin = null;
  3030. for (;;) {
  3031. event = source.pop();
  3032. if (event.ranges) {
  3033. pushSelectionToHistory(event, dest);
  3034. if (allowSelectionOnly && !event.equals(doc.sel)) {
  3035. setSelection(doc, event, {clearRedo: false});
  3036. return;
  3037. }
  3038. selAfter = event;
  3039. }
  3040. else break;
  3041. }
  3042. // Build up a reverse change object to add to the opposite history
  3043. // stack (redo when undoing, and vice versa).
  3044. var antiChanges = [];
  3045. pushSelectionToHistory(selAfter, dest);
  3046. dest.push({changes: antiChanges, generation: hist.generation});
  3047. hist.generation = event.generation || ++hist.maxGeneration;
  3048. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  3049. for (var i = event.changes.length - 1; i >= 0; --i) {
  3050. var change = event.changes[i];
  3051. change.origin = type;
  3052. if (filter && !filterChange(doc, change, false)) {
  3053. source.length = 0;
  3054. return;
  3055. }
  3056. antiChanges.push(historyChangeFromChange(doc, change));
  3057. var after = i ? computeSelAfterChange(doc, change, null) : lst(source);
  3058. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  3059. if (doc.cm) ensureCursorVisible(doc.cm);
  3060. var rebased = [];
  3061. // Propagate to the linked documents
  3062. linkedDocs(doc, function(doc, sharedHist) {
  3063. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  3064. rebaseHist(doc.history, change);
  3065. rebased.push(doc.history);
  3066. }
  3067. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  3068. });
  3069. }
  3070. }
  3071. // Sub-views need their line numbers shifted when text is added
  3072. // above or below them in the parent document.
  3073. function shiftDoc(doc, distance) {
  3074. doc.first += distance;
  3075. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  3076. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  3077. Pos(range.head.line + distance, range.head.ch));
  3078. }), doc.sel.primIndex);
  3079. if (doc.cm) regChange(doc.cm, doc.first, doc.first - distance, distance);
  3080. }
  3081. // More lower-level change function, handling only a single document
  3082. // (not linked ones).
  3083. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  3084. if (doc.cm && !doc.cm.curOp)
  3085. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  3086. if (change.to.line < doc.first) {
  3087. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  3088. return;
  3089. }
  3090. if (change.from.line > doc.lastLine()) return;
  3091. // Clip the change to the size of this doc
  3092. if (change.from.line < doc.first) {
  3093. var shift = change.text.length - 1 - (doc.first - change.from.line);
  3094. shiftDoc(doc, shift);
  3095. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  3096. text: [lst(change.text)], origin: change.origin};
  3097. }
  3098. var last = doc.lastLine();
  3099. if (change.to.line > last) {
  3100. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  3101. text: [change.text[0]], origin: change.origin};
  3102. }
  3103. change.removed = getBetween(doc, change.from, change.to);
  3104. if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
  3105. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  3106. else updateDoc(doc, change, spans);
  3107. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  3108. }
  3109. // Handle the interaction of a change to a document with the editor
  3110. // that this document is part of.
  3111. function makeChangeSingleDocInEditor(cm, change, spans) {
  3112. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  3113. var recomputeMaxLength = false, checkWidthStart = from.line;
  3114. if (!cm.options.lineWrapping) {
  3115. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  3116. doc.iter(checkWidthStart, to.line + 1, function(line) {
  3117. if (line == display.maxLine) {
  3118. recomputeMaxLength = true;
  3119. return true;
  3120. }
  3121. });
  3122. }
  3123. if (doc.sel.contains(change.from, change.to) > -1)
  3124. signalCursorActivity(cm);
  3125. updateDoc(doc, change, spans, estimateHeight(cm));
  3126. if (!cm.options.lineWrapping) {
  3127. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  3128. var len = lineLength(line);
  3129. if (len > display.maxLineLength) {
  3130. display.maxLine = line;
  3131. display.maxLineLength = len;
  3132. display.maxLineChanged = true;
  3133. recomputeMaxLength = false;
  3134. }
  3135. });
  3136. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  3137. }
  3138. // Adjust frontier, schedule worker
  3139. doc.frontier = Math.min(doc.frontier, from.line);
  3140. startWorker(cm, 400);
  3141. var lendiff = change.text.length - (to.line - from.line) - 1;
  3142. // Remember that these lines changed, for updating the display
  3143. if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  3144. regLineChange(cm, from.line, "text");
  3145. else
  3146. regChange(cm, from.line, to.line + 1, lendiff);
  3147. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  3148. if (changeHandler || changesHandler) {
  3149. var obj = {
  3150. from: from, to: to,
  3151. text: change.text,
  3152. removed: change.removed,
  3153. origin: change.origin
  3154. };
  3155. if (changeHandler) signalLater(cm, "change", cm, obj);
  3156. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  3157. }
  3158. }
  3159. function replaceRange(doc, code, from, to, origin) {
  3160. if (!to) to = from;
  3161. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  3162. if (typeof code == "string") code = splitLines(code);
  3163. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  3164. }
  3165. // SCROLLING THINGS INTO VIEW
  3166. // If an editor sits on the top or bottom of the window, partially
  3167. // scrolled out of view, this ensures that the cursor is visible.
  3168. function maybeScrollWindow(cm, coords) {
  3169. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3170. if (coords.top + box.top < 0) doScroll = true;
  3171. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  3172. if (doScroll != null && !phantom) {
  3173. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  3174. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  3175. (coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
  3176. coords.left + "px; width: 2px;");
  3177. cm.display.lineSpace.appendChild(scrollNode);
  3178. scrollNode.scrollIntoView(doScroll);
  3179. cm.display.lineSpace.removeChild(scrollNode);
  3180. }
  3181. }
  3182. // Scroll a given position into view (immediately), verifying that
  3183. // it actually became visible (as line heights are accurately
  3184. // measured, the position of something may 'drift' during drawing).
  3185. function scrollPosIntoView(cm, pos, end, margin) {
  3186. if (margin == null) margin = 0;
  3187. for (;;) {
  3188. var changed = false, coords = cursorCoords(cm, pos);
  3189. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3190. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  3191. Math.min(coords.top, endCoords.top) - margin,
  3192. Math.max(coords.left, endCoords.left),
  3193. Math.max(coords.bottom, endCoords.bottom) + margin);
  3194. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3195. if (scrollPos.scrollTop != null) {
  3196. setScrollTop(cm, scrollPos.scrollTop);
  3197. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  3198. }
  3199. if (scrollPos.scrollLeft != null) {
  3200. setScrollLeft(cm, scrollPos.scrollLeft);
  3201. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  3202. }
  3203. if (!changed) return coords;
  3204. }
  3205. }
  3206. // Scroll a given set of coordinates into view (immediately).
  3207. function scrollIntoView(cm, x1, y1, x2, y2) {
  3208. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  3209. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  3210. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  3211. }
  3212. // Calculate a new scroll position needed to scroll the given
  3213. // rectangle into view. Returns an object with scrollTop and
  3214. // scrollLeft properties. When these are undefined, the
  3215. // vertical/horizontal position does not need to be adjusted.
  3216. function calculateScrollPos(cm, x1, y1, x2, y2) {
  3217. var display = cm.display, snapMargin = textHeight(cm.display);
  3218. if (y1 < 0) y1 = 0;
  3219. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3220. var screen = display.scroller.clientHeight - scrollerCutOff, result = {};
  3221. var docBottom = cm.doc.height + paddingVert(display);
  3222. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  3223. if (y1 < screentop) {
  3224. result.scrollTop = atTop ? 0 : y1;
  3225. } else if (y2 > screentop + screen) {
  3226. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  3227. if (newTop != screentop) result.scrollTop = newTop;
  3228. }
  3229. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3230. var screenw = display.scroller.clientWidth - scrollerCutOff;
  3231. x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
  3232. var gutterw = display.gutters.offsetWidth;
  3233. var atLeft = x1 < gutterw + 10;
  3234. if (x1 < screenleft + gutterw || atLeft) {
  3235. if (atLeft) x1 = 0;
  3236. result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
  3237. } else if (x2 > screenw + screenleft - 3) {
  3238. result.scrollLeft = x2 + 10 - screenw;
  3239. }
  3240. return result;
  3241. }
  3242. // Store a relative adjustment to the scroll position in the current
  3243. // operation (to be applied when the operation finishes).
  3244. function addToScrollPos(cm, left, top) {
  3245. if (left != null || top != null) resolveScrollToPos(cm);
  3246. if (left != null)
  3247. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  3248. if (top != null)
  3249. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3250. }
  3251. // Make sure that at the end of the operation the current cursor is
  3252. // shown.
  3253. function ensureCursorVisible(cm) {
  3254. resolveScrollToPos(cm);
  3255. var cur = cm.getCursor(), from = cur, to = cur;
  3256. if (!cm.options.lineWrapping) {
  3257. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  3258. to = Pos(cur.line, cur.ch + 1);
  3259. }
  3260. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  3261. }
  3262. // When an operation has its scrollToPos property set, and another
  3263. // scroll action is applied before the end of the operation, this
  3264. // 'simulates' scrolling that position into view in a cheap way, so
  3265. // that the effect of intermediate scroll commands is not ignored.
  3266. function resolveScrollToPos(cm) {
  3267. var range = cm.curOp.scrollToPos;
  3268. if (range) {
  3269. cm.curOp.scrollToPos = null;
  3270. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3271. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  3272. Math.min(from.top, to.top) - range.margin,
  3273. Math.max(from.right, to.right),
  3274. Math.max(from.bottom, to.bottom) + range.margin);
  3275. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  3276. }
  3277. }
  3278. // API UTILITIES
  3279. // Indent the given line. The how parameter can be "smart",
  3280. // "add"/null, "subtract", or "prev". When aggressive is false
  3281. // (typically set to true for forced single-line indents), empty
  3282. // lines are not indented, and places where the mode returns Pass
  3283. // are left alone.
  3284. function indentLine(cm, n, how, aggressive) {
  3285. var doc = cm.doc, state;
  3286. if (how == null) how = "add";
  3287. if (how == "smart") {
  3288. // Fall back to "prev" when the mode doesn't have an indentation
  3289. // method.
  3290. if (!cm.doc.mode.indent) how = "prev";
  3291. else state = getStateBefore(cm, n);
  3292. }
  3293. var tabSize = cm.options.tabSize;
  3294. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  3295. if (line.stateAfter) line.stateAfter = null;
  3296. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  3297. if (!aggressive && !/\S/.test(line.text)) {
  3298. indentation = 0;
  3299. how = "not";
  3300. } else if (how == "smart") {
  3301. indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  3302. if (indentation == Pass) {
  3303. if (!aggressive) return;
  3304. how = "prev";
  3305. }
  3306. }
  3307. if (how == "prev") {
  3308. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  3309. else indentation = 0;
  3310. } else if (how == "add") {
  3311. indentation = curSpace + cm.options.indentUnit;
  3312. } else if (how == "subtract") {
  3313. indentation = curSpace - cm.options.indentUnit;
  3314. } else if (typeof how == "number") {
  3315. indentation = curSpace + how;
  3316. }
  3317. indentation = Math.max(0, indentation);
  3318. var indentString = "", pos = 0;
  3319. if (cm.options.indentWithTabs)
  3320. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  3321. if (pos < indentation) indentString += spaceStr(indentation - pos);
  3322. if (indentString != curSpaceString) {
  3323. replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  3324. } else {
  3325. // Ensure that, if the cursor was in the whitespace at the start
  3326. // of the line, it is moved to the end of that space.
  3327. for (var i = 0; i < doc.sel.ranges.length; i++) {
  3328. var range = doc.sel.ranges[i];
  3329. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  3330. var pos = Pos(n, curSpaceString.length);
  3331. replaceOneSelection(doc, i, new Range(pos, pos));
  3332. break;
  3333. }
  3334. }
  3335. }
  3336. line.stateAfter = null;
  3337. }
  3338. // Utility for applying a change to a line by handle or number,
  3339. // returning the number and optionally registering the line as
  3340. // changed.
  3341. function changeLine(cm, handle, changeType, op) {
  3342. var no = handle, line = handle, doc = cm.doc;
  3343. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  3344. else no = lineNo(handle);
  3345. if (no == null) return null;
  3346. if (op(line, no)) regLineChange(cm, no, changeType);
  3347. return line;
  3348. }
  3349. // Helper for deleting text near the selection(s), used to implement
  3350. // backspace, delete, and similar functionality.
  3351. function deleteNearSelection(cm, compute) {
  3352. var ranges = cm.doc.sel.ranges, kill = [];
  3353. // Build up a set of ranges to kill first, merging overlapping
  3354. // ranges.
  3355. for (var i = 0; i < ranges.length; i++) {
  3356. var toKill = compute(ranges[i]);
  3357. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  3358. var replaced = kill.pop();
  3359. if (cmp(replaced.from, toKill.from) < 0) {
  3360. toKill.from = replaced.from;
  3361. break;
  3362. }
  3363. }
  3364. kill.push(toKill);
  3365. }
  3366. // Next, remove those actual ranges.
  3367. runInOp(cm, function() {
  3368. for (var i = kill.length - 1; i >= 0; i--)
  3369. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  3370. ensureCursorVisible(cm);
  3371. });
  3372. }
  3373. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  3374. // right), unit can be "char", "column" (like char, but doesn't
  3375. // cross line boundaries), "word" (across next word), or "group" (to
  3376. // the start of next group of word or non-word-non-whitespace
  3377. // chars). The visually param controls whether, in right-to-left
  3378. // text, direction 1 means to move towards the next index in the
  3379. // string, or towards the character to the right of the current
  3380. // position. The resulting position will have a hitSide=true
  3381. // property if it reached the end of the document.
  3382. function findPosH(doc, pos, dir, unit, visually) {
  3383. var line = pos.line, ch = pos.ch, origDir = dir;
  3384. var lineObj = getLine(doc, line);
  3385. var possible = true;
  3386. function findNextLine() {
  3387. var l = line + dir;
  3388. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  3389. line = l;
  3390. return lineObj = getLine(doc, l);
  3391. }
  3392. function moveOnce(boundToLine) {
  3393. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  3394. if (next == null) {
  3395. if (!boundToLine && findNextLine()) {
  3396. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  3397. else ch = dir < 0 ? lineObj.text.length : 0;
  3398. } else return (possible = false);
  3399. } else ch = next;
  3400. return true;
  3401. }
  3402. if (unit == "char") moveOnce();
  3403. else if (unit == "column") moveOnce(true);
  3404. else if (unit == "word" || unit == "group") {
  3405. var sawType = null, group = unit == "group";
  3406. for (var first = true;; first = false) {
  3407. if (dir < 0 && !moveOnce(!first)) break;
  3408. var cur = lineObj.text.charAt(ch) || "\n";
  3409. var type = isWordChar(cur) ? "w"
  3410. : group && cur == "\n" ? "n"
  3411. : !group || /\s/.test(cur) ? null
  3412. : "p";
  3413. if (group && !first && !type) type = "s";
  3414. if (sawType && sawType != type) {
  3415. if (dir < 0) {dir = 1; moveOnce();}
  3416. break;
  3417. }
  3418. if (type) sawType = type;
  3419. if (dir > 0 && !moveOnce(!first)) break;
  3420. }
  3421. }
  3422. var result = skipAtomic(doc, Pos(line, ch), origDir, true);
  3423. if (!possible) result.hitSide = true;
  3424. return result;
  3425. }
  3426. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  3427. // "page" or "line". The resulting position will have a hitSide=true
  3428. // property if it reached the end of the document.
  3429. function findPosV(cm, pos, dir, unit) {
  3430. var doc = cm.doc, x = pos.left, y;
  3431. if (unit == "page") {
  3432. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  3433. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  3434. } else if (unit == "line") {
  3435. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  3436. }
  3437. for (;;) {
  3438. var target = coordsChar(cm, x, y);
  3439. if (!target.outside) break;
  3440. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  3441. y += dir * 5;
  3442. }
  3443. return target;
  3444. }
  3445. // Find the word at the given position (as returned by coordsChar).
  3446. function findWordAt(doc, pos) {
  3447. var line = getLine(doc, pos.line).text;
  3448. var start = pos.ch, end = pos.ch;
  3449. if (line) {
  3450. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  3451. var startChar = line.charAt(start);
  3452. var check = isWordChar(startChar) ? isWordChar
  3453. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  3454. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  3455. while (start > 0 && check(line.charAt(start - 1))) --start;
  3456. while (end < line.length && check(line.charAt(end))) ++end;
  3457. }
  3458. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  3459. }
  3460. // EDITOR METHODS
  3461. // The publicly visible API. Note that methodOp(f) means
  3462. // 'wrap f in an operation, performed on its `this` parameter'.
  3463. // This is not the complete set of editor methods. Most of the
  3464. // methods defined on the Doc type are also injected into
  3465. // CodeMirror.prototype, for backwards compatibility and
  3466. // convenience.
  3467. CodeMirror.prototype = {
  3468. constructor: CodeMirror,
  3469. focus: function(){window.focus(); focusInput(this); fastPoll(this);},
  3470. setOption: function(option, value) {
  3471. var options = this.options, old = options[option];
  3472. if (options[option] == value && option != "mode") return;
  3473. options[option] = value;
  3474. if (optionHandlers.hasOwnProperty(option))
  3475. operation(this, optionHandlers[option])(this, value, old);
  3476. },
  3477. getOption: function(option) {return this.options[option];},
  3478. getDoc: function() {return this.doc;},
  3479. addKeyMap: function(map, bottom) {
  3480. this.state.keyMaps[bottom ? "push" : "unshift"](map);
  3481. },
  3482. removeKeyMap: function(map) {
  3483. var maps = this.state.keyMaps;
  3484. for (var i = 0; i < maps.length; ++i)
  3485. if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
  3486. maps.splice(i, 1);
  3487. return true;
  3488. }
  3489. },
  3490. addOverlay: methodOp(function(spec, options) {
  3491. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  3492. if (mode.startState) throw new Error("Overlays may not be stateful.");
  3493. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  3494. this.state.modeGen++;
  3495. regChange(this);
  3496. }),
  3497. removeOverlay: methodOp(function(spec) {
  3498. var overlays = this.state.overlays;
  3499. for (var i = 0; i < overlays.length; ++i) {
  3500. var cur = overlays[i].modeSpec;
  3501. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  3502. overlays.splice(i, 1);
  3503. this.state.modeGen++;
  3504. regChange(this);
  3505. return;
  3506. }
  3507. }
  3508. }),
  3509. indentLine: methodOp(function(n, dir, aggressive) {
  3510. if (typeof dir != "string" && typeof dir != "number") {
  3511. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  3512. else dir = dir ? "add" : "subtract";
  3513. }
  3514. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  3515. }),
  3516. indentSelection: methodOp(function(how) {
  3517. var ranges = this.doc.sel.ranges, end = -1;
  3518. for (var i = 0; i < ranges.length; i++) {
  3519. var range = ranges[i];
  3520. if (!range.empty()) {
  3521. var start = Math.max(end, range.from().line);
  3522. var to = range.to();
  3523. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  3524. for (var j = start; j < end; ++j)
  3525. indentLine(this, j, how);
  3526. } else if (range.head.line > end) {
  3527. indentLine(this, range.head.line, how, true);
  3528. end = range.head.line;
  3529. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  3530. }
  3531. }
  3532. }),
  3533. // Fetch the parser token for a given character. Useful for hacks
  3534. // that want to inspect the mode state (say, for completion).
  3535. getTokenAt: function(pos, precise) {
  3536. var doc = this.doc;
  3537. pos = clipPos(doc, pos);
  3538. var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
  3539. var line = getLine(doc, pos.line);
  3540. var stream = new StringStream(line.text, this.options.tabSize);
  3541. while (stream.pos < pos.ch && !stream.eol()) {
  3542. stream.start = stream.pos;
  3543. var style = readToken(mode, stream, state);
  3544. }
  3545. return {start: stream.start,
  3546. end: stream.pos,
  3547. string: stream.current(),
  3548. type: style || null,
  3549. state: state};
  3550. },
  3551. getTokenTypeAt: function(pos) {
  3552. pos = clipPos(this.doc, pos);
  3553. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  3554. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  3555. var type;
  3556. if (ch == 0) type = styles[2];
  3557. else for (;;) {
  3558. var mid = (before + after) >> 1;
  3559. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  3560. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  3561. else { type = styles[mid * 2 + 2]; break; }
  3562. }
  3563. var cut = type ? type.indexOf("cm-overlay ") : -1;
  3564. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  3565. },
  3566. getModeAt: function(pos) {
  3567. var mode = this.doc.mode;
  3568. if (!mode.innerMode) return mode;
  3569. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  3570. },
  3571. getHelper: function(pos, type) {
  3572. return this.getHelpers(pos, type)[0];
  3573. },
  3574. getHelpers: function(pos, type) {
  3575. var found = [];
  3576. if (!helpers.hasOwnProperty(type)) return helpers;
  3577. var help = helpers[type], mode = this.getModeAt(pos);
  3578. if (typeof mode[type] == "string") {
  3579. if (help[mode[type]]) found.push(help[mode[type]]);
  3580. } else if (mode[type]) {
  3581. for (var i = 0; i < mode[type].length; i++) {
  3582. var val = help[mode[type][i]];
  3583. if (val) found.push(val);
  3584. }
  3585. } else if (mode.helperType && help[mode.helperType]) {
  3586. found.push(help[mode.helperType]);
  3587. } else if (help[mode.name]) {
  3588. found.push(help[mode.name]);
  3589. }
  3590. for (var i = 0; i < help._global.length; i++) {
  3591. var cur = help._global[i];
  3592. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  3593. found.push(cur.val);
  3594. }
  3595. return found;
  3596. },
  3597. getStateAfter: function(line, precise) {
  3598. var doc = this.doc;
  3599. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  3600. return getStateBefore(this, line + 1, precise);
  3601. },
  3602. cursorCoords: function(start, mode) {
  3603. var pos, range = this.doc.sel.primary();
  3604. if (start == null) pos = range.head;
  3605. else if (typeof start == "object") pos = clipPos(this.doc, start);
  3606. else pos = start ? range.from() : range.to();
  3607. return cursorCoords(this, pos, mode || "page");
  3608. },
  3609. charCoords: function(pos, mode) {
  3610. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  3611. },
  3612. coordsChar: function(coords, mode) {
  3613. coords = fromCoordSystem(this, coords, mode || "page");
  3614. return coordsChar(this, coords.left, coords.top);
  3615. },
  3616. lineAtHeight: function(height, mode) {
  3617. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  3618. return lineAtHeight(this.doc, height + this.display.viewOffset);
  3619. },
  3620. heightAtLine: function(line, mode) {
  3621. var end = false, last = this.doc.first + this.doc.size - 1;
  3622. if (line < this.doc.first) line = this.doc.first;
  3623. else if (line > last) { line = last; end = true; }
  3624. var lineObj = getLine(this.doc, line);
  3625. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  3626. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  3627. },
  3628. defaultTextHeight: function() { return textHeight(this.display); },
  3629. defaultCharWidth: function() { return charWidth(this.display); },
  3630. setGutterMarker: methodOp(function(line, gutterID, value) {
  3631. return changeLine(this, line, "gutter", function(line) {
  3632. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  3633. markers[gutterID] = value;
  3634. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  3635. return true;
  3636. });
  3637. }),
  3638. clearGutter: methodOp(function(gutterID) {
  3639. var cm = this, doc = cm.doc, i = doc.first;
  3640. doc.iter(function(line) {
  3641. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  3642. line.gutterMarkers[gutterID] = null;
  3643. regLineChange(cm, i, "gutter");
  3644. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  3645. }
  3646. ++i;
  3647. });
  3648. }),
  3649. addLineClass: methodOp(function(handle, where, cls) {
  3650. return changeLine(this, handle, "class", function(line) {
  3651. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  3652. if (!line[prop]) line[prop] = cls;
  3653. else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
  3654. else line[prop] += " " + cls;
  3655. return true;
  3656. });
  3657. }),
  3658. removeLineClass: methodOp(function(handle, where, cls) {
  3659. return changeLine(this, handle, "class", function(line) {
  3660. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  3661. var cur = line[prop];
  3662. if (!cur) return false;
  3663. else if (cls == null) line[prop] = null;
  3664. else {
  3665. var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
  3666. if (!found) return false;
  3667. var end = found.index + found[0].length;
  3668. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  3669. }
  3670. return true;
  3671. });
  3672. }),
  3673. addLineWidget: methodOp(function(handle, node, options) {
  3674. return addLineWidget(this, handle, node, options);
  3675. }),
  3676. removeLineWidget: function(widget) { widget.clear(); },
  3677. lineInfo: function(line) {
  3678. if (typeof line == "number") {
  3679. if (!isLine(this.doc, line)) return null;
  3680. var n = line;
  3681. line = getLine(this.doc, line);
  3682. if (!line) return null;
  3683. } else {
  3684. var n = lineNo(line);
  3685. if (n == null) return null;
  3686. }
  3687. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  3688. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  3689. widgets: line.widgets};
  3690. },
  3691. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  3692. addWidget: function(pos, node, scroll, vert, horiz) {
  3693. var display = this.display;
  3694. pos = cursorCoords(this, clipPos(this.doc, pos));
  3695. var top = pos.bottom, left = pos.left;
  3696. node.style.position = "absolute";
  3697. display.sizer.appendChild(node);
  3698. if (vert == "over") {
  3699. top = pos.top;
  3700. } else if (vert == "above" || vert == "near") {
  3701. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  3702. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  3703. // Default to positioning above (if specified and possible); otherwise default to positioning below
  3704. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  3705. top = pos.top - node.offsetHeight;
  3706. else if (pos.bottom + node.offsetHeight <= vspace)
  3707. top = pos.bottom;
  3708. if (left + node.offsetWidth > hspace)
  3709. left = hspace - node.offsetWidth;
  3710. }
  3711. node.style.top = top + "px";
  3712. node.style.left = node.style.right = "";
  3713. if (horiz == "right") {
  3714. left = display.sizer.clientWidth - node.offsetWidth;
  3715. node.style.right = "0px";
  3716. } else {
  3717. if (horiz == "left") left = 0;
  3718. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  3719. node.style.left = left + "px";
  3720. }
  3721. if (scroll)
  3722. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  3723. },
  3724. triggerOnKeyDown: methodOp(onKeyDown),
  3725. triggerOnKeyPress: methodOp(onKeyPress),
  3726. triggerOnKeyUp: methodOp(onKeyUp),
  3727. execCommand: function(cmd) {
  3728. if (commands.hasOwnProperty(cmd))
  3729. return commands[cmd](this);
  3730. },
  3731. findPosH: function(from, amount, unit, visually) {
  3732. var dir = 1;
  3733. if (amount < 0) { dir = -1; amount = -amount; }
  3734. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  3735. cur = findPosH(this.doc, cur, dir, unit, visually);
  3736. if (cur.hitSide) break;
  3737. }
  3738. return cur;
  3739. },
  3740. moveH: methodOp(function(dir, unit) {
  3741. var cm = this;
  3742. cm.extendSelectionsBy(function(range) {
  3743. if (cm.display.shift || cm.doc.extend || range.empty())
  3744. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  3745. else
  3746. return dir < 0 ? range.from() : range.to();
  3747. }, sel_move);
  3748. }),
  3749. deleteH: methodOp(function(dir, unit) {
  3750. var sel = this.doc.sel, doc = this.doc;
  3751. if (sel.somethingSelected())
  3752. doc.replaceSelection("", null, "+delete");
  3753. else
  3754. deleteNearSelection(this, function(range) {
  3755. var other = findPosH(doc, range.head, dir, unit, false);
  3756. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  3757. });
  3758. }),
  3759. findPosV: function(from, amount, unit, goalColumn) {
  3760. var dir = 1, x = goalColumn;
  3761. if (amount < 0) { dir = -1; amount = -amount; }
  3762. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  3763. var coords = cursorCoords(this, cur, "div");
  3764. if (x == null) x = coords.left;
  3765. else coords.left = x;
  3766. cur = findPosV(this, coords, dir, unit);
  3767. if (cur.hitSide) break;
  3768. }
  3769. return cur;
  3770. },
  3771. moveV: methodOp(function(dir, unit) {
  3772. var cm = this, doc = this.doc, goals = [];
  3773. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  3774. doc.extendSelectionsBy(function(range) {
  3775. if (collapse)
  3776. return dir < 0 ? range.from() : range.to();
  3777. var headPos = cursorCoords(cm, range.head, "div");
  3778. if (range.goalColumn != null) headPos.left = range.goalColumn;
  3779. goals.push(headPos.left);
  3780. var pos = findPosV(cm, headPos, dir, unit);
  3781. if (unit == "page" && range == doc.sel.primary())
  3782. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  3783. return pos;
  3784. }, sel_move);
  3785. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  3786. doc.sel.ranges[i].goalColumn = goals[i];
  3787. }),
  3788. toggleOverwrite: function(value) {
  3789. if (value != null && value == this.state.overwrite) return;
  3790. if (this.state.overwrite = !this.state.overwrite)
  3791. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  3792. else
  3793. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  3794. signal(this, "overwriteToggle", this, this.state.overwrite);
  3795. },
  3796. hasFocus: function() { return activeElt() == this.display.input; },
  3797. scrollTo: methodOp(function(x, y) {
  3798. if (x != null || y != null) resolveScrollToPos(this);
  3799. if (x != null) this.curOp.scrollLeft = x;
  3800. if (y != null) this.curOp.scrollTop = y;
  3801. }),
  3802. getScrollInfo: function() {
  3803. var scroller = this.display.scroller, co = scrollerCutOff;
  3804. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  3805. height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
  3806. clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
  3807. },
  3808. scrollIntoView: methodOp(function(range, margin) {
  3809. if (range == null) {
  3810. range = {from: this.doc.sel.primary().head, to: null};
  3811. if (margin == null) margin = this.options.cursorScrollMargin;
  3812. } else if (typeof range == "number") {
  3813. range = {from: Pos(range, 0), to: null};
  3814. } else if (range.from == null) {
  3815. range = {from: range, to: null};
  3816. }
  3817. if (!range.to) range.to = range.from;
  3818. range.margin = margin || 0;
  3819. if (range.from.line != null) {
  3820. resolveScrollToPos(this);
  3821. this.curOp.scrollToPos = range;
  3822. } else {
  3823. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  3824. Math.min(range.from.top, range.to.top) - range.margin,
  3825. Math.max(range.from.right, range.to.right),
  3826. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  3827. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  3828. }
  3829. }),
  3830. setSize: methodOp(function(width, height) {
  3831. function interpret(val) {
  3832. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  3833. }
  3834. if (width != null) this.display.wrapper.style.width = interpret(width);
  3835. if (height != null) this.display.wrapper.style.height = interpret(height);
  3836. if (this.options.lineWrapping) clearLineMeasurementCache(this);
  3837. this.curOp.forceUpdate = true;
  3838. signal(this, "refresh", this);
  3839. }),
  3840. operation: function(f){return runInOp(this, f);},
  3841. refresh: methodOp(function() {
  3842. var oldHeight = this.display.cachedTextHeight;
  3843. regChange(this);
  3844. this.curOp.forceUpdate = true;
  3845. clearCaches(this);
  3846. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  3847. updateGutterSpace(this);
  3848. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  3849. estimateLineHeights(this);
  3850. signal(this, "refresh", this);
  3851. }),
  3852. swapDoc: methodOp(function(doc) {
  3853. var old = this.doc;
  3854. old.cm = null;
  3855. attachDoc(this, doc);
  3856. clearCaches(this);
  3857. resetInput(this);
  3858. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  3859. signalLater(this, "swapDoc", this, old);
  3860. return old;
  3861. }),
  3862. getInputField: function(){return this.display.input;},
  3863. getWrapperElement: function(){return this.display.wrapper;},
  3864. getScrollerElement: function(){return this.display.scroller;},
  3865. getGutterElement: function(){return this.display.gutters;}
  3866. };
  3867. eventMixin(CodeMirror);
  3868. // OPTION DEFAULTS
  3869. // The default configuration options.
  3870. var defaults = CodeMirror.defaults = {};
  3871. // Functions to run when options are changed.
  3872. var optionHandlers = CodeMirror.optionHandlers = {};
  3873. function option(name, deflt, handle, notOnInit) {
  3874. CodeMirror.defaults[name] = deflt;
  3875. if (handle) optionHandlers[name] =
  3876. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  3877. }
  3878. // Passed to option handlers when there is no old value.
  3879. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  3880. // These two are, on init, called from the constructor because they
  3881. // have to be initialized before the editor can start at all.
  3882. option("value", "", function(cm, val) {
  3883. cm.setValue(val);
  3884. }, true);
  3885. option("mode", null, function(cm, val) {
  3886. cm.doc.modeOption = val;
  3887. loadMode(cm);
  3888. }, true);
  3889. option("indentUnit", 2, loadMode, true);
  3890. option("indentWithTabs", false);
  3891. option("smartIndent", true);
  3892. option("tabSize", 4, function(cm) {
  3893. resetModeState(cm);
  3894. clearCaches(cm);
  3895. regChange(cm);
  3896. }, true);
  3897. option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
  3898. cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  3899. cm.refresh();
  3900. }, true);
  3901. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  3902. option("electricChars", true);
  3903. option("rtlMoveVisually", !windows);
  3904. option("wholeLineUpdateBefore", true);
  3905. option("theme", "default", function(cm) {
  3906. themeChanged(cm);
  3907. guttersChanged(cm);
  3908. }, true);
  3909. option("keyMap", "default", keyMapChanged);
  3910. option("extraKeys", null);
  3911. option("lineWrapping", false, wrappingChanged, true);
  3912. option("gutters", [], function(cm) {
  3913. setGuttersForLineNumbers(cm.options);
  3914. guttersChanged(cm);
  3915. }, true);
  3916. option("fixedGutter", true, function(cm, val) {
  3917. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  3918. cm.refresh();
  3919. }, true);
  3920. option("coverGutterNextToScrollbar", false, updateScrollbars, true);
  3921. option("lineNumbers", false, function(cm) {
  3922. setGuttersForLineNumbers(cm.options);
  3923. guttersChanged(cm);
  3924. }, true);
  3925. option("firstLineNumber", 1, guttersChanged, true);
  3926. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  3927. option("showCursorWhenSelecting", false, updateSelection, true);
  3928. option("resetSelectionOnContextMenu", true);
  3929. option("readOnly", false, function(cm, val) {
  3930. if (val == "nocursor") {
  3931. onBlur(cm);
  3932. cm.display.input.blur();
  3933. cm.display.disabled = true;
  3934. } else {
  3935. cm.display.disabled = false;
  3936. if (!val) resetInput(cm);
  3937. }
  3938. });
  3939. option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
  3940. option("dragDrop", true);
  3941. option("cursorBlinkRate", 530);
  3942. option("cursorScrollMargin", 0);
  3943. option("cursorHeight", 1);
  3944. option("workTime", 100);
  3945. option("workDelay", 100);
  3946. option("flattenSpans", true, resetModeState, true);
  3947. option("addModeClass", false, resetModeState, true);
  3948. option("pollInterval", 100);
  3949. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  3950. option("historyEventDelay", 1250);
  3951. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  3952. option("maxHighlightLength", 10000, resetModeState, true);
  3953. option("moveInputWithCursor", true, function(cm, val) {
  3954. if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
  3955. });
  3956. option("tabindex", null, function(cm, val) {
  3957. cm.display.input.tabIndex = val || "";
  3958. });
  3959. option("autofocus", null);
  3960. // MODE DEFINITION AND QUERYING
  3961. // Known modes, by name and by MIME
  3962. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  3963. // Extra arguments are stored as the mode's dependencies, which is
  3964. // used by (legacy) mechanisms like loadmode.js to automatically
  3965. // load a mode. (Preferred mechanism is the require/define calls.)
  3966. CodeMirror.defineMode = function(name, mode) {
  3967. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  3968. if (arguments.length > 2) {
  3969. mode.dependencies = [];
  3970. for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
  3971. }
  3972. modes[name] = mode;
  3973. };
  3974. CodeMirror.defineMIME = function(mime, spec) {
  3975. mimeModes[mime] = spec;
  3976. };
  3977. // Given a MIME type, a {name, ...options} config object, or a name
  3978. // string, return a mode config object.
  3979. CodeMirror.resolveMode = function(spec) {
  3980. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  3981. spec = mimeModes[spec];
  3982. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  3983. var found = mimeModes[spec.name];
  3984. if (typeof found == "string") found = {name: found};
  3985. spec = createObj(found, spec);
  3986. spec.name = found.name;
  3987. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  3988. return CodeMirror.resolveMode("application/xml");
  3989. }
  3990. if (typeof spec == "string") return {name: spec};
  3991. else return spec || {name: "null"};
  3992. };
  3993. // Given a mode spec (anything that resolveMode accepts), find and
  3994. // initialize an actual mode object.
  3995. CodeMirror.getMode = function(options, spec) {
  3996. var spec = CodeMirror.resolveMode(spec);
  3997. var mfactory = modes[spec.name];
  3998. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  3999. var modeObj = mfactory(options, spec);
  4000. if (modeExtensions.hasOwnProperty(spec.name)) {
  4001. var exts = modeExtensions[spec.name];
  4002. for (var prop in exts) {
  4003. if (!exts.hasOwnProperty(prop)) continue;
  4004. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  4005. modeObj[prop] = exts[prop];
  4006. }
  4007. }
  4008. modeObj.name = spec.name;
  4009. if (spec.helperType) modeObj.helperType = spec.helperType;
  4010. if (spec.modeProps) for (var prop in spec.modeProps)
  4011. modeObj[prop] = spec.modeProps[prop];
  4012. return modeObj;
  4013. };
  4014. // Minimal default mode.
  4015. CodeMirror.defineMode("null", function() {
  4016. return {token: function(stream) {stream.skipToEnd();}};
  4017. });
  4018. CodeMirror.defineMIME("text/plain", "null");
  4019. // This can be used to attach properties to mode objects from
  4020. // outside the actual mode definition.
  4021. var modeExtensions = CodeMirror.modeExtensions = {};
  4022. CodeMirror.extendMode = function(mode, properties) {
  4023. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  4024. copyObj(properties, exts);
  4025. };
  4026. // EXTENSIONS
  4027. CodeMirror.defineExtension = function(name, func) {
  4028. CodeMirror.prototype[name] = func;
  4029. };
  4030. CodeMirror.defineDocExtension = function(name, func) {
  4031. Doc.prototype[name] = func;
  4032. };
  4033. CodeMirror.defineOption = option;
  4034. var initHooks = [];
  4035. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  4036. var helpers = CodeMirror.helpers = {};
  4037. CodeMirror.registerHelper = function(type, name, value) {
  4038. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  4039. helpers[type][name] = value;
  4040. };
  4041. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  4042. CodeMirror.registerHelper(type, name, value);
  4043. helpers[type]._global.push({pred: predicate, val: value});
  4044. };
  4045. // MODE STATE HANDLING
  4046. // Utility functions for working with state. Exported because nested
  4047. // modes need to do this for their inner modes.
  4048. var copyState = CodeMirror.copyState = function(mode, state) {
  4049. if (state === true) return state;
  4050. if (mode.copyState) return mode.copyState(state);
  4051. var nstate = {};
  4052. for (var n in state) {
  4053. var val = state[n];
  4054. if (val instanceof Array) val = val.concat([]);
  4055. nstate[n] = val;
  4056. }
  4057. return nstate;
  4058. };
  4059. var startState = CodeMirror.startState = function(mode, a1, a2) {
  4060. return mode.startState ? mode.startState(a1, a2) : true;
  4061. };
  4062. // Given a mode and a state (for that mode), find the inner mode and
  4063. // state at the position that the state refers to.
  4064. CodeMirror.innerMode = function(mode, state) {
  4065. while (mode.innerMode) {
  4066. var info = mode.innerMode(state);
  4067. if (!info || info.mode == mode) break;
  4068. state = info.state;
  4069. mode = info.mode;
  4070. }
  4071. return info || {mode: mode, state: state};
  4072. };
  4073. // STANDARD COMMANDS
  4074. // Commands are parameter-less actions that can be performed on an
  4075. // editor, mostly used for keybindings.
  4076. var commands = CodeMirror.commands = {
  4077. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  4078. singleSelection: function(cm) {
  4079. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  4080. },
  4081. killLine: function(cm) {
  4082. deleteNearSelection(cm, function(range) {
  4083. if (range.empty()) {
  4084. var len = getLine(cm.doc, range.head.line).text.length;
  4085. if (range.head.ch == len && range.head.line < cm.lastLine())
  4086. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  4087. else
  4088. return {from: range.head, to: Pos(range.head.line, len)};
  4089. } else {
  4090. return {from: range.from(), to: range.to()};
  4091. }
  4092. });
  4093. },
  4094. deleteLine: function(cm) {
  4095. deleteNearSelection(cm, function(range) {
  4096. return {from: Pos(range.from().line, 0),
  4097. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  4098. });
  4099. },
  4100. delLineLeft: function(cm) {
  4101. deleteNearSelection(cm, function(range) {
  4102. return {from: Pos(range.from().line, 0), to: range.from()};
  4103. });
  4104. },
  4105. undo: function(cm) {cm.undo();},
  4106. redo: function(cm) {cm.redo();},
  4107. undoSelection: function(cm) {cm.undoSelection();},
  4108. redoSelection: function(cm) {cm.redoSelection();},
  4109. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  4110. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  4111. goLineStart: function(cm) {
  4112. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move);
  4113. },
  4114. goLineStartSmart: function(cm) {
  4115. cm.extendSelectionsBy(function(range) {
  4116. var start = lineStart(cm, range.head.line);
  4117. var line = cm.getLineHandle(start.line);
  4118. var order = getOrder(line);
  4119. if (!order || order[0].level == 0) {
  4120. var firstNonWS = Math.max(0, line.text.search(/\S/));
  4121. var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch;
  4122. return Pos(start.line, inWS ? 0 : firstNonWS);
  4123. }
  4124. return start;
  4125. }, sel_move);
  4126. },
  4127. goLineEnd: function(cm) {
  4128. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move);
  4129. },
  4130. goLineRight: function(cm) {
  4131. cm.extendSelectionsBy(function(range) {
  4132. var top = cm.charCoords(range.head, "div").top + 5;
  4133. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  4134. }, sel_move);
  4135. },
  4136. goLineLeft: function(cm) {
  4137. cm.extendSelectionsBy(function(range) {
  4138. var top = cm.charCoords(range.head, "div").top + 5;
  4139. return cm.coordsChar({left: 0, top: top}, "div");
  4140. }, sel_move);
  4141. },
  4142. goLineUp: function(cm) {cm.moveV(-1, "line");},
  4143. goLineDown: function(cm) {cm.moveV(1, "line");},
  4144. goPageUp: function(cm) {cm.moveV(-1, "page");},
  4145. goPageDown: function(cm) {cm.moveV(1, "page");},
  4146. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  4147. goCharRight: function(cm) {cm.moveH(1, "char");},
  4148. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  4149. goColumnRight: function(cm) {cm.moveH(1, "column");},
  4150. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  4151. goGroupRight: function(cm) {cm.moveH(1, "group");},
  4152. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  4153. goWordRight: function(cm) {cm.moveH(1, "word");},
  4154. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  4155. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  4156. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  4157. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  4158. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  4159. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  4160. indentAuto: function(cm) {cm.indentSelection("smart");},
  4161. indentMore: function(cm) {cm.indentSelection("add");},
  4162. indentLess: function(cm) {cm.indentSelection("subtract");},
  4163. insertTab: function(cm) {cm.replaceSelection("\t");},
  4164. insertSoftTab: function(cm) {
  4165. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  4166. for (var i = 0; i < ranges.length; i++) {
  4167. var pos = ranges[i].from();
  4168. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  4169. spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
  4170. }
  4171. cm.replaceSelections(spaces);
  4172. },
  4173. defaultTab: function(cm) {
  4174. if (cm.somethingSelected()) cm.indentSelection("add");
  4175. else cm.execCommand("insertTab");
  4176. },
  4177. transposeChars: function(cm) {
  4178. runInOp(cm, function() {
  4179. var ranges = cm.listSelections();
  4180. for (var i = 0; i < ranges.length; i++) {
  4181. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  4182. if (cur.ch > 0 && cur.ch < line.length - 1)
  4183. cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
  4184. Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
  4185. }
  4186. });
  4187. },
  4188. newlineAndIndent: function(cm) {
  4189. runInOp(cm, function() {
  4190. var len = cm.listSelections().length;
  4191. for (var i = 0; i < len; i++) {
  4192. var range = cm.listSelections()[i];
  4193. cm.replaceRange("\n", range.anchor, range.head, "+input");
  4194. cm.indentLine(range.from().line + 1, null, true);
  4195. ensureCursorVisible(cm);
  4196. }
  4197. });
  4198. },
  4199. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  4200. };
  4201. // STANDARD KEYMAPS
  4202. var keyMap = CodeMirror.keyMap = {};
  4203. keyMap.basic = {
  4204. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  4205. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  4206. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  4207. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  4208. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  4209. "Esc": "singleSelection"
  4210. };
  4211. // Note that the save and find-related commands aren't defined by
  4212. // default. User code or addons can define them. Unknown commands
  4213. // are simply ignored.
  4214. keyMap.pcDefault = {
  4215. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  4216. "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
  4217. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  4218. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  4219. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  4220. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  4221. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  4222. fallthrough: "basic"
  4223. };
  4224. keyMap.macDefault = {
  4225. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  4226. "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  4227. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
  4228. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  4229. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  4230. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
  4231. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection",
  4232. fallthrough: ["basic", "emacsy"]
  4233. };
  4234. // Very basic readline/emacs-style bindings, which are standard on Mac.
  4235. keyMap.emacsy = {
  4236. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  4237. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  4238. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  4239. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  4240. };
  4241. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  4242. // KEYMAP DISPATCH
  4243. function getKeyMap(val) {
  4244. if (typeof val == "string") return keyMap[val];
  4245. else return val;
  4246. }
  4247. // Given an array of keymaps and a key name, call handle on any
  4248. // bindings found, until that returns a truthy value, at which point
  4249. // we consider the key handled. Implements things like binding a key
  4250. // to false stopping further handling and keymap fallthrough.
  4251. var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {
  4252. function lookup(map) {
  4253. map = getKeyMap(map);
  4254. var found = map[name];
  4255. if (found === false) return "stop";
  4256. if (found != null && handle(found)) return true;
  4257. if (map.nofallthrough) return "stop";
  4258. var fallthrough = map.fallthrough;
  4259. if (fallthrough == null) return false;
  4260. if (Object.prototype.toString.call(fallthrough) != "[object Array]")
  4261. return lookup(fallthrough);
  4262. for (var i = 0; i < fallthrough.length; ++i) {
  4263. var done = lookup(fallthrough[i]);
  4264. if (done) return done;
  4265. }
  4266. return false;
  4267. }
  4268. for (var i = 0; i < maps.length; ++i) {
  4269. var done = lookup(maps[i]);
  4270. if (done) return done != "stop";
  4271. }
  4272. };
  4273. // Modifier key presses don't count as 'real' key presses for the
  4274. // purpose of keymap fallthrough.
  4275. var isModifierKey = CodeMirror.isModifierKey = function(event) {
  4276. var name = keyNames[event.keyCode];
  4277. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  4278. };
  4279. // Look up the name of a key as indicated by an event object.
  4280. var keyName = CodeMirror.keyName = function(event, noShift) {
  4281. if (presto && event.keyCode == 34 && event["char"]) return false;
  4282. var name = keyNames[event.keyCode];
  4283. if (name == null || event.altGraphKey) return false;
  4284. if (event.altKey) name = "Alt-" + name;
  4285. if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
  4286. if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
  4287. if (!noShift && event.shiftKey) name = "Shift-" + name;
  4288. return name;
  4289. };
  4290. // FROMTEXTAREA
  4291. CodeMirror.fromTextArea = function(textarea, options) {
  4292. if (!options) options = {};
  4293. options.value = textarea.value;
  4294. if (!options.tabindex && textarea.tabindex)
  4295. options.tabindex = textarea.tabindex;
  4296. if (!options.placeholder && textarea.placeholder)
  4297. options.placeholder = textarea.placeholder;
  4298. // Set autofocus to true if this textarea is focused, or if it has
  4299. // autofocus and no other element is focused.
  4300. if (options.autofocus == null) {
  4301. var hasFocus = activeElt();
  4302. options.autofocus = hasFocus == textarea ||
  4303. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  4304. }
  4305. function save() {textarea.value = cm.getValue();}
  4306. if (textarea.form) {
  4307. on(textarea.form, "submit", save);
  4308. // Deplorable hack to make the submit method do the right thing.
  4309. if (!options.leaveSubmitMethodAlone) {
  4310. var form = textarea.form, realSubmit = form.submit;
  4311. try {
  4312. var wrappedSubmit = form.submit = function() {
  4313. save();
  4314. form.submit = realSubmit;
  4315. form.submit();
  4316. form.submit = wrappedSubmit;
  4317. };
  4318. } catch(e) {}
  4319. }
  4320. }
  4321. textarea.style.display = "none";
  4322. var cm = CodeMirror(function(node) {
  4323. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  4324. }, options);
  4325. cm.save = save;
  4326. cm.getTextArea = function() { return textarea; };
  4327. cm.toTextArea = function() {
  4328. save();
  4329. textarea.parentNode.removeChild(cm.getWrapperElement());
  4330. textarea.style.display = "";
  4331. if (textarea.form) {
  4332. off(textarea.form, "submit", save);
  4333. if (typeof textarea.form.submit == "function")
  4334. textarea.form.submit = realSubmit;
  4335. }
  4336. };
  4337. return cm;
  4338. };
  4339. // STRING STREAM
  4340. // Fed to the mode parsers, provides helper functions to make
  4341. // parsers more succinct.
  4342. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  4343. this.pos = this.start = 0;
  4344. this.string = string;
  4345. this.tabSize = tabSize || 8;
  4346. this.lastColumnPos = this.lastColumnValue = 0;
  4347. this.lineStart = 0;
  4348. };
  4349. StringStream.prototype = {
  4350. eol: function() {return this.pos >= this.string.length;},
  4351. sol: function() {return this.pos == this.lineStart;},
  4352. peek: function() {return this.string.charAt(this.pos) || undefined;},
  4353. next: function() {
  4354. if (this.pos < this.string.length)
  4355. return this.string.charAt(this.pos++);
  4356. },
  4357. eat: function(match) {
  4358. var ch = this.string.charAt(this.pos);
  4359. if (typeof match == "string") var ok = ch == match;
  4360. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  4361. if (ok) {++this.pos; return ch;}
  4362. },
  4363. eatWhile: function(match) {
  4364. var start = this.pos;
  4365. while (this.eat(match)){}
  4366. return this.pos > start;
  4367. },
  4368. eatSpace: function() {
  4369. var start = this.pos;
  4370. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  4371. return this.pos > start;
  4372. },
  4373. skipToEnd: function() {this.pos = this.string.length;},
  4374. skipTo: function(ch) {
  4375. var found = this.string.indexOf(ch, this.pos);
  4376. if (found > -1) {this.pos = found; return true;}
  4377. },
  4378. backUp: function(n) {this.pos -= n;},
  4379. column: function() {
  4380. if (this.lastColumnPos < this.start) {
  4381. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  4382. this.lastColumnPos = this.start;
  4383. }
  4384. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  4385. },
  4386. indentation: function() {
  4387. return countColumn(this.string, null, this.tabSize) -
  4388. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  4389. },
  4390. match: function(pattern, consume, caseInsensitive) {
  4391. if (typeof pattern == "string") {
  4392. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  4393. var substr = this.string.substr(this.pos, pattern.length);
  4394. if (cased(substr) == cased(pattern)) {
  4395. if (consume !== false) this.pos += pattern.length;
  4396. return true;
  4397. }
  4398. } else {
  4399. var match = this.string.slice(this.pos).match(pattern);
  4400. if (match && match.index > 0) return null;
  4401. if (match && consume !== false) this.pos += match[0].length;
  4402. return match;
  4403. }
  4404. },
  4405. current: function(){return this.string.slice(this.start, this.pos);},
  4406. hideFirstChars: function(n, inner) {
  4407. this.lineStart += n;
  4408. try { return inner(); }
  4409. finally { this.lineStart -= n; }
  4410. }
  4411. };
  4412. // TEXTMARKERS
  4413. // Created with markText and setBookmark methods. A TextMarker is a
  4414. // handle that can be used to clear or find a marked position in the
  4415. // document. Line objects hold arrays (markedSpans) containing
  4416. // {from, to, marker} object pointing to such marker objects, and
  4417. // indicating that such a marker is present on that line. Multiple
  4418. // lines may point to the same marker when it spans across lines.
  4419. // The spans will have null for their from/to properties when the
  4420. // marker continues beyond the start/end of the line. Markers have
  4421. // links back to the lines they currently touch.
  4422. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  4423. this.lines = [];
  4424. this.type = type;
  4425. this.doc = doc;
  4426. };
  4427. eventMixin(TextMarker);
  4428. // Clear the marker.
  4429. TextMarker.prototype.clear = function() {
  4430. if (this.explicitlyCleared) return;
  4431. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  4432. if (withOp) startOperation(cm);
  4433. if (hasHandler(this, "clear")) {
  4434. var found = this.find();
  4435. if (found) signalLater(this, "clear", found.from, found.to);
  4436. }
  4437. var min = null, max = null;
  4438. for (var i = 0; i < this.lines.length; ++i) {
  4439. var line = this.lines[i];
  4440. var span = getMarkedSpanFor(line.markedSpans, this);
  4441. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  4442. else if (cm) {
  4443. if (span.to != null) max = lineNo(line);
  4444. if (span.from != null) min = lineNo(line);
  4445. }
  4446. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  4447. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  4448. updateLineHeight(line, textHeight(cm.display));
  4449. }
  4450. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  4451. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  4452. if (len > cm.display.maxLineLength) {
  4453. cm.display.maxLine = visual;
  4454. cm.display.maxLineLength = len;
  4455. cm.display.maxLineChanged = true;
  4456. }
  4457. }
  4458. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  4459. this.lines.length = 0;
  4460. this.explicitlyCleared = true;
  4461. if (this.atomic && this.doc.cantEdit) {
  4462. this.doc.cantEdit = false;
  4463. if (cm) reCheckSelection(cm.doc);
  4464. }
  4465. if (cm) signalLater(cm, "markerCleared", cm, this);
  4466. if (withOp) endOperation(cm);
  4467. if (this.parent) this.parent.clear();
  4468. };
  4469. // Find the position of the marker in the document. Returns a {from,
  4470. // to} object by default. Side can be passed to get a specific side
  4471. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  4472. // Pos objects returned contain a line object, rather than a line
  4473. // number (used to prevent looking up the same line twice).
  4474. TextMarker.prototype.find = function(side, lineObj) {
  4475. if (side == null && this.type == "bookmark") side = 1;
  4476. var from, to;
  4477. for (var i = 0; i < this.lines.length; ++i) {
  4478. var line = this.lines[i];
  4479. var span = getMarkedSpanFor(line.markedSpans, this);
  4480. if (span.from != null) {
  4481. from = Pos(lineObj ? line : lineNo(line), span.from);
  4482. if (side == -1) return from;
  4483. }
  4484. if (span.to != null) {
  4485. to = Pos(lineObj ? line : lineNo(line), span.to);
  4486. if (side == 1) return to;
  4487. }
  4488. }
  4489. return from && {from: from, to: to};
  4490. };
  4491. // Signals that the marker's widget changed, and surrounding layout
  4492. // should be recomputed.
  4493. TextMarker.prototype.changed = function() {
  4494. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  4495. if (!pos || !cm) return;
  4496. runInOp(cm, function() {
  4497. var line = pos.line, lineN = lineNo(pos.line);
  4498. var view = findViewForLine(cm, lineN);
  4499. if (view) {
  4500. clearLineMeasurementCacheFor(view);
  4501. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  4502. }
  4503. cm.curOp.updateMaxLine = true;
  4504. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  4505. var oldHeight = widget.height;
  4506. widget.height = null;
  4507. var dHeight = widgetHeight(widget) - oldHeight;
  4508. if (dHeight)
  4509. updateLineHeight(line, line.height + dHeight);
  4510. }
  4511. });
  4512. };
  4513. TextMarker.prototype.attachLine = function(line) {
  4514. if (!this.lines.length && this.doc.cm) {
  4515. var op = this.doc.cm.curOp;
  4516. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  4517. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  4518. }
  4519. this.lines.push(line);
  4520. };
  4521. TextMarker.prototype.detachLine = function(line) {
  4522. this.lines.splice(indexOf(this.lines, line), 1);
  4523. if (!this.lines.length && this.doc.cm) {
  4524. var op = this.doc.cm.curOp;
  4525. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  4526. }
  4527. };
  4528. // Collapsed markers have unique ids, in order to be able to order
  4529. // them, which is needed for uniquely determining an outer marker
  4530. // when they overlap (they may nest, but not partially overlap).
  4531. var nextMarkerId = 0;
  4532. // Create a marker, wire it up to the right lines, and
  4533. function markText(doc, from, to, options, type) {
  4534. // Shared markers (across linked documents) are handled separately
  4535. // (markTextShared will call out to this again, once per
  4536. // document).
  4537. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  4538. // Ensure we are in an operation.
  4539. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  4540. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  4541. if (options) copyObj(options, marker, false);
  4542. // Don't connect empty markers unless clearWhenEmpty is false
  4543. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  4544. return marker;
  4545. if (marker.replacedWith) {
  4546. // Showing up as a widget implies collapsed (widget replaces text)
  4547. marker.collapsed = true;
  4548. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  4549. if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;
  4550. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  4551. }
  4552. if (marker.collapsed) {
  4553. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  4554. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  4555. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  4556. sawCollapsedSpans = true;
  4557. }
  4558. if (marker.addToHistory)
  4559. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  4560. var curLine = from.line, cm = doc.cm, updateMaxLine;
  4561. doc.iter(curLine, to.line + 1, function(line) {
  4562. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  4563. updateMaxLine = true;
  4564. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  4565. addMarkedSpan(line, new MarkedSpan(marker,
  4566. curLine == from.line ? from.ch : null,
  4567. curLine == to.line ? to.ch : null));
  4568. ++curLine;
  4569. });
  4570. // lineIsHidden depends on the presence of the spans, so needs a second pass
  4571. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  4572. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  4573. });
  4574. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  4575. if (marker.readOnly) {
  4576. sawReadOnlySpans = true;
  4577. if (doc.history.done.length || doc.history.undone.length)
  4578. doc.clearHistory();
  4579. }
  4580. if (marker.collapsed) {
  4581. marker.id = ++nextMarkerId;
  4582. marker.atomic = true;
  4583. }
  4584. if (cm) {
  4585. // Sync editor state
  4586. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  4587. if (marker.collapsed)
  4588. regChange(cm, from.line, to.line + 1);
  4589. else if (marker.className || marker.title || marker.startStyle || marker.endStyle)
  4590. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  4591. if (marker.atomic) reCheckSelection(cm.doc);
  4592. signalLater(cm, "markerAdded", cm, marker);
  4593. }
  4594. return marker;
  4595. }
  4596. // SHARED TEXTMARKERS
  4597. // A shared marker spans multiple linked documents. It is
  4598. // implemented as a meta-marker-object controlling multiple normal
  4599. // markers.
  4600. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  4601. this.markers = markers;
  4602. this.primary = primary;
  4603. for (var i = 0; i < markers.length; ++i)
  4604. markers[i].parent = this;
  4605. };
  4606. eventMixin(SharedTextMarker);
  4607. SharedTextMarker.prototype.clear = function() {
  4608. if (this.explicitlyCleared) return;
  4609. this.explicitlyCleared = true;
  4610. for (var i = 0; i < this.markers.length; ++i)
  4611. this.markers[i].clear();
  4612. signalLater(this, "clear");
  4613. };
  4614. SharedTextMarker.prototype.find = function(side, lineObj) {
  4615. return this.primary.find(side, lineObj);
  4616. };
  4617. function markTextShared(doc, from, to, options, type) {
  4618. options = copyObj(options);
  4619. options.shared = false;
  4620. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  4621. var widget = options.widgetNode;
  4622. linkedDocs(doc, function(doc) {
  4623. if (widget) options.widgetNode = widget.cloneNode(true);
  4624. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  4625. for (var i = 0; i < doc.linked.length; ++i)
  4626. if (doc.linked[i].isParent) return;
  4627. primary = lst(markers);
  4628. });
  4629. return new SharedTextMarker(markers, primary);
  4630. }
  4631. function findSharedMarkers(doc) {
  4632. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  4633. function(m) { return m.parent; });
  4634. }
  4635. function copySharedMarkers(doc, markers) {
  4636. for (var i = 0; i < markers.length; i++) {
  4637. var marker = markers[i], pos = marker.find();
  4638. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  4639. if (cmp(mFrom, mTo)) {
  4640. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  4641. marker.markers.push(subMark);
  4642. subMark.parent = marker;
  4643. }
  4644. }
  4645. }
  4646. function detachSharedMarkers(markers) {
  4647. for (var i = 0; i < markers.length; i++) {
  4648. var marker = markers[i], linked = [marker.primary.doc];;
  4649. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  4650. for (var j = 0; j < marker.markers.length; j++) {
  4651. var subMarker = marker.markers[j];
  4652. if (indexOf(linked, subMarker.doc) == -1) {
  4653. subMarker.parent = null;
  4654. marker.markers.splice(j--, 1);
  4655. }
  4656. }
  4657. }
  4658. }
  4659. // TEXTMARKER SPANS
  4660. function MarkedSpan(marker, from, to) {
  4661. this.marker = marker;
  4662. this.from = from; this.to = to;
  4663. }
  4664. // Search an array of spans for a span matching the given marker.
  4665. function getMarkedSpanFor(spans, marker) {
  4666. if (spans) for (var i = 0; i < spans.length; ++i) {
  4667. var span = spans[i];
  4668. if (span.marker == marker) return span;
  4669. }
  4670. }
  4671. // Remove a span from an array, returning undefined if no spans are
  4672. // left (we don't store arrays for lines without spans).
  4673. function removeMarkedSpan(spans, span) {
  4674. for (var r, i = 0; i < spans.length; ++i)
  4675. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  4676. return r;
  4677. }
  4678. // Add a span to a line.
  4679. function addMarkedSpan(line, span) {
  4680. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  4681. span.marker.attachLine(line);
  4682. }
  4683. // Used for the algorithm that adjusts markers for a change in the
  4684. // document. These functions cut an array of spans at a given
  4685. // character position, returning an array of remaining chunks (or
  4686. // undefined if nothing remains).
  4687. function markedSpansBefore(old, startCh, isInsert) {
  4688. if (old) for (var i = 0, nw; i < old.length; ++i) {
  4689. var span = old[i], marker = span.marker;
  4690. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  4691. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  4692. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  4693. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  4694. }
  4695. }
  4696. return nw;
  4697. }
  4698. function markedSpansAfter(old, endCh, isInsert) {
  4699. if (old) for (var i = 0, nw; i < old.length; ++i) {
  4700. var span = old[i], marker = span.marker;
  4701. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  4702. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  4703. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  4704. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  4705. span.to == null ? null : span.to - endCh));
  4706. }
  4707. }
  4708. return nw;
  4709. }
  4710. // Given a change object, compute the new set of marker spans that
  4711. // cover the line in which the change took place. Removes spans
  4712. // entirely within the change, reconnects spans belonging to the
  4713. // same marker that appear on both sides of the change, and cuts off
  4714. // spans partially within the change. Returns an array of span
  4715. // arrays with one element for each line in (after) the change.
  4716. function stretchSpansOverChange(doc, change) {
  4717. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  4718. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  4719. if (!oldFirst && !oldLast) return null;
  4720. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  4721. // Get the spans that 'stick out' on both sides
  4722. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  4723. var last = markedSpansAfter(oldLast, endCh, isInsert);
  4724. // Next, merge those two ends
  4725. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  4726. if (first) {
  4727. // Fix up .to properties of first
  4728. for (var i = 0; i < first.length; ++i) {
  4729. var span = first[i];
  4730. if (span.to == null) {
  4731. var found = getMarkedSpanFor(last, span.marker);
  4732. if (!found) span.to = startCh;
  4733. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  4734. }
  4735. }
  4736. }
  4737. if (last) {
  4738. // Fix up .from in last (or move them into first in case of sameLine)
  4739. for (var i = 0; i < last.length; ++i) {
  4740. var span = last[i];
  4741. if (span.to != null) span.to += offset;
  4742. if (span.from == null) {
  4743. var found = getMarkedSpanFor(first, span.marker);
  4744. if (!found) {
  4745. span.from = offset;
  4746. if (sameLine) (first || (first = [])).push(span);
  4747. }
  4748. } else {
  4749. span.from += offset;
  4750. if (sameLine) (first || (first = [])).push(span);
  4751. }
  4752. }
  4753. }
  4754. // Make sure we didn't create any zero-length spans
  4755. if (first) first = clearEmptySpans(first);
  4756. if (last && last != first) last = clearEmptySpans(last);
  4757. var newMarkers = [first];
  4758. if (!sameLine) {
  4759. // Fill gap with whole-line-spans
  4760. var gap = change.text.length - 2, gapMarkers;
  4761. if (gap > 0 && first)
  4762. for (var i = 0; i < first.length; ++i)
  4763. if (first[i].to == null)
  4764. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  4765. for (var i = 0; i < gap; ++i)
  4766. newMarkers.push(gapMarkers);
  4767. newMarkers.push(last);
  4768. }
  4769. return newMarkers;
  4770. }
  4771. // Remove spans that are empty and don't have a clearWhenEmpty
  4772. // option of false.
  4773. function clearEmptySpans(spans) {
  4774. for (var i = 0; i < spans.length; ++i) {
  4775. var span = spans[i];
  4776. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  4777. spans.splice(i--, 1);
  4778. }
  4779. if (!spans.length) return null;
  4780. return spans;
  4781. }
  4782. // Used for un/re-doing changes from the history. Combines the
  4783. // result of computing the existing spans with the set of spans that
  4784. // existed in the history (so that deleting around a span and then
  4785. // undoing brings back the span).
  4786. function mergeOldSpans(doc, change) {
  4787. var old = getOldSpans(doc, change);
  4788. var stretched = stretchSpansOverChange(doc, change);
  4789. if (!old) return stretched;
  4790. if (!stretched) return old;
  4791. for (var i = 0; i < old.length; ++i) {
  4792. var oldCur = old[i], stretchCur = stretched[i];
  4793. if (oldCur && stretchCur) {
  4794. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4795. var span = stretchCur[j];
  4796. for (var k = 0; k < oldCur.length; ++k)
  4797. if (oldCur[k].marker == span.marker) continue spans;
  4798. oldCur.push(span);
  4799. }
  4800. } else if (stretchCur) {
  4801. old[i] = stretchCur;
  4802. }
  4803. }
  4804. return old;
  4805. }
  4806. // Used to 'clip' out readOnly ranges when making a change.
  4807. function removeReadOnlyRanges(doc, from, to) {
  4808. var markers = null;
  4809. doc.iter(from.line, to.line + 1, function(line) {
  4810. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  4811. var mark = line.markedSpans[i].marker;
  4812. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  4813. (markers || (markers = [])).push(mark);
  4814. }
  4815. });
  4816. if (!markers) return null;
  4817. var parts = [{from: from, to: to}];
  4818. for (var i = 0; i < markers.length; ++i) {
  4819. var mk = markers[i], m = mk.find(0);
  4820. for (var j = 0; j < parts.length; ++j) {
  4821. var p = parts[j];
  4822. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  4823. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  4824. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  4825. newParts.push({from: p.from, to: m.from});
  4826. if (dto > 0 || !mk.inclusiveRight && !dto)
  4827. newParts.push({from: m.to, to: p.to});
  4828. parts.splice.apply(parts, newParts);
  4829. j += newParts.length - 1;
  4830. }
  4831. }
  4832. return parts;
  4833. }
  4834. // Connect or disconnect spans from a line.
  4835. function detachMarkedSpans(line) {
  4836. var spans = line.markedSpans;
  4837. if (!spans) return;
  4838. for (var i = 0; i < spans.length; ++i)
  4839. spans[i].marker.detachLine(line);
  4840. line.markedSpans = null;
  4841. }
  4842. function attachMarkedSpans(line, spans) {
  4843. if (!spans) return;
  4844. for (var i = 0; i < spans.length; ++i)
  4845. spans[i].marker.attachLine(line);
  4846. line.markedSpans = spans;
  4847. }
  4848. // Helpers used when computing which overlapping collapsed span
  4849. // counts as the larger one.
  4850. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  4851. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  4852. // Returns a number indicating which of two overlapping collapsed
  4853. // spans is larger (and thus includes the other). Falls back to
  4854. // comparing ids when the spans cover exactly the same range.
  4855. function compareCollapsedMarkers(a, b) {
  4856. var lenDiff = a.lines.length - b.lines.length;
  4857. if (lenDiff != 0) return lenDiff;
  4858. var aPos = a.find(), bPos = b.find();
  4859. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  4860. if (fromCmp) return -fromCmp;
  4861. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  4862. if (toCmp) return toCmp;
  4863. return b.id - a.id;
  4864. }
  4865. // Find out whether a line ends or starts in a collapsed span. If
  4866. // so, return the marker for that span.
  4867. function collapsedSpanAtSide(line, start) {
  4868. var sps = sawCollapsedSpans && line.markedSpans, found;
  4869. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  4870. sp = sps[i];
  4871. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  4872. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  4873. found = sp.marker;
  4874. }
  4875. return found;
  4876. }
  4877. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  4878. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  4879. // Test whether there exists a collapsed span that partially
  4880. // overlaps (covers the start or end, but not both) of a new span.
  4881. // Such overlap is not allowed.
  4882. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  4883. var line = getLine(doc, lineNo);
  4884. var sps = sawCollapsedSpans && line.markedSpans;
  4885. if (sps) for (var i = 0; i < sps.length; ++i) {
  4886. var sp = sps[i];
  4887. if (!sp.marker.collapsed) continue;
  4888. var found = sp.marker.find(0);
  4889. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  4890. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  4891. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  4892. if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
  4893. fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
  4894. return true;
  4895. }
  4896. }
  4897. // A visual line is a line as drawn on the screen. Folding, for
  4898. // example, can cause multiple logical lines to appear on the same
  4899. // visual line. This finds the start of the visual line that the
  4900. // given line is part of (usually that is the line itself).
  4901. function visualLine(line) {
  4902. var merged;
  4903. while (merged = collapsedSpanAtStart(line))
  4904. line = merged.find(-1, true).line;
  4905. return line;
  4906. }
  4907. // Returns an array of logical lines that continue the visual line
  4908. // started by the argument, or undefined if there are no such lines.
  4909. function visualLineContinued(line) {
  4910. var merged, lines;
  4911. while (merged = collapsedSpanAtEnd(line)) {
  4912. line = merged.find(1, true).line;
  4913. (lines || (lines = [])).push(line);
  4914. }
  4915. return lines;
  4916. }
  4917. // Get the line number of the start of the visual line that the
  4918. // given line number is part of.
  4919. function visualLineNo(doc, lineN) {
  4920. var line = getLine(doc, lineN), vis = visualLine(line);
  4921. if (line == vis) return lineN;
  4922. return lineNo(vis);
  4923. }
  4924. // Get the line number of the start of the next visual line after
  4925. // the given line.
  4926. function visualLineEndNo(doc, lineN) {
  4927. if (lineN > doc.lastLine()) return lineN;
  4928. var line = getLine(doc, lineN), merged;
  4929. if (!lineIsHidden(doc, line)) return lineN;
  4930. while (merged = collapsedSpanAtEnd(line))
  4931. line = merged.find(1, true).line;
  4932. return lineNo(line) + 1;
  4933. }
  4934. // Compute whether a line is hidden. Lines count as hidden when they
  4935. // are part of a visual line that starts with another line, or when
  4936. // they are entirely covered by collapsed, non-widget span.
  4937. function lineIsHidden(doc, line) {
  4938. var sps = sawCollapsedSpans && line.markedSpans;
  4939. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  4940. sp = sps[i];
  4941. if (!sp.marker.collapsed) continue;
  4942. if (sp.from == null) return true;
  4943. if (sp.marker.widgetNode) continue;
  4944. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  4945. return true;
  4946. }
  4947. }
  4948. function lineIsHiddenInner(doc, line, span) {
  4949. if (span.to == null) {
  4950. var end = span.marker.find(1, true);
  4951. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  4952. }
  4953. if (span.marker.inclusiveRight && span.to == line.text.length)
  4954. return true;
  4955. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  4956. sp = line.markedSpans[i];
  4957. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  4958. (sp.to == null || sp.to != span.from) &&
  4959. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  4960. lineIsHiddenInner(doc, line, sp)) return true;
  4961. }
  4962. }
  4963. // LINE WIDGETS
  4964. // Line widgets are block elements displayed above or below a line.
  4965. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
  4966. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  4967. this[opt] = options[opt];
  4968. this.cm = cm;
  4969. this.node = node;
  4970. };
  4971. eventMixin(LineWidget);
  4972. function adjustScrollWhenAboveVisible(cm, line, diff) {
  4973. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  4974. addToScrollPos(cm, null, diff);
  4975. }
  4976. LineWidget.prototype.clear = function() {
  4977. var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  4978. if (no == null || !ws) return;
  4979. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  4980. if (!ws.length) line.widgets = null;
  4981. var height = widgetHeight(this);
  4982. runInOp(cm, function() {
  4983. adjustScrollWhenAboveVisible(cm, line, -height);
  4984. regLineChange(cm, no, "widget");
  4985. updateLineHeight(line, Math.max(0, line.height - height));
  4986. });
  4987. };
  4988. LineWidget.prototype.changed = function() {
  4989. var oldH = this.height, cm = this.cm, line = this.line;
  4990. this.height = null;
  4991. var diff = widgetHeight(this) - oldH;
  4992. if (!diff) return;
  4993. runInOp(cm, function() {
  4994. cm.curOp.forceUpdate = true;
  4995. adjustScrollWhenAboveVisible(cm, line, diff);
  4996. updateLineHeight(line, line.height + diff);
  4997. });
  4998. };
  4999. function widgetHeight(widget) {
  5000. if (widget.height != null) return widget.height;
  5001. if (!contains(document.body, widget.node))
  5002. removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
  5003. return widget.height = widget.node.offsetHeight;
  5004. }
  5005. function addLineWidget(cm, handle, node, options) {
  5006. var widget = new LineWidget(cm, node, options);
  5007. if (widget.noHScroll) cm.display.alignWidgets = true;
  5008. changeLine(cm, handle, "widget", function(line) {
  5009. var widgets = line.widgets || (line.widgets = []);
  5010. if (widget.insertAt == null) widgets.push(widget);
  5011. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  5012. widget.line = line;
  5013. if (!lineIsHidden(cm.doc, line)) {
  5014. var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
  5015. updateLineHeight(line, line.height + widgetHeight(widget));
  5016. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  5017. cm.curOp.forceUpdate = true;
  5018. }
  5019. return true;
  5020. });
  5021. return widget;
  5022. }
  5023. // LINE DATA STRUCTURE
  5024. // Line objects. These hold state related to a line, including
  5025. // highlighting info (the styles array).
  5026. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  5027. this.text = text;
  5028. attachMarkedSpans(this, markedSpans);
  5029. this.height = estimateHeight ? estimateHeight(this) : 1;
  5030. };
  5031. eventMixin(Line);
  5032. Line.prototype.lineNo = function() { return lineNo(this); };
  5033. // Change the content (text, markers) of a line. Automatically
  5034. // invalidates cached information and tries to re-estimate the
  5035. // line's height.
  5036. function updateLine(line, text, markedSpans, estimateHeight) {
  5037. line.text = text;
  5038. if (line.stateAfter) line.stateAfter = null;
  5039. if (line.styles) line.styles = null;
  5040. if (line.order != null) line.order = null;
  5041. detachMarkedSpans(line);
  5042. attachMarkedSpans(line, markedSpans);
  5043. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  5044. if (estHeight != line.height) updateLineHeight(line, estHeight);
  5045. }
  5046. // Detach a line from the document tree and its markers.
  5047. function cleanUpLine(line) {
  5048. line.parent = null;
  5049. detachMarkedSpans(line);
  5050. }
  5051. function extractLineClasses(type, output) {
  5052. if (type) for (;;) {
  5053. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  5054. if (!lineClass) break;
  5055. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  5056. var prop = lineClass[1] ? "bgClass" : "textClass";
  5057. if (output[prop] == null)
  5058. output[prop] = lineClass[2];
  5059. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  5060. output[prop] += " " + lineClass[2];
  5061. }
  5062. return type;
  5063. }
  5064. function callBlankLine(mode, state) {
  5065. if (mode.blankLine) return mode.blankLine(state);
  5066. if (!mode.innerMode) return;
  5067. var inner = CodeMirror.innerMode(mode, state);
  5068. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  5069. }
  5070. function readToken(mode, stream, state) {
  5071. var style = mode.token(stream, state);
  5072. if (stream.pos <= stream.start)
  5073. throw new Error("Mode " + mode.name + " failed to advance stream.");
  5074. return style;
  5075. }
  5076. // Run the given mode's parser over a line, calling f for each token.
  5077. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  5078. var flattenSpans = mode.flattenSpans;
  5079. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  5080. var curStart = 0, curStyle = null;
  5081. var stream = new StringStream(text, cm.options.tabSize), style;
  5082. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  5083. while (!stream.eol()) {
  5084. if (stream.pos > cm.options.maxHighlightLength) {
  5085. flattenSpans = false;
  5086. if (forceToEnd) processLine(cm, text, state, stream.pos);
  5087. stream.pos = text.length;
  5088. style = null;
  5089. } else {
  5090. style = extractLineClasses(readToken(mode, stream, state), lineClasses);
  5091. }
  5092. if (cm.options.addModeClass) {
  5093. var mName = CodeMirror.innerMode(mode, state).mode.name;
  5094. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  5095. }
  5096. if (!flattenSpans || curStyle != style) {
  5097. if (curStart < stream.start) f(stream.start, curStyle);
  5098. curStart = stream.start; curStyle = style;
  5099. }
  5100. stream.start = stream.pos;
  5101. }
  5102. while (curStart < stream.pos) {
  5103. // Webkit seems to refuse to render text nodes longer than 57444 characters
  5104. var pos = Math.min(stream.pos, curStart + 50000);
  5105. f(pos, curStyle);
  5106. curStart = pos;
  5107. }
  5108. }
  5109. // Compute a style array (an array starting with a mode generation
  5110. // -- for invalidation -- followed by pairs of end positions and
  5111. // style strings), which is used to highlight the tokens on the
  5112. // line.
  5113. function highlightLine(cm, line, state, forceToEnd) {
  5114. // A styles array always starts with a number identifying the
  5115. // mode/overlays that it is based on (for easy invalidation).
  5116. var st = [cm.state.modeGen], lineClasses = {};
  5117. // Compute the base array of styles
  5118. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  5119. st.push(end, style);
  5120. }, lineClasses, forceToEnd);
  5121. // Run overlays, adjust style array.
  5122. for (var o = 0; o < cm.state.overlays.length; ++o) {
  5123. var overlay = cm.state.overlays[o], i = 1, at = 0;
  5124. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  5125. var start = i;
  5126. // Ensure there's a token end at the current position, and that i points at it
  5127. while (at < end) {
  5128. var i_end = st[i];
  5129. if (i_end > end)
  5130. st.splice(i, 1, end, st[i+1], i_end);
  5131. i += 2;
  5132. at = Math.min(end, i_end);
  5133. }
  5134. if (!style) return;
  5135. if (overlay.opaque) {
  5136. st.splice(start, i - start, end, "cm-overlay " + style);
  5137. i = start + 2;
  5138. } else {
  5139. for (; start < i; start += 2) {
  5140. var cur = st[start+1];
  5141. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  5142. }
  5143. }
  5144. }, lineClasses);
  5145. }
  5146. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  5147. }
  5148. function getLineStyles(cm, line) {
  5149. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  5150. var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  5151. line.styles = result.styles;
  5152. if (result.classes) line.styleClasses = result.classes;
  5153. else if (line.styleClasses) line.styleClasses = null;
  5154. }
  5155. return line.styles;
  5156. }
  5157. // Lightweight form of highlight -- proceed over this line and
  5158. // update state, but don't save a style array. Used for lines that
  5159. // aren't currently visible.
  5160. function processLine(cm, text, state, startAt) {
  5161. var mode = cm.doc.mode;
  5162. var stream = new StringStream(text, cm.options.tabSize);
  5163. stream.start = stream.pos = startAt || 0;
  5164. if (text == "") callBlankLine(mode, state);
  5165. while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
  5166. readToken(mode, stream, state);
  5167. stream.start = stream.pos;
  5168. }
  5169. }
  5170. // Convert a style as returned by a mode (either null, or a string
  5171. // containing one or more styles) to a CSS style. This is cached,
  5172. // and also looks for line-wide styles.
  5173. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  5174. function interpretTokenStyle(style, options) {
  5175. if (!style || /^\s*$/.test(style)) return null;
  5176. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  5177. return cache[style] ||
  5178. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  5179. }
  5180. // Render the DOM representation of the text of a line. Also builds
  5181. // up a 'line map', which points at the DOM nodes that represent
  5182. // specific stretches of text, and is used by the measuring code.
  5183. // The returned object contains the DOM node, this map, and
  5184. // information about line-wide styles that were set by the mode.
  5185. function buildLineContent(cm, lineView) {
  5186. // The padding-right forces the element to have a 'border', which
  5187. // is needed on Webkit to be able to get line-level bounding
  5188. // rectangles for it (in measureChar).
  5189. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  5190. var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
  5191. lineView.measure = {};
  5192. // Iterate over the logical lines that make up this visual line.
  5193. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  5194. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  5195. builder.pos = 0;
  5196. builder.addToken = buildToken;
  5197. // Optionally wire in some hacks into the token-rendering
  5198. // algorithm, to deal with browser quirks.
  5199. if ((ie || webkit) && cm.getOption("lineWrapping"))
  5200. builder.addToken = buildTokenSplitSpaces(builder.addToken);
  5201. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  5202. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  5203. builder.map = [];
  5204. insertLineContent(line, builder, getLineStyles(cm, line));
  5205. if (line.styleClasses) {
  5206. if (line.styleClasses.bgClass)
  5207. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  5208. if (line.styleClasses.textClass)
  5209. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  5210. }
  5211. // Ensure at least a single node is present, for measuring.
  5212. if (builder.map.length == 0)
  5213. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  5214. // Store the map and a cache object for the current logical line
  5215. if (i == 0) {
  5216. lineView.measure.map = builder.map;
  5217. lineView.measure.cache = {};
  5218. } else {
  5219. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  5220. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  5221. }
  5222. }
  5223. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  5224. return builder;
  5225. }
  5226. function defaultSpecialCharPlaceholder(ch) {
  5227. var token = elt("span", "\u2022", "cm-invalidchar");
  5228. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  5229. return token;
  5230. }
  5231. // Build up the DOM representation for a single token, and add it to
  5232. // the line map. Takes care to render special characters separately.
  5233. function buildToken(builder, text, style, startStyle, endStyle, title) {
  5234. if (!text) return;
  5235. var special = builder.cm.options.specialChars, mustWrap = false;
  5236. if (!special.test(text)) {
  5237. builder.col += text.length;
  5238. var content = document.createTextNode(text);
  5239. builder.map.push(builder.pos, builder.pos + text.length, content);
  5240. if (ie_upto8) mustWrap = true;
  5241. builder.pos += text.length;
  5242. } else {
  5243. var content = document.createDocumentFragment(), pos = 0;
  5244. while (true) {
  5245. special.lastIndex = pos;
  5246. var m = special.exec(text);
  5247. var skipped = m ? m.index - pos : text.length - pos;
  5248. if (skipped) {
  5249. var txt = document.createTextNode(text.slice(pos, pos + skipped));
  5250. if (ie_upto8) content.appendChild(elt("span", [txt]));
  5251. else content.appendChild(txt);
  5252. builder.map.push(builder.pos, builder.pos + skipped, txt);
  5253. builder.col += skipped;
  5254. builder.pos += skipped;
  5255. }
  5256. if (!m) break;
  5257. pos += skipped + 1;
  5258. if (m[0] == "\t") {
  5259. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  5260. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  5261. builder.col += tabWidth;
  5262. } else {
  5263. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  5264. if (ie_upto8) content.appendChild(elt("span", [txt]));
  5265. else content.appendChild(txt);
  5266. builder.col += 1;
  5267. }
  5268. builder.map.push(builder.pos, builder.pos + 1, txt);
  5269. builder.pos++;
  5270. }
  5271. }
  5272. if (style || startStyle || endStyle || mustWrap) {
  5273. var fullStyle = style || "";
  5274. if (startStyle) fullStyle += startStyle;
  5275. if (endStyle) fullStyle += endStyle;
  5276. var token = elt("span", [content], fullStyle);
  5277. if (title) token.title = title;
  5278. return builder.content.appendChild(token);
  5279. }
  5280. builder.content.appendChild(content);
  5281. }
  5282. function buildTokenSplitSpaces(inner) {
  5283. function split(old) {
  5284. var out = " ";
  5285. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  5286. out += " ";
  5287. return out;
  5288. }
  5289. return function(builder, text, style, startStyle, endStyle, title) {
  5290. inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
  5291. };
  5292. }
  5293. // Work around nonsense dimensions being reported for stretches of
  5294. // right-to-left text.
  5295. function buildTokenBadBidi(inner, order) {
  5296. return function(builder, text, style, startStyle, endStyle, title) {
  5297. style = style ? style + " cm-force-border" : "cm-force-border";
  5298. var start = builder.pos, end = start + text.length;
  5299. for (;;) {
  5300. // Find the part that overlaps with the start of this text
  5301. for (var i = 0; i < order.length; i++) {
  5302. var part = order[i];
  5303. if (part.to > start && part.from <= start) break;
  5304. }
  5305. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
  5306. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
  5307. startStyle = null;
  5308. text = text.slice(part.to - start);
  5309. start = part.to;
  5310. }
  5311. };
  5312. }
  5313. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  5314. var widget = !ignoreWidget && marker.widgetNode;
  5315. if (widget) {
  5316. builder.map.push(builder.pos, builder.pos + size, widget);
  5317. builder.content.appendChild(widget);
  5318. }
  5319. builder.pos += size;
  5320. }
  5321. // Outputs a number of spans to make up a line, taking highlighting
  5322. // and marked text into account.
  5323. function insertLineContent(line, builder, styles) {
  5324. var spans = line.markedSpans, allText = line.text, at = 0;
  5325. if (!spans) {
  5326. for (var i = 1; i < styles.length; i+=2)
  5327. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  5328. return;
  5329. }
  5330. var len = allText.length, pos = 0, i = 1, text = "", style;
  5331. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  5332. for (;;) {
  5333. if (nextChange == pos) { // Update current marker set
  5334. spanStyle = spanEndStyle = spanStartStyle = title = "";
  5335. collapsed = null; nextChange = Infinity;
  5336. var foundBookmarks = [];
  5337. for (var j = 0; j < spans.length; ++j) {
  5338. var sp = spans[j], m = sp.marker;
  5339. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  5340. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  5341. if (m.className) spanStyle += " " + m.className;
  5342. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  5343. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  5344. if (m.title && !title) title = m.title;
  5345. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  5346. collapsed = sp;
  5347. } else if (sp.from > pos && nextChange > sp.from) {
  5348. nextChange = sp.from;
  5349. }
  5350. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
  5351. }
  5352. if (collapsed && (collapsed.from || 0) == pos) {
  5353. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  5354. collapsed.marker, collapsed.from == null);
  5355. if (collapsed.to == null) return;
  5356. }
  5357. if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
  5358. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  5359. }
  5360. if (pos >= len) break;
  5361. var upto = Math.min(len, nextChange);
  5362. while (true) {
  5363. if (text) {
  5364. var end = pos + text.length;
  5365. if (!collapsed) {
  5366. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  5367. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  5368. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
  5369. }
  5370. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  5371. pos = end;
  5372. spanStartStyle = "";
  5373. }
  5374. text = allText.slice(at, at = styles[i++]);
  5375. style = interpretTokenStyle(styles[i++], builder.cm.options);
  5376. }
  5377. }
  5378. }
  5379. // DOCUMENT DATA STRUCTURE
  5380. // By default, updates that start and end at the beginning of a line
  5381. // are treated specially, in order to make the association of line
  5382. // widgets and marker elements with the text behave more intuitive.
  5383. function isWholeLineUpdate(doc, change) {
  5384. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  5385. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  5386. }
  5387. // Perform a change on the document data structure.
  5388. function updateDoc(doc, change, markedSpans, estimateHeight) {
  5389. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  5390. function update(line, text, spans) {
  5391. updateLine(line, text, spans, estimateHeight);
  5392. signalLater(line, "change", line, change);
  5393. }
  5394. var from = change.from, to = change.to, text = change.text;
  5395. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  5396. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  5397. // Adjust the line structure
  5398. if (isWholeLineUpdate(doc, change)) {
  5399. // This is a whole-line replace. Treated specially to make
  5400. // sure line objects move the way they are supposed to.
  5401. for (var i = 0, added = []; i < text.length - 1; ++i)
  5402. added.push(new Line(text[i], spansFor(i), estimateHeight));
  5403. update(lastLine, lastLine.text, lastSpans);
  5404. if (nlines) doc.remove(from.line, nlines);
  5405. if (added.length) doc.insert(from.line, added);
  5406. } else if (firstLine == lastLine) {
  5407. if (text.length == 1) {
  5408. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  5409. } else {
  5410. for (var added = [], i = 1; i < text.length - 1; ++i)
  5411. added.push(new Line(text[i], spansFor(i), estimateHeight));
  5412. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  5413. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5414. doc.insert(from.line + 1, added);
  5415. }
  5416. } else if (text.length == 1) {
  5417. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  5418. doc.remove(from.line + 1, nlines);
  5419. } else {
  5420. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  5421. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  5422. for (var i = 1, added = []; i < text.length - 1; ++i)
  5423. added.push(new Line(text[i], spansFor(i), estimateHeight));
  5424. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  5425. doc.insert(from.line + 1, added);
  5426. }
  5427. signalLater(doc, "change", doc, change);
  5428. }
  5429. // The document is represented as a BTree consisting of leaves, with
  5430. // chunk of lines in them, and branches, with up to ten leaves or
  5431. // other branch nodes below them. The top node is always a branch
  5432. // node, and is the document object itself (meaning it has
  5433. // additional methods and properties).
  5434. //
  5435. // All nodes have parent links. The tree is used both to go from
  5436. // line numbers to line objects, and to go from objects to numbers.
  5437. // It also indexes by height, and is used to convert between height
  5438. // and line object, and to find the total height of the document.
  5439. //
  5440. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5441. function LeafChunk(lines) {
  5442. this.lines = lines;
  5443. this.parent = null;
  5444. for (var i = 0, height = 0; i < lines.length; ++i) {
  5445. lines[i].parent = this;
  5446. height += lines[i].height;
  5447. }
  5448. this.height = height;
  5449. }
  5450. LeafChunk.prototype = {
  5451. chunkSize: function() { return this.lines.length; },
  5452. // Remove the n lines at offset 'at'.
  5453. removeInner: function(at, n) {
  5454. for (var i = at, e = at + n; i < e; ++i) {
  5455. var line = this.lines[i];
  5456. this.height -= line.height;
  5457. cleanUpLine(line);
  5458. signalLater(line, "delete");
  5459. }
  5460. this.lines.splice(at, n);
  5461. },
  5462. // Helper used to collapse a small branch into a single leaf.
  5463. collapse: function(lines) {
  5464. lines.push.apply(lines, this.lines);
  5465. },
  5466. // Insert the given array of lines at offset 'at', count them as
  5467. // having the given height.
  5468. insertInner: function(at, lines, height) {
  5469. this.height += height;
  5470. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5471. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  5472. },
  5473. // Used to iterate over a part of the tree.
  5474. iterN: function(at, n, op) {
  5475. for (var e = at + n; at < e; ++at)
  5476. if (op(this.lines[at])) return true;
  5477. }
  5478. };
  5479. function BranchChunk(children) {
  5480. this.children = children;
  5481. var size = 0, height = 0;
  5482. for (var i = 0; i < children.length; ++i) {
  5483. var ch = children[i];
  5484. size += ch.chunkSize(); height += ch.height;
  5485. ch.parent = this;
  5486. }
  5487. this.size = size;
  5488. this.height = height;
  5489. this.parent = null;
  5490. }
  5491. BranchChunk.prototype = {
  5492. chunkSize: function() { return this.size; },
  5493. removeInner: function(at, n) {
  5494. this.size -= n;
  5495. for (var i = 0; i < this.children.length; ++i) {
  5496. var child = this.children[i], sz = child.chunkSize();
  5497. if (at < sz) {
  5498. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5499. child.removeInner(at, rm);
  5500. this.height -= oldHeight - child.height;
  5501. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5502. if ((n -= rm) == 0) break;
  5503. at = 0;
  5504. } else at -= sz;
  5505. }
  5506. // If the result is smaller than 25 lines, ensure that it is a
  5507. // single leaf node.
  5508. if (this.size - n < 25 &&
  5509. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5510. var lines = [];
  5511. this.collapse(lines);
  5512. this.children = [new LeafChunk(lines)];
  5513. this.children[0].parent = this;
  5514. }
  5515. },
  5516. collapse: function(lines) {
  5517. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  5518. },
  5519. insertInner: function(at, lines, height) {
  5520. this.size += lines.length;
  5521. this.height += height;
  5522. for (var i = 0; i < this.children.length; ++i) {
  5523. var child = this.children[i], sz = child.chunkSize();
  5524. if (at <= sz) {
  5525. child.insertInner(at, lines, height);
  5526. if (child.lines && child.lines.length > 50) {
  5527. while (child.lines.length > 50) {
  5528. var spilled = child.lines.splice(child.lines.length - 25, 25);
  5529. var newleaf = new LeafChunk(spilled);
  5530. child.height -= newleaf.height;
  5531. this.children.splice(i + 1, 0, newleaf);
  5532. newleaf.parent = this;
  5533. }
  5534. this.maybeSpill();
  5535. }
  5536. break;
  5537. }
  5538. at -= sz;
  5539. }
  5540. },
  5541. // When a node has grown, check whether it should be split.
  5542. maybeSpill: function() {
  5543. if (this.children.length <= 10) return;
  5544. var me = this;
  5545. do {
  5546. var spilled = me.children.splice(me.children.length - 5, 5);
  5547. var sibling = new BranchChunk(spilled);
  5548. if (!me.parent) { // Become the parent node
  5549. var copy = new BranchChunk(me.children);
  5550. copy.parent = me;
  5551. me.children = [copy, sibling];
  5552. me = copy;
  5553. } else {
  5554. me.size -= sibling.size;
  5555. me.height -= sibling.height;
  5556. var myIndex = indexOf(me.parent.children, me);
  5557. me.parent.children.splice(myIndex + 1, 0, sibling);
  5558. }
  5559. sibling.parent = me.parent;
  5560. } while (me.children.length > 10);
  5561. me.parent.maybeSpill();
  5562. },
  5563. iterN: function(at, n, op) {
  5564. for (var i = 0; i < this.children.length; ++i) {
  5565. var child = this.children[i], sz = child.chunkSize();
  5566. if (at < sz) {
  5567. var used = Math.min(n, sz - at);
  5568. if (child.iterN(at, used, op)) return true;
  5569. if ((n -= used) == 0) break;
  5570. at = 0;
  5571. } else at -= sz;
  5572. }
  5573. }
  5574. };
  5575. var nextDocId = 0;
  5576. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  5577. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  5578. if (firstLine == null) firstLine = 0;
  5579. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5580. this.first = firstLine;
  5581. this.scrollTop = this.scrollLeft = 0;
  5582. this.cantEdit = false;
  5583. this.cleanGeneration = 1;
  5584. this.frontier = firstLine;
  5585. var start = Pos(firstLine, 0);
  5586. this.sel = simpleSelection(start);
  5587. this.history = new History(null);
  5588. this.id = ++nextDocId;
  5589. this.modeOption = mode;
  5590. if (typeof text == "string") text = splitLines(text);
  5591. updateDoc(this, {from: start, to: start, text: text});
  5592. setSelection(this, simpleSelection(start), sel_dontScroll);
  5593. };
  5594. Doc.prototype = createObj(BranchChunk.prototype, {
  5595. constructor: Doc,
  5596. // Iterate over the document. Supports two forms -- with only one
  5597. // argument, it calls that for each line in the document. With
  5598. // three, it iterates over the range given by the first two (with
  5599. // the second being non-inclusive).
  5600. iter: function(from, to, op) {
  5601. if (op) this.iterN(from - this.first, to - from, op);
  5602. else this.iterN(this.first, this.first + this.size, from);
  5603. },
  5604. // Non-public interface for adding and removing lines.
  5605. insert: function(at, lines) {
  5606. var height = 0;
  5607. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  5608. this.insertInner(at - this.first, lines, height);
  5609. },
  5610. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5611. // From here, the methods are part of the public interface. Most
  5612. // are also available from CodeMirror (editor) instances.
  5613. getValue: function(lineSep) {
  5614. var lines = getLines(this, this.first, this.first + this.size);
  5615. if (lineSep === false) return lines;
  5616. return lines.join(lineSep || "\n");
  5617. },
  5618. setValue: docMethodOp(function(code) {
  5619. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5620. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5621. text: splitLines(code), origin: "setValue"}, true);
  5622. setSelection(this, simpleSelection(top));
  5623. }),
  5624. replaceRange: function(code, from, to, origin) {
  5625. from = clipPos(this, from);
  5626. to = to ? clipPos(this, to) : from;
  5627. replaceRange(this, code, from, to, origin);
  5628. },
  5629. getRange: function(from, to, lineSep) {
  5630. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5631. if (lineSep === false) return lines;
  5632. return lines.join(lineSep || "\n");
  5633. },
  5634. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  5635. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  5636. getLineNumber: function(line) {return lineNo(line);},
  5637. getLineHandleVisualStart: function(line) {
  5638. if (typeof line == "number") line = getLine(this, line);
  5639. return visualLine(line);
  5640. },
  5641. lineCount: function() {return this.size;},
  5642. firstLine: function() {return this.first;},
  5643. lastLine: function() {return this.first + this.size - 1;},
  5644. clipPos: function(pos) {return clipPos(this, pos);},
  5645. getCursor: function(start) {
  5646. var range = this.sel.primary(), pos;
  5647. if (start == null || start == "head") pos = range.head;
  5648. else if (start == "anchor") pos = range.anchor;
  5649. else if (start == "end" || start == "to" || start === false) pos = range.to();
  5650. else pos = range.from();
  5651. return pos;
  5652. },
  5653. listSelections: function() { return this.sel.ranges; },
  5654. somethingSelected: function() {return this.sel.somethingSelected();},
  5655. setCursor: docMethodOp(function(line, ch, options) {
  5656. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5657. }),
  5658. setSelection: docMethodOp(function(anchor, head, options) {
  5659. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5660. }),
  5661. extendSelection: docMethodOp(function(head, other, options) {
  5662. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5663. }),
  5664. extendSelections: docMethodOp(function(heads, options) {
  5665. extendSelections(this, clipPosArray(this, heads, options));
  5666. }),
  5667. extendSelectionsBy: docMethodOp(function(f, options) {
  5668. extendSelections(this, map(this.sel.ranges, f), options);
  5669. }),
  5670. setSelections: docMethodOp(function(ranges, primary, options) {
  5671. if (!ranges.length) return;
  5672. for (var i = 0, out = []; i < ranges.length; i++)
  5673. out[i] = new Range(clipPos(this, ranges[i].anchor),
  5674. clipPos(this, ranges[i].head));
  5675. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  5676. setSelection(this, normalizeSelection(out, primary), options);
  5677. }),
  5678. addSelection: docMethodOp(function(anchor, head, options) {
  5679. var ranges = this.sel.ranges.slice(0);
  5680. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5681. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  5682. }),
  5683. getSelection: function(lineSep) {
  5684. var ranges = this.sel.ranges, lines;
  5685. for (var i = 0; i < ranges.length; i++) {
  5686. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5687. lines = lines ? lines.concat(sel) : sel;
  5688. }
  5689. if (lineSep === false) return lines;
  5690. else return lines.join(lineSep || "\n");
  5691. },
  5692. getSelections: function(lineSep) {
  5693. var parts = [], ranges = this.sel.ranges;
  5694. for (var i = 0; i < ranges.length; i++) {
  5695. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5696. if (lineSep !== false) sel = sel.join(lineSep || "\n");
  5697. parts[i] = sel;
  5698. }
  5699. return parts;
  5700. },
  5701. replaceSelection: function(code, collapse, origin) {
  5702. var dup = [];
  5703. for (var i = 0; i < this.sel.ranges.length; i++)
  5704. dup[i] = code;
  5705. this.replaceSelections(dup, collapse, origin || "+input");
  5706. },
  5707. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5708. var changes = [], sel = this.sel;
  5709. for (var i = 0; i < sel.ranges.length; i++) {
  5710. var range = sel.ranges[i];
  5711. changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
  5712. }
  5713. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5714. for (var i = changes.length - 1; i >= 0; i--)
  5715. makeChange(this, changes[i]);
  5716. if (newSel) setSelectionReplaceHistory(this, newSel);
  5717. else if (this.cm) ensureCursorVisible(this.cm);
  5718. }),
  5719. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5720. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5721. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5722. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5723. setExtending: function(val) {this.extend = val;},
  5724. getExtending: function() {return this.extend;},
  5725. historySize: function() {
  5726. var hist = this.history, done = 0, undone = 0;
  5727. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  5728. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  5729. return {undo: done, redo: undone};
  5730. },
  5731. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  5732. markClean: function() {
  5733. this.cleanGeneration = this.changeGeneration(true);
  5734. },
  5735. changeGeneration: function(forceSplit) {
  5736. if (forceSplit)
  5737. this.history.lastOp = this.history.lastOrigin = null;
  5738. return this.history.generation;
  5739. },
  5740. isClean: function (gen) {
  5741. return this.history.generation == (gen || this.cleanGeneration);
  5742. },
  5743. getHistory: function() {
  5744. return {done: copyHistoryArray(this.history.done),
  5745. undone: copyHistoryArray(this.history.undone)};
  5746. },
  5747. setHistory: function(histData) {
  5748. var hist = this.history = new History(this.history.maxGeneration);
  5749. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5750. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5751. },
  5752. markText: function(from, to, options) {
  5753. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  5754. },
  5755. setBookmark: function(pos, options) {
  5756. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5757. insertLeft: options && options.insertLeft,
  5758. clearWhenEmpty: false, shared: options && options.shared};
  5759. pos = clipPos(this, pos);
  5760. return markText(this, pos, pos, realOpts, "bookmark");
  5761. },
  5762. findMarksAt: function(pos) {
  5763. pos = clipPos(this, pos);
  5764. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5765. if (spans) for (var i = 0; i < spans.length; ++i) {
  5766. var span = spans[i];
  5767. if ((span.from == null || span.from <= pos.ch) &&
  5768. (span.to == null || span.to >= pos.ch))
  5769. markers.push(span.marker.parent || span.marker);
  5770. }
  5771. return markers;
  5772. },
  5773. findMarks: function(from, to, filter) {
  5774. from = clipPos(this, from); to = clipPos(this, to);
  5775. var found = [], lineNo = from.line;
  5776. this.iter(from.line, to.line + 1, function(line) {
  5777. var spans = line.markedSpans;
  5778. if (spans) for (var i = 0; i < spans.length; i++) {
  5779. var span = spans[i];
  5780. if (!(lineNo == from.line && from.ch > span.to ||
  5781. span.from == null && lineNo != from.line||
  5782. lineNo == to.line && span.from > to.ch) &&
  5783. (!filter || filter(span.marker)))
  5784. found.push(span.marker.parent || span.marker);
  5785. }
  5786. ++lineNo;
  5787. });
  5788. return found;
  5789. },
  5790. getAllMarks: function() {
  5791. var markers = [];
  5792. this.iter(function(line) {
  5793. var sps = line.markedSpans;
  5794. if (sps) for (var i = 0; i < sps.length; ++i)
  5795. if (sps[i].from != null) markers.push(sps[i].marker);
  5796. });
  5797. return markers;
  5798. },
  5799. posFromIndex: function(off) {
  5800. var ch, lineNo = this.first;
  5801. this.iter(function(line) {
  5802. var sz = line.text.length + 1;
  5803. if (sz > off) { ch = off; return true; }
  5804. off -= sz;
  5805. ++lineNo;
  5806. });
  5807. return clipPos(this, Pos(lineNo, ch));
  5808. },
  5809. indexFromPos: function (coords) {
  5810. coords = clipPos(this, coords);
  5811. var index = coords.ch;
  5812. if (coords.line < this.first || coords.ch < 0) return 0;
  5813. this.iter(this.first, coords.line, function (line) {
  5814. index += line.text.length + 1;
  5815. });
  5816. return index;
  5817. },
  5818. copy: function(copyHistory) {
  5819. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  5820. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5821. doc.sel = this.sel;
  5822. doc.extend = false;
  5823. if (copyHistory) {
  5824. doc.history.undoDepth = this.history.undoDepth;
  5825. doc.setHistory(this.getHistory());
  5826. }
  5827. return doc;
  5828. },
  5829. linkedDoc: function(options) {
  5830. if (!options) options = {};
  5831. var from = this.first, to = this.first + this.size;
  5832. if (options.from != null && options.from > from) from = options.from;
  5833. if (options.to != null && options.to < to) to = options.to;
  5834. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  5835. if (options.sharedHist) copy.history = this.history;
  5836. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5837. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5838. copySharedMarkers(copy, findSharedMarkers(this));
  5839. return copy;
  5840. },
  5841. unlinkDoc: function(other) {
  5842. if (other instanceof CodeMirror) other = other.doc;
  5843. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  5844. var link = this.linked[i];
  5845. if (link.doc != other) continue;
  5846. this.linked.splice(i, 1);
  5847. other.unlinkDoc(this);
  5848. detachSharedMarkers(findSharedMarkers(this));
  5849. break;
  5850. }
  5851. // If the histories were shared, split them again
  5852. if (other.history == this.history) {
  5853. var splitIds = [other.id];
  5854. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  5855. other.history = new History(null);
  5856. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5857. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5858. }
  5859. },
  5860. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5861. getMode: function() {return this.mode;},
  5862. getEditor: function() {return this.cm;}
  5863. });
  5864. // Public alias.
  5865. Doc.prototype.eachLine = Doc.prototype.iter;
  5866. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  5867. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  5868. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  5869. CodeMirror.prototype[prop] = (function(method) {
  5870. return function() {return method.apply(this.doc, arguments);};
  5871. })(Doc.prototype[prop]);
  5872. eventMixin(Doc);
  5873. // Call f for all linked documents.
  5874. function linkedDocs(doc, f, sharedHistOnly) {
  5875. function propagate(doc, skip, sharedHist) {
  5876. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  5877. var rel = doc.linked[i];
  5878. if (rel.doc == skip) continue;
  5879. var shared = sharedHist && rel.sharedHist;
  5880. if (sharedHistOnly && !shared) continue;
  5881. f(rel.doc, shared);
  5882. propagate(rel.doc, doc, shared);
  5883. }
  5884. }
  5885. propagate(doc, null, true);
  5886. }
  5887. // Attach a document to an editor.
  5888. function attachDoc(cm, doc) {
  5889. if (doc.cm) throw new Error("This document is already in use.");
  5890. cm.doc = doc;
  5891. doc.cm = cm;
  5892. estimateLineHeights(cm);
  5893. loadMode(cm);
  5894. if (!cm.options.lineWrapping) findMaxLine(cm);
  5895. cm.options.mode = doc.modeOption;
  5896. regChange(cm);
  5897. }
  5898. // LINE UTILITIES
  5899. // Find the line object corresponding to the given line number.
  5900. function getLine(doc, n) {
  5901. n -= doc.first;
  5902. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  5903. for (var chunk = doc; !chunk.lines;) {
  5904. for (var i = 0;; ++i) {
  5905. var child = chunk.children[i], sz = child.chunkSize();
  5906. if (n < sz) { chunk = child; break; }
  5907. n -= sz;
  5908. }
  5909. }
  5910. return chunk.lines[n];
  5911. }
  5912. // Get the part of a document between two positions, as an array of
  5913. // strings.
  5914. function getBetween(doc, start, end) {
  5915. var out = [], n = start.line;
  5916. doc.iter(start.line, end.line + 1, function(line) {
  5917. var text = line.text;
  5918. if (n == end.line) text = text.slice(0, end.ch);
  5919. if (n == start.line) text = text.slice(start.ch);
  5920. out.push(text);
  5921. ++n;
  5922. });
  5923. return out;
  5924. }
  5925. // Get the lines between from and to, as array of strings.
  5926. function getLines(doc, from, to) {
  5927. var out = [];
  5928. doc.iter(from, to, function(line) { out.push(line.text); });
  5929. return out;
  5930. }
  5931. // Update the height of a line, propagating the height change
  5932. // upwards to parent nodes.
  5933. function updateLineHeight(line, height) {
  5934. var diff = height - line.height;
  5935. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  5936. }
  5937. // Given a line object, find its line number by walking up through
  5938. // its parent links.
  5939. function lineNo(line) {
  5940. if (line.parent == null) return null;
  5941. var cur = line.parent, no = indexOf(cur.lines, line);
  5942. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  5943. for (var i = 0;; ++i) {
  5944. if (chunk.children[i] == cur) break;
  5945. no += chunk.children[i].chunkSize();
  5946. }
  5947. }
  5948. return no + cur.first;
  5949. }
  5950. // Find the line at the given vertical position, using the height
  5951. // information in the document tree.
  5952. function lineAtHeight(chunk, h) {
  5953. var n = chunk.first;
  5954. outer: do {
  5955. for (var i = 0; i < chunk.children.length; ++i) {
  5956. var child = chunk.children[i], ch = child.height;
  5957. if (h < ch) { chunk = child; continue outer; }
  5958. h -= ch;
  5959. n += child.chunkSize();
  5960. }
  5961. return n;
  5962. } while (!chunk.lines);
  5963. for (var i = 0; i < chunk.lines.length; ++i) {
  5964. var line = chunk.lines[i], lh = line.height;
  5965. if (h < lh) break;
  5966. h -= lh;
  5967. }
  5968. return n + i;
  5969. }
  5970. // Find the height above the given line.
  5971. function heightAtLine(lineObj) {
  5972. lineObj = visualLine(lineObj);
  5973. var h = 0, chunk = lineObj.parent;
  5974. for (var i = 0; i < chunk.lines.length; ++i) {
  5975. var line = chunk.lines[i];
  5976. if (line == lineObj) break;
  5977. else h += line.height;
  5978. }
  5979. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  5980. for (var i = 0; i < p.children.length; ++i) {
  5981. var cur = p.children[i];
  5982. if (cur == chunk) break;
  5983. else h += cur.height;
  5984. }
  5985. }
  5986. return h;
  5987. }
  5988. // Get the bidi ordering for the given line (and cache it). Returns
  5989. // false for lines that are fully left-to-right, and an array of
  5990. // BidiSpan objects otherwise.
  5991. function getOrder(line) {
  5992. var order = line.order;
  5993. if (order == null) order = line.order = bidiOrdering(line.text);
  5994. return order;
  5995. }
  5996. // HISTORY
  5997. function History(startGen) {
  5998. // Arrays of change events and selections. Doing something adds an
  5999. // event to done and clears undo. Undoing moves events from done
  6000. // to undone, redoing moves them in the other direction.
  6001. this.done = []; this.undone = [];
  6002. this.undoDepth = Infinity;
  6003. // Used to track when changes can be merged into a single undo
  6004. // event
  6005. this.lastModTime = this.lastSelTime = 0;
  6006. this.lastOp = null;
  6007. this.lastOrigin = this.lastSelOrigin = null;
  6008. // Used by the isClean() method
  6009. this.generation = this.maxGeneration = startGen || 1;
  6010. }
  6011. // Create a history change event from an updateDoc-style change
  6012. // object.
  6013. function historyChangeFromChange(doc, change) {
  6014. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6015. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6016. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  6017. return histChange;
  6018. }
  6019. // Pop all selection events off the end of a history array. Stop at
  6020. // a change event.
  6021. function clearSelectionEvents(array) {
  6022. while (array.length) {
  6023. var last = lst(array);
  6024. if (last.ranges) array.pop();
  6025. else break;
  6026. }
  6027. }
  6028. // Find the top change event in the history. Pop off selection
  6029. // events that are in the way.
  6030. function lastChangeEvent(hist, force) {
  6031. if (force) {
  6032. clearSelectionEvents(hist.done);
  6033. return lst(hist.done);
  6034. } else if (hist.done.length && !lst(hist.done).ranges) {
  6035. return lst(hist.done);
  6036. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  6037. hist.done.pop();
  6038. return lst(hist.done);
  6039. }
  6040. }
  6041. // Register a change in the history. Merges changes that are within
  6042. // a single operation, ore are close together with an origin that
  6043. // allows merging (starting with "+") into a single event.
  6044. function addChangeToHistory(doc, change, selAfter, opId) {
  6045. var hist = doc.history;
  6046. hist.undone.length = 0;
  6047. var time = +new Date, cur;
  6048. if ((hist.lastOp == opId ||
  6049. hist.lastOrigin == change.origin && change.origin &&
  6050. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  6051. change.origin.charAt(0) == "*")) &&
  6052. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  6053. // Merge this change into the last event
  6054. var last = lst(cur.changes);
  6055. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  6056. // Optimized case for simple insertion -- don't want to add
  6057. // new changesets for every character typed
  6058. last.to = changeEnd(change);
  6059. } else {
  6060. // Add new sub-event
  6061. cur.changes.push(historyChangeFromChange(doc, change));
  6062. }
  6063. } else {
  6064. // Can not be merged, start a new event.
  6065. var before = lst(hist.done);
  6066. if (!before || !before.ranges)
  6067. pushSelectionToHistory(doc.sel, hist.done);
  6068. cur = {changes: [historyChangeFromChange(doc, change)],
  6069. generation: hist.generation};
  6070. hist.done.push(cur);
  6071. while (hist.done.length > hist.undoDepth) {
  6072. hist.done.shift();
  6073. if (!hist.done[0].ranges) hist.done.shift();
  6074. }
  6075. }
  6076. hist.done.push(selAfter);
  6077. hist.generation = ++hist.maxGeneration;
  6078. hist.lastModTime = hist.lastSelTime = time;
  6079. hist.lastOp = opId;
  6080. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  6081. if (!last) signal(doc, "historyAdded");
  6082. }
  6083. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  6084. var ch = origin.charAt(0);
  6085. return ch == "*" ||
  6086. ch == "+" &&
  6087. prev.ranges.length == sel.ranges.length &&
  6088. prev.somethingSelected() == sel.somethingSelected() &&
  6089. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  6090. }
  6091. // Called whenever the selection changes, sets the new selection as
  6092. // the pending selection in the history, and pushes the old pending
  6093. // selection into the 'done' array when it was significantly
  6094. // different (in number of selected ranges, emptiness, or time).
  6095. function addSelectionToHistory(doc, sel, opId, options) {
  6096. var hist = doc.history, origin = options && options.origin;
  6097. // A new event is started when the previous origin does not match
  6098. // the current, or the origins don't allow matching. Origins
  6099. // starting with * are always merged, those starting with + are
  6100. // merged when similar and close together in time.
  6101. if (opId == hist.lastOp ||
  6102. (origin && hist.lastSelOrigin == origin &&
  6103. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  6104. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  6105. hist.done[hist.done.length - 1] = sel;
  6106. else
  6107. pushSelectionToHistory(sel, hist.done);
  6108. hist.lastSelTime = +new Date;
  6109. hist.lastSelOrigin = origin;
  6110. hist.lastOp = opId;
  6111. if (options && options.clearRedo !== false)
  6112. clearSelectionEvents(hist.undone);
  6113. }
  6114. function pushSelectionToHistory(sel, dest) {
  6115. var top = lst(dest);
  6116. if (!(top && top.ranges && top.equals(sel)))
  6117. dest.push(sel);
  6118. }
  6119. // Used to store marked span information in the history.
  6120. function attachLocalSpans(doc, change, from, to) {
  6121. var existing = change["spans_" + doc.id], n = 0;
  6122. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  6123. if (line.markedSpans)
  6124. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  6125. ++n;
  6126. });
  6127. }
  6128. // When un/re-doing restores text containing marked spans, those
  6129. // that have been explicitly cleared should not be restored.
  6130. function removeClearedSpans(spans) {
  6131. if (!spans) return null;
  6132. for (var i = 0, out; i < spans.length; ++i) {
  6133. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  6134. else if (out) out.push(spans[i]);
  6135. }
  6136. return !out ? spans : out.length ? out : null;
  6137. }
  6138. // Retrieve and filter the old marked spans stored in a change event.
  6139. function getOldSpans(doc, change) {
  6140. var found = change["spans_" + doc.id];
  6141. if (!found) return null;
  6142. for (var i = 0, nw = []; i < change.text.length; ++i)
  6143. nw.push(removeClearedSpans(found[i]));
  6144. return nw;
  6145. }
  6146. // Used both to provide a JSON-safe object in .getHistory, and, when
  6147. // detaching a document, to split the history in two
  6148. function copyHistoryArray(events, newGroup, instantiateSel) {
  6149. for (var i = 0, copy = []; i < events.length; ++i) {
  6150. var event = events[i];
  6151. if (event.ranges) {
  6152. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  6153. continue;
  6154. }
  6155. var changes = event.changes, newChanges = [];
  6156. copy.push({changes: newChanges});
  6157. for (var j = 0; j < changes.length; ++j) {
  6158. var change = changes[j], m;
  6159. newChanges.push({from: change.from, to: change.to, text: change.text});
  6160. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  6161. if (indexOf(newGroup, Number(m[1])) > -1) {
  6162. lst(newChanges)[prop] = change[prop];
  6163. delete change[prop];
  6164. }
  6165. }
  6166. }
  6167. }
  6168. return copy;
  6169. }
  6170. // Rebasing/resetting history to deal with externally-sourced changes
  6171. function rebaseHistSelSingle(pos, from, to, diff) {
  6172. if (to < pos.line) {
  6173. pos.line += diff;
  6174. } else if (from < pos.line) {
  6175. pos.line = from;
  6176. pos.ch = 0;
  6177. }
  6178. }
  6179. // Tries to rebase an array of history events given a change in the
  6180. // document. If the change touches the same lines as the event, the
  6181. // event, and everything 'behind' it, is discarded. If the change is
  6182. // before the event, the event's positions are updated. Uses a
  6183. // copy-on-write scheme for the positions, to avoid having to
  6184. // reallocate them all on every rebase, but also avoid problems with
  6185. // shared position objects being unsafely updated.
  6186. function rebaseHistArray(array, from, to, diff) {
  6187. for (var i = 0; i < array.length; ++i) {
  6188. var sub = array[i], ok = true;
  6189. if (sub.ranges) {
  6190. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  6191. for (var j = 0; j < sub.ranges.length; j++) {
  6192. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  6193. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  6194. }
  6195. continue;
  6196. }
  6197. for (var j = 0; j < sub.changes.length; ++j) {
  6198. var cur = sub.changes[j];
  6199. if (to < cur.from.line) {
  6200. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  6201. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  6202. } else if (from <= cur.to.line) {
  6203. ok = false;
  6204. break;
  6205. }
  6206. }
  6207. if (!ok) {
  6208. array.splice(0, i + 1);
  6209. i = 0;
  6210. }
  6211. }
  6212. }
  6213. function rebaseHist(hist, change) {
  6214. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  6215. rebaseHistArray(hist.done, from, to, diff);
  6216. rebaseHistArray(hist.undone, from, to, diff);
  6217. }
  6218. // EVENT UTILITIES
  6219. // Due to the fact that we still support jurassic IE versions, some
  6220. // compatibility wrappers are needed.
  6221. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  6222. if (e.preventDefault) e.preventDefault();
  6223. else e.returnValue = false;
  6224. };
  6225. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  6226. if (e.stopPropagation) e.stopPropagation();
  6227. else e.cancelBubble = true;
  6228. };
  6229. function e_defaultPrevented(e) {
  6230. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  6231. }
  6232. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  6233. function e_target(e) {return e.target || e.srcElement;}
  6234. function e_button(e) {
  6235. var b = e.which;
  6236. if (b == null) {
  6237. if (e.button & 1) b = 1;
  6238. else if (e.button & 2) b = 3;
  6239. else if (e.button & 4) b = 2;
  6240. }
  6241. if (mac && e.ctrlKey && b == 1) b = 3;
  6242. return b;
  6243. }
  6244. // EVENT HANDLING
  6245. // Lightweight event framework. on/off also work on DOM nodes,
  6246. // registering native DOM handlers.
  6247. var on = CodeMirror.on = function(emitter, type, f) {
  6248. if (emitter.addEventListener)
  6249. emitter.addEventListener(type, f, false);
  6250. else if (emitter.attachEvent)
  6251. emitter.attachEvent("on" + type, f);
  6252. else {
  6253. var map = emitter._handlers || (emitter._handlers = {});
  6254. var arr = map[type] || (map[type] = []);
  6255. arr.push(f);
  6256. }
  6257. };
  6258. var off = CodeMirror.off = function(emitter, type, f) {
  6259. if (emitter.removeEventListener)
  6260. emitter.removeEventListener(type, f, false);
  6261. else if (emitter.detachEvent)
  6262. emitter.detachEvent("on" + type, f);
  6263. else {
  6264. var arr = emitter._handlers && emitter._handlers[type];
  6265. if (!arr) return;
  6266. for (var i = 0; i < arr.length; ++i)
  6267. if (arr[i] == f) { arr.splice(i, 1); break; }
  6268. }
  6269. };
  6270. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  6271. var arr = emitter._handlers && emitter._handlers[type];
  6272. if (!arr) return;
  6273. var args = Array.prototype.slice.call(arguments, 2);
  6274. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  6275. };
  6276. // Often, we want to signal events at a point where we are in the
  6277. // middle of some work, but don't want the handler to start calling
  6278. // other methods on the editor, which might be in an inconsistent
  6279. // state or simply not expect any other events to happen.
  6280. // signalLater looks whether there are any handlers, and schedules
  6281. // them to be executed when the last operation ends, or, if no
  6282. // operation is active, when a timeout fires.
  6283. var delayedCallbacks, delayedCallbackDepth = 0;
  6284. function signalLater(emitter, type /*, values...*/) {
  6285. var arr = emitter._handlers && emitter._handlers[type];
  6286. if (!arr) return;
  6287. var args = Array.prototype.slice.call(arguments, 2);
  6288. if (!delayedCallbacks) {
  6289. ++delayedCallbackDepth;
  6290. delayedCallbacks = [];
  6291. setTimeout(fireDelayed, 0);
  6292. }
  6293. function bnd(f) {return function(){f.apply(null, args);};};
  6294. for (var i = 0; i < arr.length; ++i)
  6295. delayedCallbacks.push(bnd(arr[i]));
  6296. }
  6297. function fireDelayed() {
  6298. --delayedCallbackDepth;
  6299. var delayed = delayedCallbacks;
  6300. delayedCallbacks = null;
  6301. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  6302. }
  6303. // The DOM events that CodeMirror handles can be overridden by
  6304. // registering a (non-DOM) handler on the editor for the event name,
  6305. // and preventDefault-ing the event in that handler.
  6306. function signalDOMEvent(cm, e, override) {
  6307. signal(cm, override || e.type, cm, e);
  6308. return e_defaultPrevented(e) || e.codemirrorIgnore;
  6309. }
  6310. function signalCursorActivity(cm) {
  6311. var arr = cm._handlers && cm._handlers.cursorActivity;
  6312. if (!arr) return;
  6313. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  6314. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  6315. set.push(arr[i]);
  6316. }
  6317. function hasHandler(emitter, type) {
  6318. var arr = emitter._handlers && emitter._handlers[type];
  6319. return arr && arr.length > 0;
  6320. }
  6321. // Add on and off methods to a constructor's prototype, to make
  6322. // registering events on such objects more convenient.
  6323. function eventMixin(ctor) {
  6324. ctor.prototype.on = function(type, f) {on(this, type, f);};
  6325. ctor.prototype.off = function(type, f) {off(this, type, f);};
  6326. }
  6327. // MISC UTILITIES
  6328. // Number of pixels added to scroller and sizer to hide scrollbar
  6329. var scrollerCutOff = 30;
  6330. // Returned or thrown by various protocols to signal 'I'm not
  6331. // handling this'.
  6332. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  6333. // Reused option objects for setSelection & friends
  6334. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  6335. function Delayed() {this.id = null;}
  6336. Delayed.prototype.set = function(ms, f) {
  6337. clearTimeout(this.id);
  6338. this.id = setTimeout(f, ms);
  6339. };
  6340. // Counts the column offset in a string, taking tabs into account.
  6341. // Used mostly to find indentation.
  6342. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  6343. if (end == null) {
  6344. end = string.search(/[^\s\u00a0]/);
  6345. if (end == -1) end = string.length;
  6346. }
  6347. for (var i = startIndex || 0, n = startValue || 0;;) {
  6348. var nextTab = string.indexOf("\t", i);
  6349. if (nextTab < 0 || nextTab >= end)
  6350. return n + (end - i);
  6351. n += nextTab - i;
  6352. n += tabSize - (n % tabSize);
  6353. i = nextTab + 1;
  6354. }
  6355. };
  6356. // The inverse of countColumn -- find the offset that corresponds to
  6357. // a particular column.
  6358. function findColumn(string, goal, tabSize) {
  6359. for (var pos = 0, col = 0;;) {
  6360. var nextTab = string.indexOf("\t", pos);
  6361. if (nextTab == -1) nextTab = string.length;
  6362. var skipped = nextTab - pos;
  6363. if (nextTab == string.length || col + skipped >= goal)
  6364. return pos + Math.min(skipped, goal - col);
  6365. col += nextTab - pos;
  6366. col += tabSize - (col % tabSize);
  6367. pos = nextTab + 1;
  6368. if (col >= goal) return pos;
  6369. }
  6370. }
  6371. var spaceStrs = [""];
  6372. function spaceStr(n) {
  6373. while (spaceStrs.length <= n)
  6374. spaceStrs.push(lst(spaceStrs) + " ");
  6375. return spaceStrs[n];
  6376. }
  6377. function lst(arr) { return arr[arr.length-1]; }
  6378. var selectInput = function(node) { node.select(); };
  6379. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  6380. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  6381. else if (ie) // Suppress mysterious IE10 errors
  6382. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  6383. function indexOf(array, elt) {
  6384. for (var i = 0; i < array.length; ++i)
  6385. if (array[i] == elt) return i;
  6386. return -1;
  6387. }
  6388. if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };
  6389. function map(array, f) {
  6390. var out = [];
  6391. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  6392. return out;
  6393. }
  6394. if ([].map) map = function(array, f) { return array.map(f); };
  6395. function createObj(base, props) {
  6396. var inst;
  6397. if (Object.create) {
  6398. inst = Object.create(base);
  6399. } else {
  6400. var ctor = function() {};
  6401. ctor.prototype = base;
  6402. inst = new ctor();
  6403. }
  6404. if (props) copyObj(props, inst);
  6405. return inst;
  6406. };
  6407. function copyObj(obj, target, overwrite) {
  6408. if (!target) target = {};
  6409. for (var prop in obj)
  6410. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  6411. target[prop] = obj[prop];
  6412. return target;
  6413. }
  6414. function bind(f) {
  6415. var args = Array.prototype.slice.call(arguments, 1);
  6416. return function(){return f.apply(null, args);};
  6417. }
  6418. var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  6419. var isWordChar = CodeMirror.isWordChar = function(ch) {
  6420. return /\w/.test(ch) || ch > "\x80" &&
  6421. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  6422. };
  6423. function isEmpty(obj) {
  6424. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  6425. return true;
  6426. }
  6427. // Extending unicode characters. A series of a non-extending char +
  6428. // any number of extending chars is treated as a single unit as far
  6429. // as editing and measuring is concerned. This is not fully correct,
  6430. // since some scripts/fonts/browsers also treat other configurations
  6431. // of code points as a group.
  6432. 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]/;
  6433. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  6434. // DOM UTILITIES
  6435. function elt(tag, content, className, style) {
  6436. var e = document.createElement(tag);
  6437. if (className) e.className = className;
  6438. if (style) e.style.cssText = style;
  6439. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  6440. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  6441. return e;
  6442. }
  6443. var range;
  6444. if (document.createRange) range = function(node, start, end) {
  6445. var r = document.createRange();
  6446. r.setEnd(node, end);
  6447. r.setStart(node, start);
  6448. return r;
  6449. };
  6450. else range = function(node, start, end) {
  6451. var r = document.body.createTextRange();
  6452. r.moveToElementText(node.parentNode);
  6453. r.collapse(true);
  6454. r.moveEnd("character", end);
  6455. r.moveStart("character", start);
  6456. return r;
  6457. };
  6458. function removeChildren(e) {
  6459. for (var count = e.childNodes.length; count > 0; --count)
  6460. e.removeChild(e.firstChild);
  6461. return e;
  6462. }
  6463. function removeChildrenAndAdd(parent, e) {
  6464. return removeChildren(parent).appendChild(e);
  6465. }
  6466. function contains(parent, child) {
  6467. if (parent.contains)
  6468. return parent.contains(child);
  6469. while (child = child.parentNode)
  6470. if (child == parent) return true;
  6471. }
  6472. function activeElt() { return document.activeElement; }
  6473. // Older versions of IE throws unspecified error when touching
  6474. // document.activeElement in some cases (during loading, in iframe)
  6475. if (ie_upto10) activeElt = function() {
  6476. try { return document.activeElement; }
  6477. catch(e) { return document.body; }
  6478. };
  6479. function classTest(cls) { return new RegExp("\\b" + cls + "\\b\\s*"); }
  6480. function rmClass(node, cls) {
  6481. var test = classTest(cls);
  6482. if (test.test(node.className)) node.className = node.className.replace(test, "");
  6483. }
  6484. function addClass(node, cls) {
  6485. if (!classTest(cls).test(node.className)) node.className += " " + cls;
  6486. }
  6487. function joinClasses(a, b) {
  6488. var as = a.split(" ");
  6489. for (var i = 0; i < as.length; i++)
  6490. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  6491. return b;
  6492. }
  6493. // FEATURE DETECTION
  6494. // Detect drag-and-drop
  6495. var dragAndDrop = function() {
  6496. // There is *some* kind of drag-and-drop support in IE6-8, but I
  6497. // couldn't get it to work yet.
  6498. if (ie_upto8) return false;
  6499. var div = elt('div');
  6500. return "draggable" in div || "dragDrop" in div;
  6501. }();
  6502. var knownScrollbarWidth;
  6503. function scrollbarWidth(measure) {
  6504. if (knownScrollbarWidth != null) return knownScrollbarWidth;
  6505. var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
  6506. removeChildrenAndAdd(measure, test);
  6507. if (test.offsetWidth)
  6508. knownScrollbarWidth = test.offsetHeight - test.clientHeight;
  6509. return knownScrollbarWidth || 0;
  6510. }
  6511. var zwspSupported;
  6512. function zeroWidthElement(measure) {
  6513. if (zwspSupported == null) {
  6514. var test = elt("span", "\u200b");
  6515. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  6516. if (measure.firstChild.offsetHeight != 0)
  6517. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7;
  6518. }
  6519. if (zwspSupported) return elt("span", "\u200b");
  6520. else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  6521. }
  6522. // Feature-detect IE's crummy client rect reporting for bidi text
  6523. var badBidiRects;
  6524. function hasBadBidiRects(measure) {
  6525. if (badBidiRects != null) return badBidiRects;
  6526. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  6527. var r0 = range(txt, 0, 1).getBoundingClientRect();
  6528. if (r0.left == r0.right) return false;
  6529. var r1 = range(txt, 1, 2).getBoundingClientRect();
  6530. return badBidiRects = (r1.right - r0.right < 3);
  6531. }
  6532. // See if "".split is the broken IE version, if so, provide an
  6533. // alternative way to split lines.
  6534. var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  6535. var pos = 0, result = [], l = string.length;
  6536. while (pos <= l) {
  6537. var nl = string.indexOf("\n", pos);
  6538. if (nl == -1) nl = string.length;
  6539. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  6540. var rt = line.indexOf("\r");
  6541. if (rt != -1) {
  6542. result.push(line.slice(0, rt));
  6543. pos += rt + 1;
  6544. } else {
  6545. result.push(line);
  6546. pos = nl + 1;
  6547. }
  6548. }
  6549. return result;
  6550. } : function(string){return string.split(/\r\n?|\n/);};
  6551. var hasSelection = window.getSelection ? function(te) {
  6552. try { return te.selectionStart != te.selectionEnd; }
  6553. catch(e) { return false; }
  6554. } : function(te) {
  6555. try {var range = te.ownerDocument.selection.createRange();}
  6556. catch(e) {}
  6557. if (!range || range.parentElement() != te) return false;
  6558. return range.compareEndPoints("StartToEnd", range) != 0;
  6559. };
  6560. var hasCopyEvent = (function() {
  6561. var e = elt("div");
  6562. if ("oncopy" in e) return true;
  6563. e.setAttribute("oncopy", "return;");
  6564. return typeof e.oncopy == "function";
  6565. })();
  6566. // KEY NAMES
  6567. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6568. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6569. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6570. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
  6571. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6572. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6573. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
  6574. CodeMirror.keyNames = keyNames;
  6575. (function() {
  6576. // Number keys
  6577. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  6578. // Alphabetic keys
  6579. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  6580. // Function keys
  6581. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  6582. })();
  6583. // BIDI HELPERS
  6584. function iterateBidiSections(order, from, to, f) {
  6585. if (!order) return f(from, to, "ltr");
  6586. var found = false;
  6587. for (var i = 0; i < order.length; ++i) {
  6588. var part = order[i];
  6589. if (part.from < to && part.to > from || from == to && part.to == from) {
  6590. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  6591. found = true;
  6592. }
  6593. }
  6594. if (!found) f(from, to, "ltr");
  6595. }
  6596. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  6597. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  6598. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  6599. function lineRight(line) {
  6600. var order = getOrder(line);
  6601. if (!order) return line.text.length;
  6602. return bidiRight(lst(order));
  6603. }
  6604. function lineStart(cm, lineN) {
  6605. var line = getLine(cm.doc, lineN);
  6606. var visual = visualLine(line);
  6607. if (visual != line) lineN = lineNo(visual);
  6608. var order = getOrder(visual);
  6609. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  6610. return Pos(lineN, ch);
  6611. }
  6612. function lineEnd(cm, lineN) {
  6613. var merged, line = getLine(cm.doc, lineN);
  6614. while (merged = collapsedSpanAtEnd(line)) {
  6615. line = merged.find(1, true).line;
  6616. lineN = null;
  6617. }
  6618. var order = getOrder(line);
  6619. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  6620. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  6621. }
  6622. function compareBidiLevel(order, a, b) {
  6623. var linedir = order[0].level;
  6624. if (a == linedir) return true;
  6625. if (b == linedir) return false;
  6626. return a < b;
  6627. }
  6628. var bidiOther;
  6629. function getBidiPartAt(order, pos) {
  6630. bidiOther = null;
  6631. for (var i = 0, found; i < order.length; ++i) {
  6632. var cur = order[i];
  6633. if (cur.from < pos && cur.to > pos) return i;
  6634. if ((cur.from == pos || cur.to == pos)) {
  6635. if (found == null) {
  6636. found = i;
  6637. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  6638. if (cur.from != cur.to) bidiOther = found;
  6639. return i;
  6640. } else {
  6641. if (cur.from != cur.to) bidiOther = i;
  6642. return found;
  6643. }
  6644. }
  6645. }
  6646. return found;
  6647. }
  6648. function moveInLine(line, pos, dir, byUnit) {
  6649. if (!byUnit) return pos + dir;
  6650. do pos += dir;
  6651. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  6652. return pos;
  6653. }
  6654. // This is needed in order to move 'visually' through bi-directional
  6655. // text -- i.e., pressing left should make the cursor go left, even
  6656. // when in RTL text. The tricky part is the 'jumps', where RTL and
  6657. // LTR text touch each other. This often requires the cursor offset
  6658. // to move more than one unit, in order to visually move one unit.
  6659. function moveVisually(line, start, dir, byUnit) {
  6660. var bidi = getOrder(line);
  6661. if (!bidi) return moveLogically(line, start, dir, byUnit);
  6662. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  6663. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  6664. for (;;) {
  6665. if (target > part.from && target < part.to) return target;
  6666. if (target == part.from || target == part.to) {
  6667. if (getBidiPartAt(bidi, target) == pos) return target;
  6668. part = bidi[pos += dir];
  6669. return (dir > 0) == part.level % 2 ? part.to : part.from;
  6670. } else {
  6671. part = bidi[pos += dir];
  6672. if (!part) return null;
  6673. if ((dir > 0) == part.level % 2)
  6674. target = moveInLine(line, part.to, -1, byUnit);
  6675. else
  6676. target = moveInLine(line, part.from, 1, byUnit);
  6677. }
  6678. }
  6679. }
  6680. function moveLogically(line, start, dir, byUnit) {
  6681. var target = start + dir;
  6682. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  6683. return target < 0 || target > line.text.length ? null : target;
  6684. }
  6685. // Bidirectional ordering algorithm
  6686. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  6687. // that this (partially) implements.
  6688. // One-char codes used for character types:
  6689. // L (L): Left-to-Right
  6690. // R (R): Right-to-Left
  6691. // r (AL): Right-to-Left Arabic
  6692. // 1 (EN): European Number
  6693. // + (ES): European Number Separator
  6694. // % (ET): European Number Terminator
  6695. // n (AN): Arabic Number
  6696. // , (CS): Common Number Separator
  6697. // m (NSM): Non-Spacing Mark
  6698. // b (BN): Boundary Neutral
  6699. // s (B): Paragraph Separator
  6700. // t (S): Segment Separator
  6701. // w (WS): Whitespace
  6702. // N (ON): Other Neutrals
  6703. // Returns null if characters are ordered as they appear
  6704. // (left-to-right), or an array of sections ({from, to, level}
  6705. // objects) in the order in which they occur visually.
  6706. var bidiOrdering = (function() {
  6707. // Character types for codepoints 0 to 0xff
  6708. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  6709. // Character types for codepoints 0x600 to 0x6ff
  6710. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  6711. function charType(code) {
  6712. if (code <= 0xf7) return lowTypes.charAt(code);
  6713. else if (0x590 <= code && code <= 0x5f4) return "R";
  6714. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  6715. else if (0x6ee <= code && code <= 0x8ac) return "r";
  6716. else if (0x2000 <= code && code <= 0x200b) return "w";
  6717. else if (code == 0x200c) return "b";
  6718. else return "L";
  6719. }
  6720. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  6721. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  6722. // Browsers seem to always treat the boundaries of block elements as being L.
  6723. var outerType = "L";
  6724. function BidiSpan(level, from, to) {
  6725. this.level = level;
  6726. this.from = from; this.to = to;
  6727. }
  6728. return function(str) {
  6729. if (!bidiRE.test(str)) return false;
  6730. var len = str.length, types = [];
  6731. for (var i = 0, type; i < len; ++i)
  6732. types.push(type = charType(str.charCodeAt(i)));
  6733. // W1. Examine each non-spacing mark (NSM) in the level run, and
  6734. // change the type of the NSM to the type of the previous
  6735. // character. If the NSM is at the start of the level run, it will
  6736. // get the type of sor.
  6737. for (var i = 0, prev = outerType; i < len; ++i) {
  6738. var type = types[i];
  6739. if (type == "m") types[i] = prev;
  6740. else prev = type;
  6741. }
  6742. // W2. Search backwards from each instance of a European number
  6743. // until the first strong type (R, L, AL, or sor) is found. If an
  6744. // AL is found, change the type of the European number to Arabic
  6745. // number.
  6746. // W3. Change all ALs to R.
  6747. for (var i = 0, cur = outerType; i < len; ++i) {
  6748. var type = types[i];
  6749. if (type == "1" && cur == "r") types[i] = "n";
  6750. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  6751. }
  6752. // W4. A single European separator between two European numbers
  6753. // changes to a European number. A single common separator between
  6754. // two numbers of the same type changes to that type.
  6755. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  6756. var type = types[i];
  6757. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  6758. else if (type == "," && prev == types[i+1] &&
  6759. (prev == "1" || prev == "n")) types[i] = prev;
  6760. prev = type;
  6761. }
  6762. // W5. A sequence of European terminators adjacent to European
  6763. // numbers changes to all European numbers.
  6764. // W6. Otherwise, separators and terminators change to Other
  6765. // Neutral.
  6766. for (var i = 0; i < len; ++i) {
  6767. var type = types[i];
  6768. if (type == ",") types[i] = "N";
  6769. else if (type == "%") {
  6770. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  6771. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  6772. for (var j = i; j < end; ++j) types[j] = replace;
  6773. i = end - 1;
  6774. }
  6775. }
  6776. // W7. Search backwards from each instance of a European number
  6777. // until the first strong type (R, L, or sor) is found. If an L is
  6778. // found, then change the type of the European number to L.
  6779. for (var i = 0, cur = outerType; i < len; ++i) {
  6780. var type = types[i];
  6781. if (cur == "L" && type == "1") types[i] = "L";
  6782. else if (isStrong.test(type)) cur = type;
  6783. }
  6784. // N1. A sequence of neutrals takes the direction of the
  6785. // surrounding strong text if the text on both sides has the same
  6786. // direction. European and Arabic numbers act as if they were R in
  6787. // terms of their influence on neutrals. Start-of-level-run (sor)
  6788. // and end-of-level-run (eor) are used at level run boundaries.
  6789. // N2. Any remaining neutrals take the embedding direction.
  6790. for (var i = 0; i < len; ++i) {
  6791. if (isNeutral.test(types[i])) {
  6792. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  6793. var before = (i ? types[i-1] : outerType) == "L";
  6794. var after = (end < len ? types[end] : outerType) == "L";
  6795. var replace = before || after ? "L" : "R";
  6796. for (var j = i; j < end; ++j) types[j] = replace;
  6797. i = end - 1;
  6798. }
  6799. }
  6800. // Here we depart from the documented algorithm, in order to avoid
  6801. // building up an actual levels array. Since there are only three
  6802. // levels (0, 1, 2) in an implementation that doesn't take
  6803. // explicit embedding into account, we can build up the order on
  6804. // the fly, without following the level-based algorithm.
  6805. var order = [], m;
  6806. for (var i = 0; i < len;) {
  6807. if (countsAsLeft.test(types[i])) {
  6808. var start = i;
  6809. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  6810. order.push(new BidiSpan(0, start, i));
  6811. } else {
  6812. var pos = i, at = order.length;
  6813. for (++i; i < len && types[i] != "L"; ++i) {}
  6814. for (var j = pos; j < i;) {
  6815. if (countsAsNum.test(types[j])) {
  6816. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  6817. var nstart = j;
  6818. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  6819. order.splice(at, 0, new BidiSpan(2, nstart, j));
  6820. pos = j;
  6821. } else ++j;
  6822. }
  6823. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  6824. }
  6825. }
  6826. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  6827. order[0].from = m[0].length;
  6828. order.unshift(new BidiSpan(0, 0, m[0].length));
  6829. }
  6830. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  6831. lst(order).to -= m[0].length;
  6832. order.push(new BidiSpan(0, len - m[0].length, len));
  6833. }
  6834. if (order[0].level != lst(order).level)
  6835. order.push(new BidiSpan(order[0].level, len, len));
  6836. return order;
  6837. };
  6838. })();
  6839. // THE END
  6840. CodeMirror.version = "4.1.0";
  6841. return CodeMirror;
  6842. });