1
0

codemirror.js 209 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516
  1. // CodeMirror version 3.11
  2. //
  3. // CodeMirror is the only global var we claim
  4. window.CodeMirror = (function() {
  5. "use strict";
  6. // BROWSER SNIFFING
  7. // Crude, but necessary to handle a number of hard-to-feature-detect
  8. // bugs and behavior differences.
  9. var gecko = /gecko\/\d/i.test(navigator.userAgent);
  10. var ie = /MSIE \d/.test(navigator.userAgent);
  11. var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
  12. var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
  13. var webkit = /WebKit\//.test(navigator.userAgent);
  14. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
  15. var chrome = /Chrome\//.test(navigator.userAgent);
  16. var opera = /Opera\//.test(navigator.userAgent);
  17. var safari = /Apple Computer/.test(navigator.vendor);
  18. var khtml = /KHTML\//.test(navigator.userAgent);
  19. var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
  20. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
  21. var phantom = /PhantomJS/.test(navigator.userAgent);
  22. var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
  23. // This is woefully incomplete. Suggestions for alternative methods welcome.
  24. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
  25. var mac = ios || /Mac/.test(navigator.platform);
  26. var windows = /windows/i.test(navigator.platform);
  27. var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
  28. if (opera_version) opera_version = Number(opera_version[1]);
  29. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  30. var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
  31. var captureMiddleClick = gecko || (ie && !ie_lt9);
  32. // Optimize some code when these features are not used
  33. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  34. // CONSTRUCTOR
  35. function CodeMirror(place, options) {
  36. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  37. this.options = options = options || {};
  38. // Determine effective options based on given values and defaults.
  39. for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
  40. options[opt] = defaults[opt];
  41. setGuttersForLineNumbers(options);
  42. var docStart = typeof options.value == "string" ? 0 : options.value.first;
  43. var display = this.display = makeDisplay(place, docStart);
  44. display.wrapper.CodeMirror = this;
  45. updateGutters(this);
  46. if (options.autofocus && !mobile) focusInput(this);
  47. this.state = {keyMaps: [],
  48. overlays: [],
  49. modeGen: 0,
  50. overwrite: false, focused: false,
  51. suppressEdits: false, pasteIncoming: false,
  52. draggingText: false,
  53. highlight: new Delayed()};
  54. themeChanged(this);
  55. if (options.lineWrapping)
  56. this.display.wrapper.className += " CodeMirror-wrap";
  57. var doc = options.value;
  58. if (typeof doc == "string") doc = new Doc(options.value, options.mode);
  59. operation(this, attachDoc)(this, doc);
  60. // Override magic textarea content restore that IE sometimes does
  61. // on our hidden textarea on reload
  62. if (ie) setTimeout(bind(resetInput, this, true), 20);
  63. registerEventHandlers(this);
  64. // IE throws unspecified error in certain cases, when
  65. // trying to access activeElement before onload
  66. var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
  67. if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
  68. else onBlur(this);
  69. operation(this, function() {
  70. for (var opt in optionHandlers)
  71. if (optionHandlers.propertyIsEnumerable(opt))
  72. optionHandlers[opt](this, options[opt], Init);
  73. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  74. })();
  75. }
  76. // DISPLAY CONSTRUCTOR
  77. function makeDisplay(place, docStart) {
  78. var d = {};
  79. var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none;");
  80. if (webkit) input.style.width = "1000px";
  81. else input.setAttribute("wrap", "off");
  82. // if border: 0; -- iOS fails to open keyboard (issue #1287)
  83. if (ios) input.style.border = "1px solid black";
  84. input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off");
  85. // Wraps and hides input textarea
  86. d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  87. // The actual fake scrollbars.
  88. d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
  89. d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
  90. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  91. // DIVs containing the selection and the actual code
  92. d.lineDiv = elt("div");
  93. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  94. // Blinky cursor, and element used to ensure cursor fits at the end of a line
  95. d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
  96. // Secondary cursor, shown when on a 'jump' in bi-directional text
  97. d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
  98. // Used to measure text size
  99. d.measure = elt("div", null, "CodeMirror-measure");
  100. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  101. d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
  102. null, "position: relative; outline: none");
  103. // Moved around its parent to cover visible view
  104. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  105. // Set to the height of the text, causes scrolling
  106. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  107. // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
  108. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
  109. // Will contain the gutters, if any
  110. d.gutters = elt("div", null, "CodeMirror-gutters");
  111. d.lineGutter = null;
  112. // Helper element to properly size the gutter backgrounds
  113. var scrollerInner = elt("div", [d.sizer, d.heightForcer, d.gutters], null, "position: relative; min-height: 100%");
  114. // Provides scrolling
  115. d.scroller = elt("div", [scrollerInner], "CodeMirror-scroll");
  116. d.scroller.setAttribute("tabIndex", "-1");
  117. // The element in which the editor lives.
  118. d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
  119. d.scrollbarFiller, d.scroller], "CodeMirror");
  120. // Work around IE7 z-index bug
  121. if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  122. if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
  123. // Needed to hide big blue blinking cursor on Mobile Safari
  124. if (ios) input.style.width = "0px";
  125. if (!webkit) d.scroller.draggable = true;
  126. // Needed to handle Tab key in KHTML
  127. if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
  128. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  129. else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
  130. // Current visible range (may be bigger than the view window).
  131. d.viewOffset = d.lastSizeC = 0;
  132. d.showingFrom = d.showingTo = docStart;
  133. // Used to only resize the line number gutter when necessary (when
  134. // the amount of lines crosses a boundary that makes its width change)
  135. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  136. // See readInput and resetInput
  137. d.prevInput = "";
  138. // Set to true when a non-horizontal-scrolling widget is added. As
  139. // an optimization, widget aligning is skipped when d is false.
  140. d.alignWidgets = false;
  141. // Flag that indicates whether we currently expect input to appear
  142. // (after some event like 'keypress' or 'input') and are polling
  143. // intensively.
  144. d.pollingFast = false;
  145. // Self-resetting timeout for the poller
  146. d.poll = new Delayed();
  147. // True when a drag from the editor is active
  148. d.draggingText = false;
  149. d.cachedCharWidth = d.cachedTextHeight = null;
  150. d.measureLineCache = [];
  151. d.measureLineCachePos = 0;
  152. // Tracks when resetInput has punted to just putting a short
  153. // string instead of the (large) selection.
  154. d.inaccurateSelection = false;
  155. // Tracks the maximum line length so that the horizontal scrollbar
  156. // can be kept static when scrolling.
  157. d.maxLine = null;
  158. d.maxLineLength = 0;
  159. d.maxLineChanged = false;
  160. // Used for measuring wheel scrolling granularity
  161. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  162. return d;
  163. }
  164. // STATE UPDATES
  165. // Used to get the editor into a consistent state again when options change.
  166. function loadMode(cm) {
  167. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  168. cm.doc.iter(function(line) {
  169. if (line.stateAfter) line.stateAfter = null;
  170. if (line.styles) line.styles = null;
  171. });
  172. cm.doc.frontier = cm.doc.first;
  173. startWorker(cm, 100);
  174. cm.state.modeGen++;
  175. if (cm.curOp) regChange(cm);
  176. }
  177. function wrappingChanged(cm) {
  178. if (cm.options.lineWrapping) {
  179. cm.display.wrapper.className += " CodeMirror-wrap";
  180. cm.display.sizer.style.minWidth = "";
  181. } else {
  182. cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
  183. computeMaxLength(cm);
  184. }
  185. estimateLineHeights(cm);
  186. regChange(cm);
  187. clearCaches(cm);
  188. setTimeout(function(){updateScrollbars(cm.display, cm.doc.height);}, 100);
  189. }
  190. function estimateHeight(cm) {
  191. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  192. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  193. return function(line) {
  194. if (lineIsHidden(cm.doc, line))
  195. return 0;
  196. else if (wrapping)
  197. return (Math.ceil(line.text.length / perLine) || 1) * th;
  198. else
  199. return th;
  200. };
  201. }
  202. function estimateLineHeights(cm) {
  203. var doc = cm.doc, est = estimateHeight(cm);
  204. doc.iter(function(line) {
  205. var estHeight = est(line);
  206. if (estHeight != line.height) updateLineHeight(line, estHeight);
  207. });
  208. }
  209. function keyMapChanged(cm) {
  210. var style = keyMap[cm.options.keyMap].style;
  211. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
  212. (style ? " cm-keymap-" + style : "");
  213. }
  214. function themeChanged(cm) {
  215. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  216. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  217. clearCaches(cm);
  218. }
  219. function guttersChanged(cm) {
  220. updateGutters(cm);
  221. regChange(cm);
  222. }
  223. function updateGutters(cm) {
  224. var gutters = cm.display.gutters, specs = cm.options.gutters;
  225. removeChildren(gutters);
  226. for (var i = 0; i < specs.length; ++i) {
  227. var gutterClass = specs[i];
  228. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  229. if (gutterClass == "CodeMirror-linenumbers") {
  230. cm.display.lineGutter = gElt;
  231. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  232. }
  233. }
  234. gutters.style.display = i ? "" : "none";
  235. }
  236. function lineLength(doc, line) {
  237. if (line.height == 0) return 0;
  238. var len = line.text.length, merged, cur = line;
  239. while (merged = collapsedSpanAtStart(cur)) {
  240. var found = merged.find();
  241. cur = getLine(doc, found.from.line);
  242. len += found.from.ch - found.to.ch;
  243. }
  244. cur = line;
  245. while (merged = collapsedSpanAtEnd(cur)) {
  246. var found = merged.find();
  247. len -= cur.text.length - found.from.ch;
  248. cur = getLine(doc, found.to.line);
  249. len += cur.text.length - found.to.ch;
  250. }
  251. return len;
  252. }
  253. function computeMaxLength(cm) {
  254. var d = cm.display, doc = cm.doc;
  255. d.maxLine = getLine(doc, doc.first);
  256. d.maxLineLength = lineLength(doc, d.maxLine);
  257. d.maxLineChanged = true;
  258. doc.iter(function(line) {
  259. var len = lineLength(doc, line);
  260. if (len > d.maxLineLength) {
  261. d.maxLineLength = len;
  262. d.maxLine = line;
  263. }
  264. });
  265. }
  266. // Make sure the gutters options contains the element
  267. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  268. function setGuttersForLineNumbers(options) {
  269. var found = false;
  270. for (var i = 0; i < options.gutters.length; ++i) {
  271. if (options.gutters[i] == "CodeMirror-linenumbers") {
  272. if (options.lineNumbers) found = true;
  273. else options.gutters.splice(i--, 1);
  274. }
  275. }
  276. if (!found && options.lineNumbers)
  277. options.gutters.push("CodeMirror-linenumbers");
  278. }
  279. // SCROLLBARS
  280. // Re-synchronize the fake scrollbars with the actual size of the
  281. // content. Optionally force a scrollTop.
  282. function updateScrollbars(d /* display */, docHeight) {
  283. var totalHeight = docHeight + paddingVert(d);
  284. d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
  285. var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
  286. var needsH = d.scroller.scrollWidth > d.scroller.clientWidth;
  287. var needsV = scrollHeight > d.scroller.clientHeight;
  288. if (needsV) {
  289. d.scrollbarV.style.display = "block";
  290. d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
  291. d.scrollbarV.firstChild.style.height =
  292. (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
  293. } else d.scrollbarV.style.display = "";
  294. if (needsH) {
  295. d.scrollbarH.style.display = "block";
  296. d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
  297. d.scrollbarH.firstChild.style.width =
  298. (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
  299. } else d.scrollbarH.style.display = "";
  300. if (needsH && needsV) {
  301. d.scrollbarFiller.style.display = "block";
  302. d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
  303. } else d.scrollbarFiller.style.display = "";
  304. if (mac_geLion && scrollbarWidth(d.measure) === 0)
  305. d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
  306. }
  307. function visibleLines(display, doc, viewPort) {
  308. var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
  309. if (typeof viewPort == "number") top = viewPort;
  310. else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
  311. top = Math.floor(top - paddingTop(display));
  312. var bottom = Math.ceil(top + height);
  313. return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
  314. }
  315. // LINE NUMBERS
  316. function alignHorizontally(cm) {
  317. var display = cm.display;
  318. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  319. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  320. var gutterW = display.gutters.offsetWidth, l = comp + "px";
  321. for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
  322. for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
  323. }
  324. if (cm.options.fixedGutter)
  325. display.gutters.style.left = (comp + gutterW) + "px";
  326. }
  327. function maybeUpdateLineNumberWidth(cm) {
  328. if (!cm.options.lineNumbers) return false;
  329. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  330. if (last.length != display.lineNumChars) {
  331. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  332. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  333. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  334. display.lineGutter.style.width = "";
  335. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
  336. display.lineNumWidth = display.lineNumInnerWidth + padding;
  337. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  338. display.lineGutter.style.width = display.lineNumWidth + "px";
  339. return true;
  340. }
  341. return false;
  342. }
  343. function lineNumberFor(options, i) {
  344. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  345. }
  346. function compensateForHScroll(display) {
  347. return getRect(display.scroller).left - getRect(display.sizer).left;
  348. }
  349. // DISPLAY DRAWING
  350. function updateDisplay(cm, changes, viewPort) {
  351. var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo;
  352. var updated = updateDisplayInner(cm, changes, viewPort);
  353. if (updated) {
  354. signalLater(cm, "update", cm);
  355. if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
  356. signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
  357. }
  358. updateSelection(cm);
  359. updateScrollbars(cm.display, cm.doc.height);
  360. return updated;
  361. }
  362. // Uses a set of changes plus the current scroll position to
  363. // determine which DOM updates have to be made, and makes the
  364. // updates.
  365. function updateDisplayInner(cm, changes, viewPort) {
  366. var display = cm.display, doc = cm.doc;
  367. if (!display.wrapper.clientWidth) {
  368. display.showingFrom = display.showingTo = doc.first;
  369. display.viewOffset = 0;
  370. return;
  371. }
  372. // Compute the new visible window
  373. // If scrollTop is specified, use that to determine which lines
  374. // to render instead of the current scrollbar position.
  375. var visible = visibleLines(display, doc, viewPort);
  376. // Bail out if the visible area is already rendered and nothing changed.
  377. if (changes.length == 0 &&
  378. visible.from > display.showingFrom && visible.to < display.showingTo)
  379. return;
  380. if (maybeUpdateLineNumberWidth(cm))
  381. changes = [{from: doc.first, to: doc.first + doc.size}];
  382. var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
  383. display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
  384. // Used to determine which lines need their line numbers updated
  385. var positionsChangedFrom = Infinity;
  386. if (cm.options.lineNumbers)
  387. for (var i = 0; i < changes.length; ++i)
  388. if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
  389. var end = doc.first + doc.size;
  390. var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
  391. var to = Math.min(end, visible.to + cm.options.viewportMargin);
  392. if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
  393. if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
  394. if (sawCollapsedSpans) {
  395. from = lineNo(visualLine(doc, getLine(doc, from)));
  396. while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
  397. }
  398. // Create a range of theoretically intact lines, and punch holes
  399. // in that using the change info.
  400. var intact = [{from: Math.max(display.showingFrom, doc.first),
  401. to: Math.min(display.showingTo, end)}];
  402. if (intact[0].from >= intact[0].to) intact = [];
  403. else intact = computeIntact(intact, changes);
  404. // When merged lines are present, we might have to reduce the
  405. // intact ranges because changes in continued fragments of the
  406. // intact lines do require the lines to be redrawn.
  407. if (sawCollapsedSpans)
  408. for (var i = 0; i < intact.length; ++i) {
  409. var range = intact[i], merged;
  410. while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
  411. var newTo = merged.find().from.line;
  412. if (newTo > range.from) range.to = newTo;
  413. else { intact.splice(i--, 1); break; }
  414. }
  415. }
  416. // Clip off the parts that won't be visible
  417. var intactLines = 0;
  418. for (var i = 0; i < intact.length; ++i) {
  419. var range = intact[i];
  420. if (range.from < from) range.from = from;
  421. if (range.to > to) range.to = to;
  422. if (range.from >= range.to) intact.splice(i--, 1);
  423. else intactLines += range.to - range.from;
  424. }
  425. if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
  426. updateViewOffset(cm);
  427. return;
  428. }
  429. intact.sort(function(a, b) {return a.from - b.from;});
  430. var focused = document.activeElement;
  431. if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
  432. patchDisplay(cm, from, to, intact, positionsChangedFrom);
  433. display.lineDiv.style.display = "";
  434. if (document.activeElement != focused && focused.offsetHeight) focused.focus();
  435. var different = from != display.showingFrom || to != display.showingTo ||
  436. display.lastSizeC != display.wrapper.clientHeight;
  437. // This is just a bogus formula that detects when the editor is
  438. // resized or the font size changes.
  439. if (different) display.lastSizeC = display.wrapper.clientHeight;
  440. display.showingFrom = from; display.showingTo = to;
  441. startWorker(cm, 100);
  442. var prevBottom = display.lineDiv.offsetTop;
  443. for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
  444. if (ie_lt8) {
  445. var bot = node.offsetTop + node.offsetHeight;
  446. height = bot - prevBottom;
  447. prevBottom = bot;
  448. } else {
  449. var box = getRect(node);
  450. height = box.bottom - box.top;
  451. }
  452. var diff = node.lineObj.height - height;
  453. if (height < 2) height = textHeight(display);
  454. if (diff > .001 || diff < -.001) {
  455. updateLineHeight(node.lineObj, height);
  456. var widgets = node.lineObj.widgets;
  457. if (widgets) for (var i = 0; i < widgets.length; ++i)
  458. widgets[i].height = widgets[i].node.offsetHeight;
  459. }
  460. }
  461. updateViewOffset(cm);
  462. if (visibleLines(display, doc, viewPort).to > to)
  463. updateDisplayInner(cm, [], viewPort);
  464. return true;
  465. }
  466. function updateViewOffset(cm) {
  467. var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
  468. // Position the mover div to align with the current virtual scroll position
  469. cm.display.mover.style.top = off + "px";
  470. }
  471. function computeIntact(intact, changes) {
  472. for (var i = 0, l = changes.length || 0; i < l; ++i) {
  473. var change = changes[i], intact2 = [], diff = change.diff || 0;
  474. for (var j = 0, l2 = intact.length; j < l2; ++j) {
  475. var range = intact[j];
  476. if (change.to <= range.from && change.diff) {
  477. intact2.push({from: range.from + diff, to: range.to + diff});
  478. } else if (change.to <= range.from || change.from >= range.to) {
  479. intact2.push(range);
  480. } else {
  481. if (change.from > range.from)
  482. intact2.push({from: range.from, to: change.from});
  483. if (change.to < range.to)
  484. intact2.push({from: change.to + diff, to: range.to + diff});
  485. }
  486. }
  487. intact = intact2;
  488. }
  489. return intact;
  490. }
  491. function getDimensions(cm) {
  492. var d = cm.display, left = {}, width = {};
  493. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  494. left[cm.options.gutters[i]] = n.offsetLeft;
  495. width[cm.options.gutters[i]] = n.offsetWidth;
  496. }
  497. return {fixedPos: compensateForHScroll(d),
  498. gutterTotalWidth: d.gutters.offsetWidth,
  499. gutterLeft: left,
  500. gutterWidth: width,
  501. wrapperWidth: d.wrapper.clientWidth};
  502. }
  503. function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
  504. var dims = getDimensions(cm);
  505. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  506. if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
  507. removeChildren(display.lineDiv);
  508. var container = display.lineDiv, cur = container.firstChild;
  509. function rm(node) {
  510. var next = node.nextSibling;
  511. if (webkit && mac && cm.display.currentWheelTarget == node) {
  512. node.style.display = "none";
  513. node.lineObj = null;
  514. } else {
  515. node.parentNode.removeChild(node);
  516. }
  517. return next;
  518. }
  519. var nextIntact = intact.shift(), lineN = from;
  520. cm.doc.iter(from, to, function(line) {
  521. if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
  522. if (lineIsHidden(cm.doc, line)) {
  523. if (line.height != 0) updateLineHeight(line, 0);
  524. if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i)
  525. if (line.widgets[i].showIfHidden) {
  526. var prev = cur.previousSibling;
  527. if (/pre/i.test(prev.nodeName)) {
  528. var wrap = elt("div", null, null, "position: relative");
  529. prev.parentNode.replaceChild(wrap, prev);
  530. wrap.appendChild(prev);
  531. prev = wrap;
  532. }
  533. var wnode = prev.appendChild(elt("div", [line.widgets[i].node], "CodeMirror-linewidget"));
  534. positionLineWidget(line.widgets[i], wnode, prev, dims);
  535. }
  536. } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
  537. // This line is intact. Skip to the actual node. Update its
  538. // line number if needed.
  539. while (cur.lineObj != line) cur = rm(cur);
  540. if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
  541. setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
  542. cur = cur.nextSibling;
  543. } else {
  544. // For lines with widgets, make an attempt to find and reuse
  545. // the existing element, so that widgets aren't needlessly
  546. // removed and re-inserted into the dom
  547. if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
  548. if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
  549. // This line needs to be generated.
  550. var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
  551. if (lineNode != reuse) {
  552. container.insertBefore(lineNode, cur);
  553. } else {
  554. while (cur != reuse) cur = rm(cur);
  555. cur = cur.nextSibling;
  556. }
  557. lineNode.lineObj = line;
  558. }
  559. ++lineN;
  560. });
  561. while (cur) cur = rm(cur);
  562. }
  563. function buildLineElement(cm, line, lineNo, dims, reuse) {
  564. var lineElement = lineContent(cm, line);
  565. var markers = line.gutterMarkers, display = cm.display, wrap;
  566. if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets)
  567. return lineElement;
  568. // Lines with gutter elements, widgets or a background class need
  569. // to be wrapped again, and have the extra elements added to the
  570. // wrapper div
  571. if (reuse) {
  572. reuse.alignable = null;
  573. var isOk = true, widgetsSeen = 0;
  574. for (var n = reuse.firstChild, next; n; n = next) {
  575. next = n.nextSibling;
  576. if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
  577. reuse.removeChild(n);
  578. } else {
  579. for (var i = 0, first = true; i < line.widgets.length; ++i) {
  580. var widget = line.widgets[i], isFirst = false;
  581. if (!widget.above) { isFirst = first; first = false; }
  582. if (widget.node == n.firstChild) {
  583. positionLineWidget(widget, n, reuse, dims);
  584. ++widgetsSeen;
  585. if (isFirst) reuse.insertBefore(lineElement, n);
  586. break;
  587. }
  588. }
  589. if (i == line.widgets.length) { isOk = false; break; }
  590. }
  591. }
  592. if (isOk && widgetsSeen == line.widgets.length) {
  593. wrap = reuse;
  594. reuse.className = line.wrapClass || "";
  595. }
  596. }
  597. if (!wrap) {
  598. wrap = elt("div", null, line.wrapClass, "position: relative");
  599. wrap.appendChild(lineElement);
  600. }
  601. // Kludge to make sure the styled element lies behind the selection (by z-index)
  602. if (line.bgClass)
  603. wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild);
  604. if (cm.options.lineNumbers || markers) {
  605. var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
  606. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
  607. wrap.firstChild);
  608. if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
  609. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  610. wrap.lineNumber = gutterWrap.appendChild(
  611. elt("div", lineNumberFor(cm.options, lineNo),
  612. "CodeMirror-linenumber CodeMirror-gutter-elt",
  613. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  614. + display.lineNumInnerWidth + "px"));
  615. if (markers)
  616. for (var k = 0; k < cm.options.gutters.length; ++k) {
  617. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  618. if (found)
  619. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  620. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  621. }
  622. }
  623. if (ie_lt8) wrap.style.zIndex = 2;
  624. if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  625. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  626. positionLineWidget(widget, node, wrap, dims);
  627. if (widget.above)
  628. wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
  629. else
  630. wrap.appendChild(node);
  631. signalLater(widget, "redraw");
  632. }
  633. return wrap;
  634. }
  635. function positionLineWidget(widget, node, wrap, dims) {
  636. if (widget.noHScroll) {
  637. (wrap.alignable || (wrap.alignable = [])).push(node);
  638. var width = dims.wrapperWidth;
  639. node.style.left = dims.fixedPos + "px";
  640. if (!widget.coverGutter) {
  641. width -= dims.gutterTotalWidth;
  642. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  643. }
  644. node.style.width = width + "px";
  645. }
  646. if (widget.coverGutter) {
  647. node.style.zIndex = 5;
  648. node.style.position = "relative";
  649. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  650. }
  651. }
  652. // SELECTION / CURSOR
  653. function updateSelection(cm) {
  654. var display = cm.display;
  655. var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
  656. if (collapsed || cm.options.showCursorWhenSelecting)
  657. updateSelectionCursor(cm);
  658. else
  659. display.cursor.style.display = display.otherCursor.style.display = "none";
  660. if (!collapsed)
  661. updateSelectionRange(cm);
  662. else
  663. display.selectionDiv.style.display = "none";
  664. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  665. var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
  666. var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
  667. display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  668. headPos.top + lineOff.top - wrapOff.top)) + "px";
  669. display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  670. headPos.left + lineOff.left - wrapOff.left)) + "px";
  671. }
  672. // No selection, plain cursor
  673. function updateSelectionCursor(cm) {
  674. var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
  675. display.cursor.style.left = pos.left + "px";
  676. display.cursor.style.top = pos.top + "px";
  677. display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  678. display.cursor.style.display = "";
  679. if (pos.other) {
  680. display.otherCursor.style.display = "";
  681. display.otherCursor.style.left = pos.other.left + "px";
  682. display.otherCursor.style.top = pos.other.top + "px";
  683. display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  684. } else { display.otherCursor.style.display = "none"; }
  685. }
  686. // Highlight selection
  687. function updateSelectionRange(cm) {
  688. var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
  689. var fragment = document.createDocumentFragment();
  690. var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
  691. function add(left, top, width, bottom) {
  692. if (top < 0) top = 0;
  693. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  694. "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
  695. "px; height: " + (bottom - top) + "px"));
  696. }
  697. function drawForLine(line, fromArg, toArg, retTop) {
  698. var lineObj = getLine(doc, line);
  699. var lineLen = lineObj.text.length, rVal = retTop ? Infinity : -Infinity;
  700. function coords(ch) {
  701. return charCoords(cm, Pos(line, ch), "div", lineObj);
  702. }
  703. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  704. var leftPos = coords(dir == "rtl" ? to - 1 : from);
  705. var rightPos = coords(dir == "rtl" ? from : to - 1);
  706. var left = leftPos.left, right = rightPos.right;
  707. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  708. add(left, leftPos.top, null, leftPos.bottom);
  709. left = pl;
  710. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  711. }
  712. if (toArg == null && to == lineLen) right = clientWidth;
  713. if (fromArg == null && from == 0) left = pl;
  714. rVal = retTop ? Math.min(rightPos.top, rVal) : Math.max(rightPos.bottom, rVal);
  715. if (left < pl + 1) left = pl;
  716. add(left, rightPos.top, right - left, rightPos.bottom);
  717. });
  718. return rVal;
  719. }
  720. if (sel.from.line == sel.to.line) {
  721. drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
  722. } else {
  723. var fromObj = getLine(doc, sel.from.line);
  724. var cur = fromObj, merged, path = [sel.from.line, sel.from.ch], singleLine;
  725. while (merged = collapsedSpanAtEnd(cur)) {
  726. var found = merged.find();
  727. path.push(found.from.ch, found.to.line, found.to.ch);
  728. if (found.to.line == sel.to.line) {
  729. path.push(sel.to.ch);
  730. singleLine = true;
  731. break;
  732. }
  733. cur = getLine(doc, found.to.line);
  734. }
  735. // This is a single, merged line
  736. if (singleLine) {
  737. for (var i = 0; i < path.length; i += 3)
  738. drawForLine(path[i], path[i+1], path[i+2]);
  739. } else {
  740. var middleTop, middleBot, toObj = getLine(doc, sel.to.line);
  741. if (sel.from.ch)
  742. // Draw the first line of selection.
  743. middleTop = drawForLine(sel.from.line, sel.from.ch, null, false);
  744. else
  745. // Simply include it in the middle block.
  746. middleTop = heightAtLine(cm, fromObj) - display.viewOffset;
  747. if (!sel.to.ch)
  748. middleBot = heightAtLine(cm, toObj) - display.viewOffset;
  749. else
  750. middleBot = drawForLine(sel.to.line, collapsedSpanAtStart(toObj) ? null : 0, sel.to.ch, true);
  751. if (middleTop < middleBot) add(pl, middleTop, null, middleBot);
  752. }
  753. }
  754. removeChildrenAndAdd(display.selectionDiv, fragment);
  755. display.selectionDiv.style.display = "";
  756. }
  757. // Cursor-blinking
  758. function restartBlink(cm) {
  759. var display = cm.display;
  760. clearInterval(display.blinker);
  761. var on = true;
  762. display.cursor.style.visibility = display.otherCursor.style.visibility = "";
  763. display.blinker = setInterval(function() {
  764. if (!display.cursor.offsetHeight) return;
  765. display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
  766. }, cm.options.cursorBlinkRate);
  767. }
  768. // HIGHLIGHT WORKER
  769. function startWorker(cm, time) {
  770. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
  771. cm.state.highlight.set(time, bind(highlightWorker, cm));
  772. }
  773. function highlightWorker(cm) {
  774. var doc = cm.doc;
  775. if (doc.frontier < doc.first) doc.frontier = doc.first;
  776. if (doc.frontier >= cm.display.showingTo) return;
  777. var end = +new Date + cm.options.workTime;
  778. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  779. var changed = [], prevChange;
  780. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
  781. if (doc.frontier >= cm.display.showingFrom) { // Visible
  782. var oldStyles = line.styles;
  783. line.styles = highlightLine(cm, line, state);
  784. var ischange = !oldStyles || oldStyles.length != line.styles.length;
  785. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  786. if (ischange) {
  787. if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
  788. else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
  789. }
  790. line.stateAfter = copyState(doc.mode, state);
  791. } else {
  792. processLine(cm, line, state);
  793. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  794. }
  795. ++doc.frontier;
  796. if (+new Date > end) {
  797. startWorker(cm, cm.options.workDelay);
  798. return true;
  799. }
  800. });
  801. if (changed.length)
  802. operation(cm, function() {
  803. for (var i = 0; i < changed.length; ++i)
  804. regChange(this, changed[i].start, changed[i].end);
  805. })();
  806. }
  807. // Finds the line to start with when starting a parse. Tries to
  808. // find a line with a stateAfter, so that it can start with a
  809. // valid state. If that fails, it returns the line with the
  810. // smallest indentation, which tends to need the least context to
  811. // parse correctly.
  812. function findStartLine(cm, n) {
  813. var minindent, minline, doc = cm.doc;
  814. for (var search = n, lim = n - 100; search > lim; --search) {
  815. if (search <= doc.first) return doc.first;
  816. var line = getLine(doc, search - 1);
  817. if (line.stateAfter) return search;
  818. var indented = countColumn(line.text, null, cm.options.tabSize);
  819. if (minline == null || minindent > indented) {
  820. minline = search - 1;
  821. minindent = indented;
  822. }
  823. }
  824. return minline;
  825. }
  826. function getStateBefore(cm, n) {
  827. var doc = cm.doc, display = cm.display;
  828. if (!doc.mode.startState) return true;
  829. var pos = findStartLine(cm, n), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  830. if (!state) state = startState(doc.mode);
  831. else state = copyState(doc.mode, state);
  832. doc.iter(pos, n, function(line) {
  833. processLine(cm, line, state);
  834. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
  835. line.stateAfter = save ? copyState(doc.mode, state) : null;
  836. ++pos;
  837. });
  838. return state;
  839. }
  840. // POSITION MEASUREMENT
  841. function paddingTop(display) {return display.lineSpace.offsetTop;}
  842. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  843. function paddingLeft(display) {
  844. var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
  845. return e.offsetLeft;
  846. }
  847. function measureChar(cm, line, ch, data) {
  848. var dir = -1;
  849. data = data || measureLine(cm, line);
  850. for (var pos = ch;; pos += dir) {
  851. var r = data[pos];
  852. if (r) break;
  853. if (dir < 0 && pos == 0) dir = 1;
  854. }
  855. return {left: pos < ch ? r.right : r.left,
  856. right: pos > ch ? r.left : r.right,
  857. top: r.top, bottom: r.bottom};
  858. }
  859. function findCachedMeasurement(cm, line) {
  860. var cache = cm.display.measureLineCache;
  861. for (var i = 0; i < cache.length; ++i) {
  862. var memo = cache[i];
  863. if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
  864. cm.display.scroller.clientWidth == memo.width &&
  865. memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass)
  866. return memo.measure;
  867. }
  868. }
  869. function measureLine(cm, line) {
  870. // First look in the cache
  871. var measure = findCachedMeasurement(cm, line);
  872. if (!measure) {
  873. // Failing that, recompute and store result in cache
  874. measure = measureLineInner(cm, line);
  875. var cache = cm.display.measureLineCache;
  876. var memo = {text: line.text, width: cm.display.scroller.clientWidth,
  877. markedSpans: line.markedSpans, measure: measure,
  878. classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass};
  879. if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
  880. else cache.push(memo);
  881. }
  882. return measure;
  883. }
  884. function measureLineInner(cm, line) {
  885. var display = cm.display, measure = emptyArray(line.text.length);
  886. var pre = lineContent(cm, line, measure);
  887. // IE does not cache element positions of inline elements between
  888. // calls to getBoundingClientRect. This makes the loop below,
  889. // which gathers the positions of all the characters on the line,
  890. // do an amount of layout work quadratic to the number of
  891. // characters. When line wrapping is off, we try to improve things
  892. // by first subdividing the line into a bunch of inline blocks, so
  893. // that IE can reuse most of the layout information from caches
  894. // for those blocks. This does interfere with line wrapping, so it
  895. // doesn't work when wrapping is on, but in that case the
  896. // situation is slightly better, since IE does cache line-wrapping
  897. // information and only recomputes per-line.
  898. if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
  899. var fragment = document.createDocumentFragment();
  900. var chunk = 10, n = pre.childNodes.length;
  901. for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
  902. var wrap = elt("div", null, null, "display: inline-block");
  903. for (var j = 0; j < chunk && n; ++j) {
  904. wrap.appendChild(pre.firstChild);
  905. --n;
  906. }
  907. fragment.appendChild(wrap);
  908. }
  909. pre.appendChild(fragment);
  910. }
  911. removeChildrenAndAdd(display.measure, pre);
  912. var outer = getRect(display.lineDiv);
  913. var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
  914. // Work around an IE7/8 bug where it will sometimes have randomly
  915. // replaced our pre with a clone at this point.
  916. if (ie_lt9 && display.measure.first != pre)
  917. removeChildrenAndAdd(display.measure, pre);
  918. for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
  919. var size = getRect(cur);
  920. var top = Math.max(0, size.top - outer.top), bot = Math.min(size.bottom - outer.top, maxBot);
  921. for (var j = 0; j < vranges.length; j += 2) {
  922. var rtop = vranges[j], rbot = vranges[j+1];
  923. if (rtop > bot || rbot < top) continue;
  924. if (rtop <= top && rbot >= bot ||
  925. top <= rtop && bot >= rbot ||
  926. Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
  927. vranges[j] = Math.min(top, rtop);
  928. vranges[j+1] = Math.max(bot, rbot);
  929. break;
  930. }
  931. }
  932. if (j == vranges.length) vranges.push(top, bot);
  933. var right = size.right;
  934. if (cur.measureRight) right = getRect(cur.measureRight).left;
  935. data[i] = {left: size.left - outer.left, right: right - outer.left, top: j};
  936. }
  937. for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
  938. var vr = cur.top;
  939. cur.top = vranges[vr]; cur.bottom = vranges[vr+1];
  940. }
  941. return data;
  942. }
  943. function measureLineWidth(cm, line) {
  944. var hasBadSpan = false;
  945. if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
  946. var sp = line.markedSpans[i];
  947. if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
  948. }
  949. var cached = !hasBadSpan && findCachedMeasurement(cm, line);
  950. if (cached) return measureChar(cm, line, line.text.length, cached).right;
  951. var pre = lineContent(cm, line);
  952. var end = pre.appendChild(zeroWidthElement(cm.display.measure));
  953. removeChildrenAndAdd(cm.display.measure, pre);
  954. return getRect(end).right - getRect(cm.display.lineDiv).left;
  955. }
  956. function clearCaches(cm) {
  957. cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
  958. cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
  959. cm.display.maxLineChanged = true;
  960. cm.display.lineNumChars = null;
  961. }
  962. // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
  963. function intoCoordSystem(cm, lineObj, rect, context) {
  964. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  965. var size = widgetHeight(lineObj.widgets[i]);
  966. rect.top += size; rect.bottom += size;
  967. }
  968. if (context == "line") return rect;
  969. if (!context) context = "local";
  970. var yOff = heightAtLine(cm, lineObj);
  971. if (context != "local") yOff -= cm.display.viewOffset;
  972. if (context == "page") {
  973. var lOff = getRect(cm.display.lineSpace);
  974. yOff += lOff.top + (window.pageYOffset || (document.documentElement || document.body).scrollTop);
  975. var xOff = lOff.left + (window.pageXOffset || (document.documentElement || document.body).scrollLeft);
  976. rect.left += xOff; rect.right += xOff;
  977. }
  978. rect.top += yOff; rect.bottom += yOff;
  979. return rect;
  980. }
  981. // Context may be "window", "page", "div", or "local"/null
  982. // Result is in local coords
  983. function fromCoordSystem(cm, coords, context) {
  984. if (context == "div") return coords;
  985. var left = coords.left, top = coords.top;
  986. if (context == "page") {
  987. left -= window.pageXOffset || (document.documentElement || document.body).scrollLeft;
  988. top -= window.pageYOffset || (document.documentElement || document.body).scrollTop;
  989. }
  990. var lineSpaceBox = getRect(cm.display.lineSpace);
  991. left -= lineSpaceBox.left;
  992. top -= lineSpaceBox.top;
  993. if (context == "local" || !context) {
  994. var editorBox = getRect(cm.display.wrapper);
  995. left -= editorBox.left;
  996. top -= editorBox.top;
  997. }
  998. return {left: left, top: top};
  999. }
  1000. function charCoords(cm, pos, context, lineObj) {
  1001. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  1002. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch), context);
  1003. }
  1004. function cursorCoords(cm, pos, context, lineObj, measurement) {
  1005. lineObj = lineObj || getLine(cm.doc, pos.line);
  1006. if (!measurement) measurement = measureLine(cm, lineObj);
  1007. function get(ch, right) {
  1008. var m = measureChar(cm, lineObj, ch, measurement);
  1009. if (right) m.left = m.right; else m.right = m.left;
  1010. return intoCoordSystem(cm, lineObj, m, context);
  1011. }
  1012. var order = getOrder(lineObj), ch = pos.ch;
  1013. if (!order) return get(ch);
  1014. var main, other, linedir = order[0].level;
  1015. for (var i = 0; i < order.length; ++i) {
  1016. var part = order[i], rtl = part.level % 2, nb, here;
  1017. if (part.from < ch && part.to > ch) return get(ch, rtl);
  1018. var left = rtl ? part.to : part.from, right = rtl ? part.from : part.to;
  1019. if (left == ch) {
  1020. // IE returns bogus offsets and widths for edges where the
  1021. // direction flips, but only for the side with the lower
  1022. // level. So we try to use the side with the higher level.
  1023. if (i && part.level < (nb = order[i-1]).level) here = get(nb.level % 2 ? nb.from : nb.to - 1, true);
  1024. else here = get(rtl && part.from != part.to ? ch - 1 : ch);
  1025. if (rtl == linedir) main = here; else other = here;
  1026. } else if (right == ch) {
  1027. var nb = i < order.length - 1 && order[i+1];
  1028. if (!rtl && nb && nb.from == nb.to) continue;
  1029. if (nb && part.level < nb.level) here = get(nb.level % 2 ? nb.to - 1 : nb.from);
  1030. else here = get(rtl ? ch : ch - 1, true);
  1031. if (rtl == linedir) main = here; else other = here;
  1032. }
  1033. }
  1034. if (linedir && !ch) other = get(order[0].to - 1);
  1035. if (!main) return other;
  1036. if (other) main.other = other;
  1037. return main;
  1038. }
  1039. function PosMaybeOutside(line, ch, outside) {
  1040. var pos = new Pos(line, ch);
  1041. if (outside) pos.outside = true;
  1042. return pos;
  1043. }
  1044. // Coords must be lineSpace-local
  1045. function coordsChar(cm, x, y) {
  1046. var doc = cm.doc;
  1047. y += cm.display.viewOffset;
  1048. if (y < 0) return PosMaybeOutside(doc.first, 0, true);
  1049. var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  1050. if (lineNo > last)
  1051. return PosMaybeOutside(doc.first + doc.size - 1, getLine(doc, last).text.length, true);
  1052. if (x < 0) x = 0;
  1053. for (;;) {
  1054. var lineObj = getLine(doc, lineNo);
  1055. var found = coordsCharInner(cm, lineObj, lineNo, x, y);
  1056. var merged = collapsedSpanAtEnd(lineObj);
  1057. var mergedPos = merged && merged.find();
  1058. if (merged && found.ch >= mergedPos.from.ch)
  1059. lineNo = mergedPos.to.line;
  1060. else
  1061. return found;
  1062. }
  1063. }
  1064. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  1065. var innerOff = y - heightAtLine(cm, lineObj);
  1066. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  1067. var measurement = measureLine(cm, lineObj);
  1068. function getX(ch) {
  1069. var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
  1070. lineObj, measurement);
  1071. wrongLine = true;
  1072. if (innerOff > sp.bottom) return sp.left - adjust;
  1073. else if (innerOff < sp.top) return sp.left + adjust;
  1074. else wrongLine = false;
  1075. return sp.left;
  1076. }
  1077. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  1078. var from = lineLeft(lineObj), to = lineRight(lineObj);
  1079. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  1080. if (x > toX) return PosMaybeOutside(lineNo, to, toOutside);
  1081. // Do a binary search between these bounds.
  1082. for (;;) {
  1083. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  1084. var after = x - fromX < toX - x, ch = after ? from : to;
  1085. while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
  1086. var pos = PosMaybeOutside(lineNo, ch, after ? fromOutside : toOutside);
  1087. pos.after = after;
  1088. return pos;
  1089. }
  1090. var step = Math.ceil(dist / 2), middle = from + step;
  1091. if (bidi) {
  1092. middle = from;
  1093. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  1094. }
  1095. var middleX = getX(middle);
  1096. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist -= step;}
  1097. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist = step;}
  1098. }
  1099. }
  1100. var measureText;
  1101. function textHeight(display) {
  1102. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  1103. if (measureText == null) {
  1104. measureText = elt("pre");
  1105. // Measure a bunch of lines, for browsers that compute
  1106. // fractional heights.
  1107. for (var i = 0; i < 49; ++i) {
  1108. measureText.appendChild(document.createTextNode("x"));
  1109. measureText.appendChild(elt("br"));
  1110. }
  1111. measureText.appendChild(document.createTextNode("x"));
  1112. }
  1113. removeChildrenAndAdd(display.measure, measureText);
  1114. var height = measureText.offsetHeight / 50;
  1115. if (height > 3) display.cachedTextHeight = height;
  1116. removeChildren(display.measure);
  1117. return height || 1;
  1118. }
  1119. function charWidth(display) {
  1120. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  1121. var anchor = elt("span", "x");
  1122. var pre = elt("pre", [anchor]);
  1123. removeChildrenAndAdd(display.measure, pre);
  1124. var width = anchor.offsetWidth;
  1125. if (width > 2) display.cachedCharWidth = width;
  1126. return width || 10;
  1127. }
  1128. // OPERATIONS
  1129. // Operations are used to wrap changes in such a way that each
  1130. // change won't have to update the cursor and display (which would
  1131. // be awkward, slow, and error-prone), but instead updates are
  1132. // batched and then all combined and executed at once.
  1133. var nextOpId = 0;
  1134. function startOperation(cm) {
  1135. cm.curOp = {
  1136. // An array of ranges of lines that have to be updated. See
  1137. // updateDisplay.
  1138. changes: [],
  1139. updateInput: null,
  1140. userSelChange: null,
  1141. textChanged: null,
  1142. selectionChanged: false,
  1143. updateMaxLine: false,
  1144. updateScrollPos: false,
  1145. id: ++nextOpId
  1146. };
  1147. if (!delayedCallbackDepth++) delayedCallbacks = [];
  1148. }
  1149. function endOperation(cm) {
  1150. var op = cm.curOp, doc = cm.doc, display = cm.display;
  1151. cm.curOp = null;
  1152. if (op.updateMaxLine) computeMaxLength(cm);
  1153. if (display.maxLineChanged && !cm.options.lineWrapping) {
  1154. var width = measureLineWidth(cm, display.maxLine);
  1155. display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
  1156. display.maxLineChanged = false;
  1157. var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
  1158. if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
  1159. setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
  1160. }
  1161. var newScrollPos, updated;
  1162. if (op.updateScrollPos) {
  1163. newScrollPos = op.updateScrollPos;
  1164. } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
  1165. var coords = cursorCoords(cm, doc.sel.head);
  1166. newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
  1167. }
  1168. if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) {
  1169. updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop);
  1170. if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
  1171. }
  1172. if (!updated && op.selectionChanged) updateSelection(cm);
  1173. if (op.updateScrollPos) {
  1174. display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
  1175. display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
  1176. alignHorizontally(cm);
  1177. } else if (newScrollPos) {
  1178. scrollCursorIntoView(cm);
  1179. }
  1180. if (op.selectionChanged) restartBlink(cm);
  1181. if (cm.state.focused && op.updateInput)
  1182. resetInput(cm, op.userSelChange);
  1183. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  1184. if (hidden) for (var i = 0; i < hidden.length; ++i)
  1185. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  1186. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  1187. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  1188. var delayed;
  1189. if (!--delayedCallbackDepth) {
  1190. delayed = delayedCallbacks;
  1191. delayedCallbacks = null;
  1192. }
  1193. if (op.textChanged)
  1194. signal(cm, "change", cm, op.textChanged);
  1195. if (op.selectionChanged) signal(cm, "cursorActivity", cm);
  1196. if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
  1197. }
  1198. // Wraps a function in an operation. Returns the wrapped function.
  1199. function operation(cm1, f) {
  1200. return function() {
  1201. var cm = cm1 || this, withOp = !cm.curOp;
  1202. if (withOp) startOperation(cm);
  1203. try { var result = f.apply(cm, arguments); }
  1204. finally { if (withOp) endOperation(cm); }
  1205. return result;
  1206. };
  1207. }
  1208. function docOperation(f) {
  1209. return function() {
  1210. var withOp = this.cm && !this.cm.curOp, result;
  1211. if (withOp) startOperation(this.cm);
  1212. try { result = f.apply(this, arguments); }
  1213. finally { if (withOp) endOperation(this.cm); }
  1214. return result;
  1215. };
  1216. }
  1217. function runInOp(cm, f) {
  1218. var withOp = !cm.curOp, result;
  1219. if (withOp) startOperation(cm);
  1220. try { result = f(); }
  1221. finally { if (withOp) endOperation(cm); }
  1222. return result;
  1223. }
  1224. function regChange(cm, from, to, lendiff) {
  1225. if (from == null) from = cm.doc.first;
  1226. if (to == null) to = cm.doc.first + cm.doc.size;
  1227. cm.curOp.changes.push({from: from, to: to, diff: lendiff});
  1228. }
  1229. // INPUT HANDLING
  1230. function slowPoll(cm) {
  1231. if (cm.display.pollingFast) return;
  1232. cm.display.poll.set(cm.options.pollInterval, function() {
  1233. readInput(cm);
  1234. if (cm.state.focused) slowPoll(cm);
  1235. });
  1236. }
  1237. function fastPoll(cm) {
  1238. var missed = false;
  1239. cm.display.pollingFast = true;
  1240. function p() {
  1241. var changed = readInput(cm);
  1242. if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
  1243. else {cm.display.pollingFast = false; slowPoll(cm);}
  1244. }
  1245. cm.display.poll.set(20, p);
  1246. }
  1247. // prevInput is a hack to work with IME. If we reset the textarea
  1248. // on every change, that breaks IME. So we look for changes
  1249. // compared to the previous content instead. (Modern browsers have
  1250. // events that indicate IME taking place, but these are not widely
  1251. // supported or compatible enough yet to rely on.)
  1252. function readInput(cm) {
  1253. var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
  1254. if (!cm.state.focused || hasSelection(input) || isReadOnly(cm)) return false;
  1255. var text = input.value;
  1256. if (text == prevInput && posEq(sel.from, sel.to)) return false;
  1257. // IE enjoys randomly deselecting our input's text when
  1258. // re-focusing. If the selection is gone but the cursor is at the
  1259. // start of the input, that's probably what happened.
  1260. if (ie && text && input.selectionStart === 0) {
  1261. resetInput(cm, true);
  1262. return false;
  1263. }
  1264. var withOp = !cm.curOp;
  1265. if (withOp) startOperation(cm);
  1266. sel.shift = false;
  1267. var same = 0, l = Math.min(prevInput.length, text.length);
  1268. while (same < l && prevInput[same] == text[same]) ++same;
  1269. var from = sel.from, to = sel.to;
  1270. if (same < prevInput.length)
  1271. from = Pos(from.line, from.ch - (prevInput.length - same));
  1272. else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
  1273. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
  1274. var updateInput = cm.curOp.updateInput;
  1275. makeChange(cm.doc, {from: from, to: to, text: splitLines(text.slice(same)),
  1276. origin: cm.state.pasteIncoming ? "paste" : "+input"}, "end");
  1277. cm.curOp.updateInput = updateInput;
  1278. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
  1279. else cm.display.prevInput = text;
  1280. if (withOp) endOperation(cm);
  1281. cm.state.pasteIncoming = false;
  1282. return true;
  1283. }
  1284. function resetInput(cm, user) {
  1285. var minimal, selected, doc = cm.doc;
  1286. if (!posEq(doc.sel.from, doc.sel.to)) {
  1287. cm.display.prevInput = "";
  1288. minimal = hasCopyEvent &&
  1289. (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
  1290. if (minimal) cm.display.input.value = "-";
  1291. else cm.display.input.value = selected || cm.getSelection();
  1292. if (cm.state.focused) selectInput(cm.display.input);
  1293. } else if (user) cm.display.prevInput = cm.display.input.value = "";
  1294. cm.display.inaccurateSelection = minimal;
  1295. }
  1296. function focusInput(cm) {
  1297. if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
  1298. cm.display.input.focus();
  1299. }
  1300. function isReadOnly(cm) {
  1301. return cm.options.readOnly || cm.doc.cantEdit;
  1302. }
  1303. // EVENT HANDLERS
  1304. function registerEventHandlers(cm) {
  1305. var d = cm.display;
  1306. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  1307. on(d.scroller, "dblclick", operation(cm, e_preventDefault));
  1308. on(d.lineSpace, "selectstart", function(e) {
  1309. if (!eventInWidget(d, e)) e_preventDefault(e);
  1310. });
  1311. // Gecko browsers fire contextmenu *after* opening the menu, at
  1312. // which point we can't mess with it anymore. Context menu is
  1313. // handled in onMouseDown for Gecko.
  1314. if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  1315. on(d.scroller, "scroll", function() {
  1316. if (d.scroller.clientHeight) {
  1317. setScrollTop(cm, d.scroller.scrollTop);
  1318. setScrollLeft(cm, d.scroller.scrollLeft, true);
  1319. signal(cm, "scroll", cm);
  1320. }
  1321. });
  1322. on(d.scrollbarV, "scroll", function() {
  1323. if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
  1324. });
  1325. on(d.scrollbarH, "scroll", function() {
  1326. if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
  1327. });
  1328. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  1329. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  1330. function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
  1331. on(d.scrollbarH, "mousedown", reFocus);
  1332. on(d.scrollbarV, "mousedown", reFocus);
  1333. // Prevent wrapper from ever scrolling
  1334. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  1335. function onResize() {
  1336. // Might be a text scaling operation, clear size caches.
  1337. d.cachedCharWidth = d.cachedTextHeight = null;
  1338. clearCaches(cm);
  1339. runInOp(cm, bind(regChange, cm));
  1340. }
  1341. on(window, "resize", onResize);
  1342. // Above handler holds on to the editor and its data structures.
  1343. // Here we poll to unregister it when the editor is no longer in
  1344. // the document, so that it can be garbage-collected.
  1345. function unregister() {
  1346. for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
  1347. if (p) setTimeout(unregister, 5000);
  1348. else off(window, "resize", onResize);
  1349. }
  1350. setTimeout(unregister, 5000);
  1351. on(d.input, "keyup", operation(cm, function(e) {
  1352. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1353. if (e.keyCode == 16) cm.doc.sel.shift = false;
  1354. }));
  1355. on(d.input, "input", bind(fastPoll, cm));
  1356. on(d.input, "keydown", operation(cm, onKeyDown));
  1357. on(d.input, "keypress", operation(cm, onKeyPress));
  1358. on(d.input, "focus", bind(onFocus, cm));
  1359. on(d.input, "blur", bind(onBlur, cm));
  1360. function drag_(e) {
  1361. if (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
  1362. e_stop(e);
  1363. }
  1364. if (cm.options.dragDrop) {
  1365. on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
  1366. on(d.scroller, "dragenter", drag_);
  1367. on(d.scroller, "dragover", drag_);
  1368. on(d.scroller, "drop", operation(cm, onDrop));
  1369. }
  1370. on(d.scroller, "paste", function(e){
  1371. if (eventInWidget(d, e)) return;
  1372. focusInput(cm);
  1373. fastPoll(cm);
  1374. });
  1375. on(d.input, "paste", function() {
  1376. cm.state.pasteIncoming = true;
  1377. fastPoll(cm);
  1378. });
  1379. function prepareCopy() {
  1380. if (d.inaccurateSelection) {
  1381. d.prevInput = "";
  1382. d.inaccurateSelection = false;
  1383. d.input.value = cm.getSelection();
  1384. selectInput(d.input);
  1385. }
  1386. }
  1387. on(d.input, "cut", prepareCopy);
  1388. on(d.input, "copy", prepareCopy);
  1389. // Needed to handle Tab key in KHTML
  1390. if (khtml) on(d.sizer, "mouseup", function() {
  1391. if (document.activeElement == d.input) d.input.blur();
  1392. focusInput(cm);
  1393. });
  1394. }
  1395. function eventInWidget(display, e) {
  1396. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  1397. if (!n) return true;
  1398. if (/\bCodeMirror-(?:line)?widget\b/.test(n.className) ||
  1399. n.parentNode == display.sizer && n != display.mover) return true;
  1400. }
  1401. }
  1402. function posFromMouse(cm, e, liberal) {
  1403. var display = cm.display;
  1404. if (!liberal) {
  1405. var target = e_target(e);
  1406. if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
  1407. target == display.scrollbarV || target == display.scrollbarV.firstChild ||
  1408. target == display.scrollbarFiller) return null;
  1409. }
  1410. var x, y, space = getRect(display.lineSpace);
  1411. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  1412. try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
  1413. return coordsChar(cm, x - space.left, y - space.top);
  1414. }
  1415. var lastClick, lastDoubleClick;
  1416. function onMouseDown(e) {
  1417. var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
  1418. sel.shift = e.shiftKey;
  1419. if (eventInWidget(display, e)) {
  1420. if (!webkit) {
  1421. display.scroller.draggable = false;
  1422. setTimeout(function(){display.scroller.draggable = true;}, 100);
  1423. }
  1424. return;
  1425. }
  1426. if (clickInGutter(cm, e)) return;
  1427. var start = posFromMouse(cm, e);
  1428. switch (e_button(e)) {
  1429. case 3:
  1430. if (captureMiddleClick) onContextMenu.call(cm, cm, e);
  1431. return;
  1432. case 2:
  1433. if (start) extendSelection(cm.doc, start);
  1434. setTimeout(bind(focusInput, cm), 20);
  1435. e_preventDefault(e);
  1436. return;
  1437. }
  1438. // For button 1, if it was clicked inside the editor
  1439. // (posFromMouse returning non-null), we have to adjust the
  1440. // selection.
  1441. if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
  1442. if (!cm.state.focused) onFocus(cm);
  1443. var now = +new Date, type = "single";
  1444. if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
  1445. type = "triple";
  1446. e_preventDefault(e);
  1447. setTimeout(bind(focusInput, cm), 20);
  1448. selectLine(cm, start.line);
  1449. } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
  1450. type = "double";
  1451. lastDoubleClick = {time: now, pos: start};
  1452. e_preventDefault(e);
  1453. var word = findWordAt(getLine(doc, start.line).text, start);
  1454. extendSelection(cm.doc, word.from, word.to);
  1455. } else { lastClick = {time: now, pos: start}; }
  1456. var last = start;
  1457. if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
  1458. !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
  1459. var dragEnd = operation(cm, function(e2) {
  1460. if (webkit) display.scroller.draggable = false;
  1461. cm.state.draggingText = false;
  1462. off(document, "mouseup", dragEnd);
  1463. off(display.scroller, "drop", dragEnd);
  1464. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  1465. e_preventDefault(e2);
  1466. extendSelection(cm.doc, start);
  1467. focusInput(cm);
  1468. }
  1469. });
  1470. // Let the drag handler handle this.
  1471. if (webkit) display.scroller.draggable = true;
  1472. cm.state.draggingText = dragEnd;
  1473. // IE's approach to draggable
  1474. if (display.scroller.dragDrop) display.scroller.dragDrop();
  1475. on(document, "mouseup", dragEnd);
  1476. on(display.scroller, "drop", dragEnd);
  1477. return;
  1478. }
  1479. e_preventDefault(e);
  1480. if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
  1481. var startstart = sel.from, startend = sel.to;
  1482. function doSelect(cur) {
  1483. if (type == "single") {
  1484. extendSelection(cm.doc, clipPos(doc, start), cur);
  1485. return;
  1486. }
  1487. startstart = clipPos(doc, startstart);
  1488. startend = clipPos(doc, startend);
  1489. if (type == "double") {
  1490. var word = findWordAt(getLine(doc, cur.line).text, cur);
  1491. if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
  1492. else extendSelection(cm.doc, startstart, word.to);
  1493. } else if (type == "triple") {
  1494. if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
  1495. else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
  1496. }
  1497. }
  1498. var editorSize = getRect(display.wrapper);
  1499. // Used to ensure timeout re-tries don't fire when another extend
  1500. // happened in the meantime (clearTimeout isn't reliable -- at
  1501. // least on Chrome, the timeouts still happen even when cleared,
  1502. // if the clear happens after their scheduled firing time).
  1503. var counter = 0;
  1504. function extend(e) {
  1505. var curCount = ++counter;
  1506. var cur = posFromMouse(cm, e, true);
  1507. if (!cur) return;
  1508. if (!posEq(cur, last)) {
  1509. if (!cm.state.focused) onFocus(cm);
  1510. last = cur;
  1511. doSelect(cur);
  1512. var visible = visibleLines(display, doc);
  1513. if (cur.line >= visible.to || cur.line < visible.from)
  1514. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  1515. } else {
  1516. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  1517. if (outside) setTimeout(operation(cm, function() {
  1518. if (counter != curCount) return;
  1519. display.scroller.scrollTop += outside;
  1520. extend(e);
  1521. }), 50);
  1522. }
  1523. }
  1524. function done(e) {
  1525. counter = Infinity;
  1526. var cur = posFromMouse(cm, e);
  1527. if (cur) doSelect(cur);
  1528. e_preventDefault(e);
  1529. focusInput(cm);
  1530. off(document, "mousemove", move);
  1531. off(document, "mouseup", up);
  1532. }
  1533. var move = operation(cm, function(e) {
  1534. if (!ie && !e_button(e)) done(e);
  1535. else extend(e);
  1536. });
  1537. var up = operation(cm, done);
  1538. on(document, "mousemove", move);
  1539. on(document, "mouseup", up);
  1540. }
  1541. function onDrop(e) {
  1542. var cm = this;
  1543. if (eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
  1544. return;
  1545. e_preventDefault(e);
  1546. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  1547. if (!pos || isReadOnly(cm)) return;
  1548. if (files && files.length && window.FileReader && window.File) {
  1549. var n = files.length, text = Array(n), read = 0;
  1550. var loadFile = function(file, i) {
  1551. var reader = new FileReader;
  1552. reader.onload = function() {
  1553. text[i] = reader.result;
  1554. if (++read == n) {
  1555. pos = clipPos(cm.doc, pos);
  1556. makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
  1557. }
  1558. };
  1559. reader.readAsText(file);
  1560. };
  1561. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  1562. } else {
  1563. // Don't do a replace if the drop happened inside of the selected text.
  1564. if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
  1565. cm.state.draggingText(e);
  1566. // Ensure the editor is re-focused
  1567. setTimeout(bind(focusInput, cm), 20);
  1568. return;
  1569. }
  1570. try {
  1571. var text = e.dataTransfer.getData("Text");
  1572. if (text) {
  1573. var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
  1574. setSelection(cm.doc, pos, pos);
  1575. if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
  1576. cm.replaceSelection(text, null, "paste");
  1577. focusInput(cm);
  1578. onFocus(cm);
  1579. }
  1580. }
  1581. catch(e){}
  1582. }
  1583. }
  1584. function clickInGutter(cm, e) {
  1585. var display = cm.display;
  1586. try { var mX = e.clientX, mY = e.clientY; }
  1587. catch(e) { return false; }
  1588. if (mX >= Math.floor(getRect(display.gutters).right)) return false;
  1589. e_preventDefault(e);
  1590. if (!hasHandler(cm, "gutterClick")) return true;
  1591. var lineBox = getRect(display.lineDiv);
  1592. if (mY > lineBox.bottom) return true;
  1593. mY -= lineBox.top - display.viewOffset;
  1594. for (var i = 0; i < cm.options.gutters.length; ++i) {
  1595. var g = display.gutters.childNodes[i];
  1596. if (g && getRect(g).right >= mX) {
  1597. var line = lineAtHeight(cm.doc, mY);
  1598. var gutter = cm.options.gutters[i];
  1599. signalLater(cm, "gutterClick", cm, line, gutter, e);
  1600. break;
  1601. }
  1602. }
  1603. return true;
  1604. }
  1605. function onDragStart(cm, e) {
  1606. if (eventInWidget(cm.display, e)) return;
  1607. var txt = cm.getSelection();
  1608. e.dataTransfer.setData("Text", txt);
  1609. // Use dummy image instead of default browsers image.
  1610. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  1611. if (e.dataTransfer.setDragImage) {
  1612. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  1613. if (opera) {
  1614. img.width = img.height = 1;
  1615. cm.display.wrapper.appendChild(img);
  1616. // Force a relayout, or Opera won't use our image for some obscure reason
  1617. img._top = img.offsetTop;
  1618. }
  1619. if (safari) {
  1620. if (cm.display.dragImg) {
  1621. img = cm.display.dragImg;
  1622. } else {
  1623. cm.display.dragImg = img;
  1624. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  1625. cm.display.wrapper.appendChild(img);
  1626. }
  1627. }
  1628. e.dataTransfer.setDragImage(img, 0, 0);
  1629. if (opera) img.parentNode.removeChild(img);
  1630. }
  1631. }
  1632. function setScrollTop(cm, val) {
  1633. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  1634. cm.doc.scrollTop = val;
  1635. if (!gecko) updateDisplay(cm, [], val);
  1636. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  1637. if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
  1638. if (gecko) updateDisplay(cm, []);
  1639. }
  1640. function setScrollLeft(cm, val, isScroller) {
  1641. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  1642. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  1643. cm.doc.scrollLeft = val;
  1644. alignHorizontally(cm);
  1645. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  1646. if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
  1647. }
  1648. // Since the delta values reported on mouse wheel events are
  1649. // unstandardized between browsers and even browser versions, and
  1650. // generally horribly unpredictable, this code starts by measuring
  1651. // the scroll effect that the first few mouse wheel events have,
  1652. // and, from that, detects the way it can convert deltas to pixel
  1653. // offsets afterwards.
  1654. //
  1655. // The reason we want to know the amount a wheel event will scroll
  1656. // is that it gives us a chance to update the display before the
  1657. // actual scrolling happens, reducing flickering.
  1658. var wheelSamples = 0, wheelPixelsPerUnit = null;
  1659. // Fill in a browser-detected starting value on browsers where we
  1660. // know one. These don't have to be accurate -- the result of them
  1661. // being wrong would just be a slight flicker on the first wheel
  1662. // scroll (if it is large enough).
  1663. if (ie) wheelPixelsPerUnit = -.53;
  1664. else if (gecko) wheelPixelsPerUnit = 15;
  1665. else if (chrome) wheelPixelsPerUnit = -.7;
  1666. else if (safari) wheelPixelsPerUnit = -1/3;
  1667. function onScrollWheel(cm, e) {
  1668. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  1669. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  1670. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  1671. else if (dy == null) dy = e.wheelDelta;
  1672. // Webkit browsers on OS X abort momentum scrolls when the target
  1673. // of the scroll event is removed from the scrollable element.
  1674. // This hack (see related code in patchDisplay) makes sure the
  1675. // element is kept around.
  1676. if (dy && mac && webkit) {
  1677. for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
  1678. if (cur.lineObj) {
  1679. cm.display.currentWheelTarget = cur;
  1680. break;
  1681. }
  1682. }
  1683. }
  1684. var display = cm.display, scroll = display.scroller;
  1685. // On some browsers, horizontal scrolling will cause redraws to
  1686. // happen before the gutter has been realigned, causing it to
  1687. // wriggle around in a most unseemly way. When we have an
  1688. // estimated pixels/delta value, we just handle horizontal
  1689. // scrolling entirely here. It'll be slightly off from native, but
  1690. // better than glitching out.
  1691. if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
  1692. if (dy)
  1693. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  1694. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  1695. e_preventDefault(e);
  1696. display.wheelStartX = null; // Abort measurement, if in progress
  1697. return;
  1698. }
  1699. if (dy && wheelPixelsPerUnit != null) {
  1700. var pixels = dy * wheelPixelsPerUnit;
  1701. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  1702. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  1703. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  1704. updateDisplay(cm, [], {top: top, bottom: bot});
  1705. }
  1706. if (wheelSamples < 20) {
  1707. if (display.wheelStartX == null) {
  1708. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  1709. display.wheelDX = dx; display.wheelDY = dy;
  1710. setTimeout(function() {
  1711. if (display.wheelStartX == null) return;
  1712. var movedX = scroll.scrollLeft - display.wheelStartX;
  1713. var movedY = scroll.scrollTop - display.wheelStartY;
  1714. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  1715. (movedX && display.wheelDX && movedX / display.wheelDX);
  1716. display.wheelStartX = display.wheelStartY = null;
  1717. if (!sample) return;
  1718. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  1719. ++wheelSamples;
  1720. }, 200);
  1721. } else {
  1722. display.wheelDX += dx; display.wheelDY += dy;
  1723. }
  1724. }
  1725. }
  1726. function doHandleBinding(cm, bound, dropShift) {
  1727. if (typeof bound == "string") {
  1728. bound = commands[bound];
  1729. if (!bound) return false;
  1730. }
  1731. // Ensure previous input has been read, so that the handler sees a
  1732. // consistent view of the document
  1733. if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
  1734. var doc = cm.doc, prevShift = doc.sel.shift, done = false;
  1735. try {
  1736. if (isReadOnly(cm)) cm.state.suppressEdits = true;
  1737. if (dropShift) doc.sel.shift = false;
  1738. done = bound(cm) != Pass;
  1739. } finally {
  1740. doc.sel.shift = prevShift;
  1741. cm.state.suppressEdits = false;
  1742. }
  1743. return done;
  1744. }
  1745. function allKeyMaps(cm) {
  1746. var maps = cm.state.keyMaps.slice(0);
  1747. if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
  1748. maps.push(cm.options.keyMap);
  1749. return maps;
  1750. }
  1751. var maybeTransition;
  1752. function handleKeyBinding(cm, e) {
  1753. // Handle auto keymap transitions
  1754. var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
  1755. clearTimeout(maybeTransition);
  1756. if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
  1757. if (getKeyMap(cm.options.keyMap) == startMap)
  1758. cm.options.keyMap = (next.call ? next.call(null, cm) : next);
  1759. }, 50);
  1760. var name = keyName(e, true), handled = false;
  1761. if (!name) return false;
  1762. var keymaps = allKeyMaps(cm);
  1763. if (e.shiftKey) {
  1764. // First try to resolve full name (including 'Shift-'). Failing
  1765. // that, see if there is a cursor-motion command (starting with
  1766. // 'go') bound to the keyname without 'Shift-'.
  1767. handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
  1768. || lookupKey(name, keymaps, function(b) {
  1769. if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(cm, b);
  1770. });
  1771. } else {
  1772. handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
  1773. }
  1774. if (handled == "stop") handled = false;
  1775. if (handled) {
  1776. e_preventDefault(e);
  1777. restartBlink(cm);
  1778. if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
  1779. }
  1780. return handled;
  1781. }
  1782. function handleCharBinding(cm, e, ch) {
  1783. var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
  1784. function(b) { return doHandleBinding(cm, b, true); });
  1785. if (handled) {
  1786. e_preventDefault(e);
  1787. restartBlink(cm);
  1788. }
  1789. return handled;
  1790. }
  1791. var lastStoppedKey = null;
  1792. function onKeyDown(e) {
  1793. var cm = this;
  1794. if (!cm.state.focused) onFocus(cm);
  1795. if (ie && e.keyCode == 27) { e.returnValue = false; }
  1796. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1797. var code = e.keyCode;
  1798. // IE does strange things with escape.
  1799. cm.doc.sel.shift = code == 16 || e.shiftKey;
  1800. // First give onKeyEvent option a chance to handle this.
  1801. var handled = handleKeyBinding(cm, e);
  1802. if (opera) {
  1803. lastStoppedKey = handled ? code : null;
  1804. // Opera has no cut event... we try to at least catch the key combo
  1805. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  1806. cm.replaceSelection("");
  1807. }
  1808. }
  1809. function onKeyPress(e) {
  1810. var cm = this;
  1811. if (cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
  1812. var keyCode = e.keyCode, charCode = e.charCode;
  1813. if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  1814. if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
  1815. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  1816. if (this.options.electricChars && this.doc.mode.electricChars &&
  1817. this.options.smartIndent && !isReadOnly(this) &&
  1818. this.doc.mode.electricChars.indexOf(ch) > -1)
  1819. setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
  1820. if (handleCharBinding(cm, e, ch)) return;
  1821. fastPoll(cm);
  1822. }
  1823. function onFocus(cm) {
  1824. if (cm.options.readOnly == "nocursor") return;
  1825. if (!cm.state.focused) {
  1826. signal(cm, "focus", cm);
  1827. cm.state.focused = true;
  1828. if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
  1829. cm.display.wrapper.className += " CodeMirror-focused";
  1830. resetInput(cm, true);
  1831. }
  1832. slowPoll(cm);
  1833. restartBlink(cm);
  1834. }
  1835. function onBlur(cm) {
  1836. if (cm.state.focused) {
  1837. signal(cm, "blur", cm);
  1838. cm.state.focused = false;
  1839. cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
  1840. }
  1841. clearInterval(cm.display.blinker);
  1842. setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
  1843. }
  1844. var detectingSelectAll;
  1845. function onContextMenu(cm, e) {
  1846. var display = cm.display, sel = cm.doc.sel;
  1847. if (eventInWidget(display, e)) return;
  1848. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  1849. if (!pos || opera) return; // Opera is difficult.
  1850. if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
  1851. operation(cm, setSelection)(cm.doc, pos, pos);
  1852. var oldCSS = display.input.style.cssText;
  1853. display.inputDiv.style.position = "absolute";
  1854. display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
  1855. "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
  1856. "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
  1857. focusInput(cm);
  1858. resetInput(cm, true);
  1859. // Adds "Select all" to context menu in FF
  1860. if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
  1861. function rehide() {
  1862. display.inputDiv.style.position = "relative";
  1863. display.input.style.cssText = oldCSS;
  1864. if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
  1865. slowPoll(cm);
  1866. // Try to detect the user choosing select-all
  1867. if (display.input.selectionStart != null && (!ie || ie_lt9)) {
  1868. clearTimeout(detectingSelectAll);
  1869. var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value), i = 0;
  1870. display.prevInput = " ";
  1871. display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
  1872. var poll = function(){
  1873. if (display.prevInput == " " && display.input.selectionStart == 0)
  1874. operation(cm, commands.selectAll)(cm);
  1875. else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
  1876. else resetInput(cm);
  1877. };
  1878. detectingSelectAll = setTimeout(poll, 200);
  1879. }
  1880. }
  1881. if (captureMiddleClick) {
  1882. e_stop(e);
  1883. var mouseup = function() {
  1884. off(window, "mouseup", mouseup);
  1885. setTimeout(rehide, 20);
  1886. };
  1887. on(window, "mouseup", mouseup);
  1888. } else {
  1889. setTimeout(rehide, 50);
  1890. }
  1891. }
  1892. // UPDATING
  1893. function changeEnd(change) {
  1894. return Pos(change.from.line + change.text.length - 1,
  1895. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  1896. }
  1897. // Make sure a position will be valid after the given change.
  1898. function clipPostChange(doc, change, pos) {
  1899. if (!posLess(change.from, pos)) return clipPos(doc, pos);
  1900. var diff = (change.text.length - 1) - (change.to.line - change.from.line);
  1901. if (pos.line > change.to.line + diff) {
  1902. var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
  1903. if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
  1904. return clipToLen(pos, getLine(doc, preLine).text.length);
  1905. }
  1906. if (pos.line == change.to.line + diff)
  1907. return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
  1908. getLine(doc, change.to.line).text.length - change.to.ch);
  1909. var inside = pos.line - change.from.line;
  1910. return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
  1911. }
  1912. // Hint can be null|"end"|"start"|"around"|{anchor,head}
  1913. function computeSelAfterChange(doc, change, hint) {
  1914. if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
  1915. return {anchor: clipPostChange(doc, change, hint.anchor),
  1916. head: clipPostChange(doc, change, hint.head)};
  1917. if (hint == "start") return {anchor: change.from, head: change.from};
  1918. var end = changeEnd(change);
  1919. if (hint == "around") return {anchor: change.from, head: end};
  1920. if (hint == "end") return {anchor: end, head: end};
  1921. // hint is null, leave the selection alone as much as possible
  1922. var adjustPos = function(pos) {
  1923. if (posLess(pos, change.from)) return pos;
  1924. if (!posLess(change.to, pos)) return end;
  1925. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  1926. if (pos.line == change.to.line) ch += end.ch - change.to.ch;
  1927. return Pos(line, ch);
  1928. };
  1929. return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
  1930. }
  1931. function filterChange(doc, change) {
  1932. var obj = {
  1933. canceled: false,
  1934. from: change.from,
  1935. to: change.to,
  1936. text: change.text,
  1937. origin: change.origin,
  1938. update: function(from, to, text, origin) {
  1939. if (from) this.from = clipPos(doc, from);
  1940. if (to) this.to = clipPos(doc, to);
  1941. if (text) this.text = text;
  1942. if (origin !== undefined) this.origin = origin;
  1943. },
  1944. cancel: function() { this.canceled = true; }
  1945. };
  1946. signal(doc, "beforeChange", doc, obj);
  1947. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  1948. if (obj.canceled) return null;
  1949. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  1950. }
  1951. // Replace the range from from to to by the strings in replacement.
  1952. // change is a {from, to, text [, origin]} object
  1953. function makeChange(doc, change, selUpdate, ignoreReadOnly) {
  1954. if (doc.cm) {
  1955. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
  1956. if (doc.cm.state.suppressEdits) return;
  1957. }
  1958. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  1959. change = filterChange(doc, change);
  1960. if (!change) return;
  1961. }
  1962. // Possibly split or suppress the update based on the presence
  1963. // of read-only spans in its range.
  1964. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  1965. if (split) {
  1966. for (var i = split.length - 1; i >= 1; --i)
  1967. makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
  1968. if (split.length)
  1969. makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
  1970. } else {
  1971. makeChangeNoReadonly(doc, change, selUpdate);
  1972. }
  1973. }
  1974. function makeChangeNoReadonly(doc, change, selUpdate) {
  1975. var selAfter = computeSelAfterChange(doc, change, selUpdate);
  1976. addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  1977. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  1978. var rebased = [];
  1979. linkedDocs(doc, function(doc, sharedHist) {
  1980. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  1981. rebaseHist(doc.history, change);
  1982. rebased.push(doc.history);
  1983. }
  1984. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  1985. });
  1986. }
  1987. function makeChangeFromHistory(doc, type) {
  1988. if (doc.cm && doc.cm.state.suppressEdits) return;
  1989. var hist = doc.history;
  1990. var event = (type == "undo" ? hist.done : hist.undone).pop();
  1991. if (!event) return;
  1992. hist.dirtyCounter += type == "undo" ? -1 : 1;
  1993. var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
  1994. anchorAfter: event.anchorBefore, headAfter: event.headBefore};
  1995. (type == "undo" ? hist.undone : hist.done).push(anti);
  1996. for (var i = event.changes.length - 1; i >= 0; --i) {
  1997. var change = event.changes[i];
  1998. change.origin = type;
  1999. anti.changes.push(historyChangeFromChange(doc, change));
  2000. var after = i ? computeSelAfterChange(doc, change, null)
  2001. : {anchor: event.anchorBefore, head: event.headBefore};
  2002. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  2003. var rebased = [];
  2004. linkedDocs(doc, function(doc, sharedHist) {
  2005. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  2006. rebaseHist(doc.history, change);
  2007. rebased.push(doc.history);
  2008. }
  2009. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  2010. });
  2011. }
  2012. }
  2013. function shiftDoc(doc, distance) {
  2014. function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
  2015. doc.first += distance;
  2016. if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
  2017. doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
  2018. doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
  2019. }
  2020. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  2021. if (doc.cm && !doc.cm.curOp)
  2022. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  2023. if (change.to.line < doc.first) {
  2024. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  2025. return;
  2026. }
  2027. if (change.from.line > doc.lastLine()) return;
  2028. // Clip the change to the size of this doc
  2029. if (change.from.line < doc.first) {
  2030. var shift = change.text.length - 1 - (doc.first - change.from.line);
  2031. shiftDoc(doc, shift);
  2032. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  2033. text: [lst(change.text)], origin: change.origin};
  2034. }
  2035. var last = doc.lastLine();
  2036. if (change.to.line > last) {
  2037. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  2038. text: [change.text[0]], origin: change.origin};
  2039. }
  2040. change.removed = getBetween(doc, change.from, change.to);
  2041. if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
  2042. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
  2043. else updateDoc(doc, change, spans, selAfter);
  2044. }
  2045. function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
  2046. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  2047. var recomputeMaxLength = false, checkWidthStart = from.line;
  2048. if (!cm.options.lineWrapping) {
  2049. checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
  2050. doc.iter(checkWidthStart, to.line + 1, function(line) {
  2051. if (line == display.maxLine) {
  2052. recomputeMaxLength = true;
  2053. return true;
  2054. }
  2055. });
  2056. }
  2057. updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
  2058. if (!cm.options.lineWrapping) {
  2059. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  2060. var len = lineLength(doc, line);
  2061. if (len > display.maxLineLength) {
  2062. display.maxLine = line;
  2063. display.maxLineLength = len;
  2064. display.maxLineChanged = true;
  2065. recomputeMaxLength = false;
  2066. }
  2067. });
  2068. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  2069. }
  2070. // Adjust frontier, schedule worker
  2071. doc.frontier = Math.min(doc.frontier, from.line);
  2072. startWorker(cm, 400);
  2073. var lendiff = change.text.length - (to.line - from.line) - 1;
  2074. // Remember that these lines changed, for updating the display
  2075. regChange(cm, from.line, to.line + 1, lendiff);
  2076. if (hasHandler(cm, "change")) {
  2077. var changeObj = {from: from, to: to,
  2078. text: change.text,
  2079. removed: change.removed,
  2080. origin: change.origin};
  2081. if (cm.curOp.textChanged) {
  2082. for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
  2083. cur.next = changeObj;
  2084. } else cm.curOp.textChanged = changeObj;
  2085. }
  2086. }
  2087. function replaceRange(doc, code, from, to, origin) {
  2088. if (!to) to = from;
  2089. if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
  2090. if (typeof code == "string") code = splitLines(code);
  2091. makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
  2092. }
  2093. // POSITION OBJECT
  2094. function Pos(line, ch) {
  2095. if (!(this instanceof Pos)) return new Pos(line, ch);
  2096. this.line = line; this.ch = ch;
  2097. }
  2098. CodeMirror.Pos = Pos;
  2099. function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
  2100. function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
  2101. function copyPos(x) {return Pos(x.line, x.ch);}
  2102. // SELECTION
  2103. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  2104. function clipPos(doc, pos) {
  2105. if (pos.line < doc.first) return Pos(doc.first, 0);
  2106. var last = doc.first + doc.size - 1;
  2107. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  2108. return clipToLen(pos, getLine(doc, pos.line).text.length);
  2109. }
  2110. function clipToLen(pos, linelen) {
  2111. var ch = pos.ch;
  2112. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  2113. else if (ch < 0) return Pos(pos.line, 0);
  2114. else return pos;
  2115. }
  2116. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  2117. // If shift is held, this will move the selection anchor. Otherwise,
  2118. // it'll set the whole selection.
  2119. function extendSelection(doc, pos, other, bias) {
  2120. if (doc.sel.shift || doc.sel.extend) {
  2121. var anchor = doc.sel.anchor;
  2122. if (other) {
  2123. var posBefore = posLess(pos, anchor);
  2124. if (posBefore != posLess(other, anchor)) {
  2125. anchor = pos;
  2126. pos = other;
  2127. } else if (posBefore != posLess(pos, other)) {
  2128. pos = other;
  2129. }
  2130. }
  2131. setSelection(doc, anchor, pos, bias);
  2132. } else {
  2133. setSelection(doc, pos, other || pos, bias);
  2134. }
  2135. if (doc.cm) doc.cm.curOp.userSelChange = true;
  2136. }
  2137. function filterSelectionChange(doc, anchor, head) {
  2138. var obj = {anchor: anchor, head: head};
  2139. signal(doc, "beforeSelectionChange", doc, obj);
  2140. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  2141. obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
  2142. return obj;
  2143. }
  2144. // Update the selection. Last two args are only used by
  2145. // updateDoc, since they have to be expressed in the line
  2146. // numbers before the update.
  2147. function setSelection(doc, anchor, head, bias, checkAtomic) {
  2148. if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
  2149. var filtered = filterSelectionChange(doc, anchor, head);
  2150. head = filtered.head;
  2151. anchor = filtered.anchor;
  2152. }
  2153. var sel = doc.sel;
  2154. sel.goalColumn = null;
  2155. // Skip over atomic spans.
  2156. if (checkAtomic || !posEq(anchor, sel.anchor))
  2157. anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
  2158. if (checkAtomic || !posEq(head, sel.head))
  2159. head = skipAtomic(doc, head, bias, checkAtomic != "push");
  2160. if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
  2161. sel.anchor = anchor; sel.head = head;
  2162. var inv = posLess(head, anchor);
  2163. sel.from = inv ? head : anchor;
  2164. sel.to = inv ? anchor : head;
  2165. if (doc.cm)
  2166. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  2167. signalLater(doc, "cursorActivity", doc);
  2168. }
  2169. function reCheckSelection(cm) {
  2170. setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
  2171. }
  2172. function skipAtomic(doc, pos, bias, mayClear) {
  2173. var flipped = false, curPos = pos;
  2174. var dir = bias || 1;
  2175. doc.cantEdit = false;
  2176. search: for (;;) {
  2177. var line = getLine(doc, curPos.line);
  2178. if (line.markedSpans) {
  2179. for (var i = 0; i < line.markedSpans.length; ++i) {
  2180. var sp = line.markedSpans[i], m = sp.marker;
  2181. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
  2182. (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
  2183. if (mayClear) {
  2184. signal(m, "beforeCursorEnter");
  2185. if (m.explicitlyCleared) {
  2186. if (!line.markedSpans) break;
  2187. else {--i; continue;}
  2188. }
  2189. }
  2190. if (!m.atomic) continue;
  2191. var newPos = m.find()[dir < 0 ? "from" : "to"];
  2192. if (posEq(newPos, curPos)) {
  2193. newPos.ch += dir;
  2194. if (newPos.ch < 0) {
  2195. if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
  2196. else newPos = null;
  2197. } else if (newPos.ch > line.text.length) {
  2198. if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
  2199. else newPos = null;
  2200. }
  2201. if (!newPos) {
  2202. if (flipped) {
  2203. // Driven in a corner -- no valid cursor position found at all
  2204. // -- try again *with* clearing, if we didn't already
  2205. if (!mayClear) return skipAtomic(doc, pos, bias, true);
  2206. // Otherwise, turn off editing until further notice, and return the start of the doc
  2207. doc.cantEdit = true;
  2208. return Pos(doc.first, 0);
  2209. }
  2210. flipped = true; newPos = pos; dir = -dir;
  2211. }
  2212. }
  2213. curPos = newPos;
  2214. continue search;
  2215. }
  2216. }
  2217. }
  2218. return curPos;
  2219. }
  2220. }
  2221. // SCROLLING
  2222. function scrollCursorIntoView(cm) {
  2223. var coords = scrollPosIntoView(cm, cm.doc.sel.head);
  2224. if (!cm.state.focused) return;
  2225. var display = cm.display, box = getRect(display.sizer), doScroll = null, pTop = paddingTop(cm.display);
  2226. if (coords.top + pTop + box.top < 0) doScroll = true;
  2227. else if (coords.bottom + pTop + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  2228. if (doScroll != null && !phantom) {
  2229. var hidden = display.cursor.style.display == "none";
  2230. if (hidden) {
  2231. display.cursor.style.display = "";
  2232. display.cursor.style.left = coords.left + "px";
  2233. display.cursor.style.top = (coords.top - display.viewOffset) + "px";
  2234. }
  2235. display.cursor.scrollIntoView(doScroll);
  2236. if (hidden) display.cursor.style.display = "none";
  2237. }
  2238. }
  2239. function scrollPosIntoView(cm, pos, margin) {
  2240. if (margin == null) margin = 0;
  2241. for (;;) {
  2242. var changed = false, coords = cursorCoords(cm, pos);
  2243. var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
  2244. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  2245. if (scrollPos.scrollTop != null) {
  2246. setScrollTop(cm, scrollPos.scrollTop);
  2247. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  2248. }
  2249. if (scrollPos.scrollLeft != null) {
  2250. setScrollLeft(cm, scrollPos.scrollLeft);
  2251. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  2252. }
  2253. if (!changed) return coords;
  2254. }
  2255. }
  2256. function scrollIntoView(cm, x1, y1, x2, y2) {
  2257. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  2258. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  2259. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  2260. }
  2261. function calculateScrollPos(cm, x1, y1, x2, y2) {
  2262. var display = cm.display, pt = paddingTop(display);
  2263. y1 += pt; y2 += pt;
  2264. var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
  2265. var docBottom = cm.doc.height + paddingVert(display);
  2266. var atTop = y1 < pt + 10, atBottom = y2 + pt > docBottom - 10;
  2267. if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1);
  2268. else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen;
  2269. var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
  2270. x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
  2271. var gutterw = display.gutters.offsetWidth;
  2272. var atLeft = x1 < gutterw + 10;
  2273. if (x1 < screenleft + gutterw || atLeft) {
  2274. if (atLeft) x1 = 0;
  2275. result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
  2276. } else if (x2 > screenw + screenleft - 3) {
  2277. result.scrollLeft = x2 + 10 - screenw;
  2278. }
  2279. return result;
  2280. }
  2281. function updateScrollPos(cm, left, top) {
  2282. cm.curOp.updateScrollPos = {scrollLeft: left, scrollTop: top};
  2283. }
  2284. function addToScrollPos(cm, left, top) {
  2285. var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
  2286. var scroll = cm.display.scroller;
  2287. pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
  2288. pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
  2289. }
  2290. // API UTILITIES
  2291. function indentLine(cm, n, how, aggressive) {
  2292. var doc = cm.doc;
  2293. if (!how) how = "add";
  2294. if (how == "smart") {
  2295. if (!cm.doc.mode.indent) how = "prev";
  2296. else var state = getStateBefore(cm, n);
  2297. }
  2298. var tabSize = cm.options.tabSize;
  2299. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  2300. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  2301. if (how == "smart") {
  2302. indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  2303. if (indentation == Pass) {
  2304. if (!aggressive) return;
  2305. how = "prev";
  2306. }
  2307. }
  2308. if (how == "prev") {
  2309. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  2310. else indentation = 0;
  2311. } else if (how == "add") {
  2312. indentation = curSpace + cm.options.indentUnit;
  2313. } else if (how == "subtract") {
  2314. indentation = curSpace - cm.options.indentUnit;
  2315. }
  2316. indentation = Math.max(0, indentation);
  2317. var indentString = "", pos = 0;
  2318. if (cm.options.indentWithTabs)
  2319. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  2320. if (pos < indentation) indentString += spaceStr(indentation - pos);
  2321. if (indentString != curSpaceString)
  2322. replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  2323. line.stateAfter = null;
  2324. }
  2325. function changeLine(cm, handle, op) {
  2326. var no = handle, line = handle, doc = cm.doc;
  2327. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  2328. else no = lineNo(handle);
  2329. if (no == null) return null;
  2330. if (op(line, no)) regChange(cm, no, no + 1);
  2331. else return null;
  2332. return line;
  2333. }
  2334. function findPosH(doc, pos, dir, unit, visually) {
  2335. var line = pos.line, ch = pos.ch;
  2336. var lineObj = getLine(doc, line);
  2337. var possible = true;
  2338. function findNextLine() {
  2339. var l = line + dir;
  2340. if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
  2341. line = l;
  2342. return lineObj = getLine(doc, l);
  2343. }
  2344. function moveOnce(boundToLine) {
  2345. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  2346. if (next == null) {
  2347. if (!boundToLine && findNextLine()) {
  2348. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  2349. else ch = dir < 0 ? lineObj.text.length : 0;
  2350. } else return (possible = false);
  2351. } else ch = next;
  2352. return true;
  2353. }
  2354. if (unit == "char") moveOnce();
  2355. else if (unit == "column") moveOnce(true);
  2356. else if (unit == "word" || unit == "group") {
  2357. var sawType = null, group = unit == "group";
  2358. for (var first = true;; first = false) {
  2359. if (dir < 0 && !moveOnce(!first)) break;
  2360. var cur = lineObj.text.charAt(ch) || "\n";
  2361. var type = isWordChar(cur) ? "w"
  2362. : !group ? null
  2363. : /\s/.test(cur) ? null
  2364. : "p";
  2365. if (sawType && sawType != type) {
  2366. if (dir < 0) {dir = 1; moveOnce();}
  2367. break;
  2368. }
  2369. if (type) sawType = type;
  2370. if (dir > 0 && !moveOnce(!first)) break;
  2371. }
  2372. }
  2373. var result = skipAtomic(doc, Pos(line, ch), dir, true);
  2374. if (!possible) result.hitSide = true;
  2375. return result;
  2376. }
  2377. function findPosV(cm, pos, dir, unit) {
  2378. var doc = cm.doc, x = pos.left, y;
  2379. if (unit == "page") {
  2380. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  2381. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  2382. } else if (unit == "line") {
  2383. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  2384. }
  2385. for (;;) {
  2386. var target = coordsChar(cm, x, y);
  2387. if (!target.outside) break;
  2388. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  2389. y += dir * 5;
  2390. }
  2391. return target;
  2392. }
  2393. function findWordAt(line, pos) {
  2394. var start = pos.ch, end = pos.ch;
  2395. if (line) {
  2396. if (pos.after === false || end == line.length) --start; else ++end;
  2397. var startChar = line.charAt(start);
  2398. var check = isWordChar(startChar) ? isWordChar
  2399. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  2400. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  2401. while (start > 0 && check(line.charAt(start - 1))) --start;
  2402. while (end < line.length && check(line.charAt(end))) ++end;
  2403. }
  2404. return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
  2405. }
  2406. function selectLine(cm, line) {
  2407. extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
  2408. }
  2409. // PROTOTYPE
  2410. // The publicly visible API. Note that operation(null, f) means
  2411. // 'wrap f in an operation, performed on its `this` parameter'
  2412. CodeMirror.prototype = {
  2413. focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
  2414. setOption: function(option, value) {
  2415. var options = this.options, old = options[option];
  2416. if (options[option] == value && option != "mode") return;
  2417. options[option] = value;
  2418. if (optionHandlers.hasOwnProperty(option))
  2419. operation(this, optionHandlers[option])(this, value, old);
  2420. },
  2421. getOption: function(option) {return this.options[option];},
  2422. getDoc: function() {return this.doc;},
  2423. addKeyMap: function(map, bottom) {
  2424. this.state.keyMaps[bottom ? "push" : "unshift"](map);
  2425. },
  2426. removeKeyMap: function(map) {
  2427. var maps = this.state.keyMaps;
  2428. for (var i = 0; i < maps.length; ++i)
  2429. if ((typeof map == "string" ? maps[i].name : maps[i]) == map) {
  2430. maps.splice(i, 1);
  2431. return true;
  2432. }
  2433. },
  2434. addOverlay: operation(null, function(spec, options) {
  2435. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  2436. if (mode.startState) throw new Error("Overlays may not be stateful.");
  2437. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  2438. this.state.modeGen++;
  2439. regChange(this);
  2440. }),
  2441. removeOverlay: operation(null, function(spec) {
  2442. var overlays = this.state.overlays;
  2443. for (var i = 0; i < overlays.length; ++i) {
  2444. if (overlays[i].modeSpec == spec) {
  2445. overlays.splice(i, 1);
  2446. this.state.modeGen++;
  2447. regChange(this);
  2448. return;
  2449. }
  2450. }
  2451. }),
  2452. indentLine: operation(null, function(n, dir, aggressive) {
  2453. if (typeof dir != "string") {
  2454. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  2455. else dir = dir ? "add" : "subtract";
  2456. }
  2457. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  2458. }),
  2459. indentSelection: operation(null, function(how) {
  2460. var sel = this.doc.sel;
  2461. if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
  2462. var e = sel.to.line - (sel.to.ch ? 0 : 1);
  2463. for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
  2464. }),
  2465. // Fetch the parser token for a given character. Useful for hacks
  2466. // that want to inspect the mode state (say, for completion).
  2467. getTokenAt: function(pos) {
  2468. var doc = this.doc;
  2469. pos = clipPos(doc, pos);
  2470. var state = getStateBefore(this, pos.line), mode = this.doc.mode;
  2471. var line = getLine(doc, pos.line);
  2472. var stream = new StringStream(line.text, this.options.tabSize);
  2473. while (stream.pos < pos.ch && !stream.eol()) {
  2474. stream.start = stream.pos;
  2475. var style = mode.token(stream, state);
  2476. }
  2477. return {start: stream.start,
  2478. end: stream.pos,
  2479. string: stream.current(),
  2480. className: style || null, // Deprecated, use 'type' instead
  2481. type: style || null,
  2482. state: state};
  2483. },
  2484. getStateAfter: function(line) {
  2485. var doc = this.doc;
  2486. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  2487. return getStateBefore(this, line + 1);
  2488. },
  2489. cursorCoords: function(start, mode) {
  2490. var pos, sel = this.doc.sel;
  2491. if (start == null) pos = sel.head;
  2492. else if (typeof start == "object") pos = clipPos(this.doc, start);
  2493. else pos = start ? sel.from : sel.to;
  2494. return cursorCoords(this, pos, mode || "page");
  2495. },
  2496. charCoords: function(pos, mode) {
  2497. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  2498. },
  2499. coordsChar: function(coords, mode) {
  2500. coords = fromCoordSystem(this, coords, mode || "page");
  2501. return coordsChar(this, coords.left, coords.top);
  2502. },
  2503. defaultTextHeight: function() { return textHeight(this.display); },
  2504. defaultCharWidth: function() { return charWidth(this.display); },
  2505. setGutterMarker: operation(null, function(line, gutterID, value) {
  2506. return changeLine(this, line, function(line) {
  2507. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  2508. markers[gutterID] = value;
  2509. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  2510. return true;
  2511. });
  2512. }),
  2513. clearGutter: operation(null, function(gutterID) {
  2514. var cm = this, doc = cm.doc, i = doc.first;
  2515. doc.iter(function(line) {
  2516. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  2517. line.gutterMarkers[gutterID] = null;
  2518. regChange(cm, i, i + 1);
  2519. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  2520. }
  2521. ++i;
  2522. });
  2523. }),
  2524. addLineClass: operation(null, function(handle, where, cls) {
  2525. return changeLine(this, handle, function(line) {
  2526. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2527. if (!line[prop]) line[prop] = cls;
  2528. else if (new RegExp("\\b" + cls + "\\b").test(line[prop])) return false;
  2529. else line[prop] += " " + cls;
  2530. return true;
  2531. });
  2532. }),
  2533. removeLineClass: operation(null, function(handle, where, cls) {
  2534. return changeLine(this, handle, function(line) {
  2535. var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
  2536. var cur = line[prop];
  2537. if (!cur) return false;
  2538. else if (cls == null) line[prop] = null;
  2539. else {
  2540. var upd = cur.replace(new RegExp("^" + cls + "\\b\\s*|\\s*\\b" + cls + "\\b"), "");
  2541. if (upd == cur) return false;
  2542. line[prop] = upd || null;
  2543. }
  2544. return true;
  2545. });
  2546. }),
  2547. addLineWidget: operation(null, function(handle, node, options) {
  2548. return addLineWidget(this, handle, node, options);
  2549. }),
  2550. removeLineWidget: function(widget) { widget.clear(); },
  2551. lineInfo: function(line) {
  2552. if (typeof line == "number") {
  2553. if (!isLine(this.doc, line)) return null;
  2554. var n = line;
  2555. line = getLine(this.doc, line);
  2556. if (!line) return null;
  2557. } else {
  2558. var n = lineNo(line);
  2559. if (n == null) return null;
  2560. }
  2561. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  2562. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  2563. widgets: line.widgets};
  2564. },
  2565. getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
  2566. addWidget: function(pos, node, scroll, vert, horiz) {
  2567. var display = this.display;
  2568. pos = cursorCoords(this, clipPos(this.doc, pos));
  2569. var top = pos.bottom, left = pos.left;
  2570. node.style.position = "absolute";
  2571. display.sizer.appendChild(node);
  2572. if (vert == "over") {
  2573. top = pos.top;
  2574. } else if (vert == "above" || vert == "near") {
  2575. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  2576. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  2577. // Default to positioning above (if specified and possible); otherwise default to positioning below
  2578. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  2579. top = pos.top - node.offsetHeight;
  2580. else if (pos.bottom + node.offsetHeight <= vspace)
  2581. top = pos.bottom;
  2582. if (left + node.offsetWidth > hspace)
  2583. left = hspace - node.offsetWidth;
  2584. }
  2585. node.style.top = (top + paddingTop(display)) + "px";
  2586. node.style.left = node.style.right = "";
  2587. if (horiz == "right") {
  2588. left = display.sizer.clientWidth - node.offsetWidth;
  2589. node.style.right = "0px";
  2590. } else {
  2591. if (horiz == "left") left = 0;
  2592. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  2593. node.style.left = left + "px";
  2594. }
  2595. if (scroll)
  2596. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  2597. },
  2598. triggerOnKeyDown: operation(null, onKeyDown),
  2599. execCommand: function(cmd) {return commands[cmd](this);},
  2600. findPosH: function(from, amount, unit, visually) {
  2601. var dir = 1;
  2602. if (amount < 0) { dir = -1; amount = -amount; }
  2603. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  2604. cur = findPosH(this.doc, cur, dir, unit, visually);
  2605. if (cur.hitSide) break;
  2606. }
  2607. return cur;
  2608. },
  2609. moveH: operation(null, function(dir, unit) {
  2610. var sel = this.doc.sel, pos;
  2611. if (sel.shift || sel.extend || posEq(sel.from, sel.to))
  2612. pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
  2613. else
  2614. pos = dir < 0 ? sel.from : sel.to;
  2615. extendSelection(this.doc, pos, pos, dir);
  2616. }),
  2617. deleteH: operation(null, function(dir, unit) {
  2618. var sel = this.doc.sel;
  2619. if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
  2620. else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
  2621. this.curOp.userSelChange = true;
  2622. }),
  2623. findPosV: function(from, amount, unit, goalColumn) {
  2624. var dir = 1, x = goalColumn;
  2625. if (amount < 0) { dir = -1; amount = -amount; }
  2626. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  2627. var coords = cursorCoords(this, cur, "div");
  2628. if (x == null) x = coords.left;
  2629. else coords.left = x;
  2630. cur = findPosV(this, coords, dir, unit);
  2631. if (cur.hitSide) break;
  2632. }
  2633. return cur;
  2634. },
  2635. moveV: operation(null, function(dir, unit) {
  2636. var sel = this.doc.sel;
  2637. var pos = cursorCoords(this, sel.head, "div");
  2638. if (sel.goalColumn != null) pos.left = sel.goalColumn;
  2639. var target = findPosV(this, pos, dir, unit);
  2640. if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
  2641. extendSelection(this.doc, target, target, dir);
  2642. sel.goalColumn = pos.left;
  2643. }),
  2644. toggleOverwrite: function() {
  2645. if (this.state.overwrite = !this.state.overwrite)
  2646. this.display.cursor.className += " CodeMirror-overwrite";
  2647. else
  2648. this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
  2649. },
  2650. hasFocus: function() { return this.state.focused; },
  2651. scrollTo: operation(null, function(x, y) {
  2652. updateScrollPos(this, x, y);
  2653. }),
  2654. getScrollInfo: function() {
  2655. var scroller = this.display.scroller, co = scrollerCutOff;
  2656. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  2657. height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
  2658. clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
  2659. },
  2660. scrollIntoView: function(pos, margin) {
  2661. if (typeof pos == "number") pos = Pos(pos, 0);
  2662. if (!pos || pos.line != null) {
  2663. pos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
  2664. scrollPosIntoView(this, pos, margin);
  2665. } else {
  2666. scrollIntoView(this, pos.left, pos.top - margin, pos.right, pos.bottom + margin);
  2667. }
  2668. },
  2669. setSize: function(width, height) {
  2670. function interpret(val) {
  2671. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  2672. }
  2673. if (width != null) this.display.wrapper.style.width = interpret(width);
  2674. if (height != null) this.display.wrapper.style.height = interpret(height);
  2675. this.refresh();
  2676. },
  2677. on: function(type, f) {on(this, type, f);},
  2678. off: function(type, f) {off(this, type, f);},
  2679. operation: function(f){return runInOp(this, f);},
  2680. refresh: operation(null, function() {
  2681. clearCaches(this);
  2682. updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
  2683. regChange(this);
  2684. }),
  2685. swapDoc: operation(null, function(doc) {
  2686. var old = this.doc;
  2687. old.cm = null;
  2688. attachDoc(this, doc);
  2689. clearCaches(this);
  2690. updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
  2691. return old;
  2692. }),
  2693. getInputField: function(){return this.display.input;},
  2694. getWrapperElement: function(){return this.display.wrapper;},
  2695. getScrollerElement: function(){return this.display.scroller;},
  2696. getGutterElement: function(){return this.display.gutters;}
  2697. };
  2698. // OPTION DEFAULTS
  2699. var optionHandlers = CodeMirror.optionHandlers = {};
  2700. // The default configuration options.
  2701. var defaults = CodeMirror.defaults = {};
  2702. function option(name, deflt, handle, notOnInit) {
  2703. CodeMirror.defaults[name] = deflt;
  2704. if (handle) optionHandlers[name] =
  2705. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  2706. }
  2707. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  2708. // These two are, on init, called from the constructor because they
  2709. // have to be initialized before the editor can start at all.
  2710. option("value", "", function(cm, val) {
  2711. cm.setValue(val);
  2712. }, true);
  2713. option("mode", null, function(cm, val) {
  2714. cm.doc.modeOption = val;
  2715. loadMode(cm);
  2716. }, true);
  2717. option("indentUnit", 2, loadMode, true);
  2718. option("indentWithTabs", false);
  2719. option("smartIndent", true);
  2720. option("tabSize", 4, function(cm) {
  2721. loadMode(cm);
  2722. clearCaches(cm);
  2723. regChange(cm);
  2724. }, true);
  2725. option("electricChars", true);
  2726. option("rtlMoveVisually", !windows);
  2727. option("theme", "default", function(cm) {
  2728. themeChanged(cm);
  2729. guttersChanged(cm);
  2730. }, true);
  2731. option("keyMap", "default", keyMapChanged);
  2732. option("extraKeys", null);
  2733. option("onKeyEvent", null);
  2734. option("onDragEvent", null);
  2735. option("lineWrapping", false, wrappingChanged, true);
  2736. option("gutters", [], function(cm) {
  2737. setGuttersForLineNumbers(cm.options);
  2738. guttersChanged(cm);
  2739. }, true);
  2740. option("fixedGutter", true, function(cm, val) {
  2741. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  2742. cm.refresh();
  2743. }, true);
  2744. option("lineNumbers", false, function(cm) {
  2745. setGuttersForLineNumbers(cm.options);
  2746. guttersChanged(cm);
  2747. }, true);
  2748. option("firstLineNumber", 1, guttersChanged, true);
  2749. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  2750. option("showCursorWhenSelecting", false, updateSelection, true);
  2751. option("readOnly", false, function(cm, val) {
  2752. if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
  2753. else if (!val) resetInput(cm, true);
  2754. });
  2755. option("dragDrop", true);
  2756. option("cursorBlinkRate", 530);
  2757. option("cursorHeight", 1);
  2758. option("workTime", 100);
  2759. option("workDelay", 100);
  2760. option("flattenSpans", true);
  2761. option("pollInterval", 100);
  2762. option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
  2763. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  2764. option("tabindex", null, function(cm, val) {
  2765. cm.display.input.tabIndex = val || "";
  2766. });
  2767. option("autofocus", null);
  2768. // MODE DEFINITION AND QUERYING
  2769. // Known modes, by name and by MIME
  2770. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  2771. CodeMirror.defineMode = function(name, mode) {
  2772. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  2773. if (arguments.length > 2) {
  2774. mode.dependencies = [];
  2775. for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
  2776. }
  2777. modes[name] = mode;
  2778. };
  2779. CodeMirror.defineMIME = function(mime, spec) {
  2780. mimeModes[mime] = spec;
  2781. };
  2782. CodeMirror.resolveMode = function(spec) {
  2783. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
  2784. spec = mimeModes[spec];
  2785. else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec))
  2786. return CodeMirror.resolveMode("application/xml");
  2787. if (typeof spec == "string") return {name: spec};
  2788. else return spec || {name: "null"};
  2789. };
  2790. CodeMirror.getMode = function(options, spec) {
  2791. spec = CodeMirror.resolveMode(spec);
  2792. var mfactory = modes[spec.name];
  2793. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  2794. var modeObj = mfactory(options, spec);
  2795. if (modeExtensions.hasOwnProperty(spec.name)) {
  2796. var exts = modeExtensions[spec.name];
  2797. for (var prop in exts) {
  2798. if (!exts.hasOwnProperty(prop)) continue;
  2799. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  2800. modeObj[prop] = exts[prop];
  2801. }
  2802. }
  2803. modeObj.name = spec.name;
  2804. return modeObj;
  2805. };
  2806. CodeMirror.defineMode("null", function() {
  2807. return {token: function(stream) {stream.skipToEnd();}};
  2808. });
  2809. CodeMirror.defineMIME("text/plain", "null");
  2810. var modeExtensions = CodeMirror.modeExtensions = {};
  2811. CodeMirror.extendMode = function(mode, properties) {
  2812. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  2813. copyObj(properties, exts);
  2814. };
  2815. // EXTENSIONS
  2816. CodeMirror.defineExtension = function(name, func) {
  2817. CodeMirror.prototype[name] = func;
  2818. };
  2819. CodeMirror.defineOption = option;
  2820. var initHooks = [];
  2821. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  2822. // MODE STATE HANDLING
  2823. // Utility functions for working with state. Exported because modes
  2824. // sometimes need to do this.
  2825. function copyState(mode, state) {
  2826. if (state === true) return state;
  2827. if (mode.copyState) return mode.copyState(state);
  2828. var nstate = {};
  2829. for (var n in state) {
  2830. var val = state[n];
  2831. if (val instanceof Array) val = val.concat([]);
  2832. nstate[n] = val;
  2833. }
  2834. return nstate;
  2835. }
  2836. CodeMirror.copyState = copyState;
  2837. function startState(mode, a1, a2) {
  2838. return mode.startState ? mode.startState(a1, a2) : true;
  2839. }
  2840. CodeMirror.startState = startState;
  2841. CodeMirror.innerMode = function(mode, state) {
  2842. while (mode.innerMode) {
  2843. var info = mode.innerMode(state);
  2844. state = info.state;
  2845. mode = info.mode;
  2846. }
  2847. return info || {mode: mode, state: state};
  2848. };
  2849. // STANDARD COMMANDS
  2850. var commands = CodeMirror.commands = {
  2851. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
  2852. killLine: function(cm) {
  2853. var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
  2854. if (!sel && cm.getLine(from.line).length == from.ch)
  2855. cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
  2856. else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
  2857. },
  2858. deleteLine: function(cm) {
  2859. var l = cm.getCursor().line;
  2860. cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
  2861. },
  2862. undo: function(cm) {cm.undo();},
  2863. redo: function(cm) {cm.redo();},
  2864. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  2865. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  2866. goLineStart: function(cm) {
  2867. cm.extendSelection(lineStart(cm, cm.getCursor().line));
  2868. },
  2869. goLineStartSmart: function(cm) {
  2870. var cur = cm.getCursor(), start = lineStart(cm, cur.line);
  2871. var line = cm.getLineHandle(start.line);
  2872. var order = getOrder(line);
  2873. if (!order || order[0].level == 0) {
  2874. var firstNonWS = Math.max(0, line.text.search(/\S/));
  2875. var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
  2876. cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
  2877. } else cm.extendSelection(start);
  2878. },
  2879. goLineEnd: function(cm) {
  2880. cm.extendSelection(lineEnd(cm, cm.getCursor().line));
  2881. },
  2882. goLineRight: function(cm) {
  2883. var top = cm.charCoords(cm.getCursor(), "div").top + 5;
  2884. cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
  2885. },
  2886. goLineLeft: function(cm) {
  2887. var top = cm.charCoords(cm.getCursor(), "div").top + 5;
  2888. cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
  2889. },
  2890. goLineUp: function(cm) {cm.moveV(-1, "line");},
  2891. goLineDown: function(cm) {cm.moveV(1, "line");},
  2892. goPageUp: function(cm) {cm.moveV(-1, "page");},
  2893. goPageDown: function(cm) {cm.moveV(1, "page");},
  2894. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  2895. goCharRight: function(cm) {cm.moveH(1, "char");},
  2896. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  2897. goColumnRight: function(cm) {cm.moveH(1, "column");},
  2898. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  2899. goGroupRight: function(cm) {cm.moveH(1, "group");},
  2900. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  2901. goWordRight: function(cm) {cm.moveH(1, "word");},
  2902. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  2903. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  2904. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  2905. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  2906. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  2907. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  2908. indentAuto: function(cm) {cm.indentSelection("smart");},
  2909. indentMore: function(cm) {cm.indentSelection("add");},
  2910. indentLess: function(cm) {cm.indentSelection("subtract");},
  2911. insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
  2912. defaultTab: function(cm) {
  2913. if (cm.somethingSelected()) cm.indentSelection("add");
  2914. else cm.replaceSelection("\t", "end", "+input");
  2915. },
  2916. transposeChars: function(cm) {
  2917. var cur = cm.getCursor(), line = cm.getLine(cur.line);
  2918. if (cur.ch > 0 && cur.ch < line.length - 1)
  2919. cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
  2920. Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
  2921. },
  2922. newlineAndIndent: function(cm) {
  2923. operation(cm, function() {
  2924. cm.replaceSelection("\n", "end", "+input");
  2925. cm.indentLine(cm.getCursor().line, null, true);
  2926. })();
  2927. },
  2928. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  2929. };
  2930. // STANDARD KEYMAPS
  2931. var keyMap = CodeMirror.keyMap = {};
  2932. keyMap.basic = {
  2933. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  2934. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  2935. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  2936. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
  2937. };
  2938. // Note that the save and find-related commands aren't defined by
  2939. // default. Unknown commands are simply ignored.
  2940. keyMap.pcDefault = {
  2941. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  2942. "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
  2943. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  2944. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  2945. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  2946. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  2947. fallthrough: "basic"
  2948. };
  2949. keyMap.macDefault = {
  2950. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  2951. "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  2952. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
  2953. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  2954. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  2955. "Cmd-[": "indentLess", "Cmd-]": "indentMore",
  2956. fallthrough: ["basic", "emacsy"]
  2957. };
  2958. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  2959. keyMap.emacsy = {
  2960. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  2961. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  2962. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  2963. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
  2964. };
  2965. // KEYMAP DISPATCH
  2966. function getKeyMap(val) {
  2967. if (typeof val == "string") return keyMap[val];
  2968. else return val;
  2969. }
  2970. function lookupKey(name, maps, handle) {
  2971. function lookup(map) {
  2972. map = getKeyMap(map);
  2973. var found = map[name];
  2974. if (found === false) return "stop";
  2975. if (found != null && handle(found)) return true;
  2976. if (map.nofallthrough) return "stop";
  2977. var fallthrough = map.fallthrough;
  2978. if (fallthrough == null) return false;
  2979. if (Object.prototype.toString.call(fallthrough) != "[object Array]")
  2980. return lookup(fallthrough);
  2981. for (var i = 0, e = fallthrough.length; i < e; ++i) {
  2982. var done = lookup(fallthrough[i]);
  2983. if (done) return done;
  2984. }
  2985. return false;
  2986. }
  2987. for (var i = 0; i < maps.length; ++i) {
  2988. var done = lookup(maps[i]);
  2989. if (done) return done;
  2990. }
  2991. }
  2992. function isModifierKey(event) {
  2993. var name = keyNames[event.keyCode];
  2994. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  2995. }
  2996. function keyName(event, noShift) {
  2997. var name = keyNames[event.keyCode];
  2998. if (name == null || event.altGraphKey) return false;
  2999. if (event.altKey) name = "Alt-" + name;
  3000. if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
  3001. if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
  3002. if (!noShift && event.shiftKey) name = "Shift-" + name;
  3003. return name;
  3004. }
  3005. CodeMirror.lookupKey = lookupKey;
  3006. CodeMirror.isModifierKey = isModifierKey;
  3007. CodeMirror.keyName = keyName;
  3008. // FROMTEXTAREA
  3009. CodeMirror.fromTextArea = function(textarea, options) {
  3010. if (!options) options = {};
  3011. options.value = textarea.value;
  3012. if (!options.tabindex && textarea.tabindex)
  3013. options.tabindex = textarea.tabindex;
  3014. if (!options.placeholder && textarea.placeholder)
  3015. options.placeholder = textarea.placeholder;
  3016. // Set autofocus to true if this textarea is focused, or if it has
  3017. // autofocus and no other element is focused.
  3018. if (options.autofocus == null) {
  3019. var hasFocus = document.body;
  3020. // doc.activeElement occasionally throws on IE
  3021. try { hasFocus = document.activeElement; } catch(e) {}
  3022. options.autofocus = hasFocus == textarea ||
  3023. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  3024. }
  3025. function save() {textarea.value = cm.getValue();}
  3026. if (textarea.form) {
  3027. on(textarea.form, "submit", save);
  3028. // Deplorable hack to make the submit method do the right thing.
  3029. if (!options.leaveSubmitMethodAlone) {
  3030. var form = textarea.form, realSubmit = form.submit;
  3031. try {
  3032. var wrappedSubmit = form.submit = function() {
  3033. save();
  3034. form.submit = realSubmit;
  3035. form.submit();
  3036. form.submit = wrappedSubmit;
  3037. };
  3038. } catch(e) {}
  3039. }
  3040. }
  3041. textarea.style.display = "none";
  3042. var cm = CodeMirror(function(node) {
  3043. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  3044. }, options);
  3045. cm.save = save;
  3046. cm.getTextArea = function() { return textarea; };
  3047. cm.toTextArea = function() {
  3048. save();
  3049. textarea.parentNode.removeChild(cm.getWrapperElement());
  3050. textarea.style.display = "";
  3051. if (textarea.form) {
  3052. off(textarea.form, "submit", save);
  3053. if (typeof textarea.form.submit == "function")
  3054. textarea.form.submit = realSubmit;
  3055. }
  3056. };
  3057. return cm;
  3058. };
  3059. // STRING STREAM
  3060. // Fed to the mode parsers, provides helper functions to make
  3061. // parsers more succinct.
  3062. // The character stream used by a mode's parser.
  3063. function StringStream(string, tabSize) {
  3064. this.pos = this.start = 0;
  3065. this.string = string;
  3066. this.tabSize = tabSize || 8;
  3067. this.lastColumnPos = this.lastColumnValue = 0;
  3068. }
  3069. StringStream.prototype = {
  3070. eol: function() {return this.pos >= this.string.length;},
  3071. sol: function() {return this.pos == 0;},
  3072. peek: function() {return this.string.charAt(this.pos) || undefined;},
  3073. next: function() {
  3074. if (this.pos < this.string.length)
  3075. return this.string.charAt(this.pos++);
  3076. },
  3077. eat: function(match) {
  3078. var ch = this.string.charAt(this.pos);
  3079. if (typeof match == "string") var ok = ch == match;
  3080. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  3081. if (ok) {++this.pos; return ch;}
  3082. },
  3083. eatWhile: function(match) {
  3084. var start = this.pos;
  3085. while (this.eat(match)){}
  3086. return this.pos > start;
  3087. },
  3088. eatSpace: function() {
  3089. var start = this.pos;
  3090. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  3091. return this.pos > start;
  3092. },
  3093. skipToEnd: function() {this.pos = this.string.length;},
  3094. skipTo: function(ch) {
  3095. var found = this.string.indexOf(ch, this.pos);
  3096. if (found > -1) {this.pos = found; return true;}
  3097. },
  3098. backUp: function(n) {this.pos -= n;},
  3099. column: function() {
  3100. if (this.lastColumnPos < this.start) {
  3101. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  3102. this.lastColumnPos = this.start;
  3103. }
  3104. return this.lastColumnValue;
  3105. },
  3106. indentation: function() {return countColumn(this.string, null, this.tabSize);},
  3107. match: function(pattern, consume, caseInsensitive) {
  3108. if (typeof pattern == "string") {
  3109. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  3110. var substr = this.string.substr(this.pos, pattern.length);
  3111. if (cased(substr) == cased(pattern)) {
  3112. if (consume !== false) this.pos += pattern.length;
  3113. return true;
  3114. }
  3115. } else {
  3116. var match = this.string.slice(this.pos).match(pattern);
  3117. if (match && match.index > 0) return null;
  3118. if (match && consume !== false) this.pos += match[0].length;
  3119. return match;
  3120. }
  3121. },
  3122. current: function(){return this.string.slice(this.start, this.pos);}
  3123. };
  3124. CodeMirror.StringStream = StringStream;
  3125. // TEXTMARKERS
  3126. function TextMarker(doc, type) {
  3127. this.lines = [];
  3128. this.type = type;
  3129. this.doc = doc;
  3130. }
  3131. CodeMirror.TextMarker = TextMarker;
  3132. TextMarker.prototype.clear = function() {
  3133. if (this.explicitlyCleared) return;
  3134. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  3135. if (withOp) startOperation(cm);
  3136. var min = null, max = null;
  3137. for (var i = 0; i < this.lines.length; ++i) {
  3138. var line = this.lines[i];
  3139. var span = getMarkedSpanFor(line.markedSpans, this);
  3140. if (span.to != null) max = lineNo(line);
  3141. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  3142. if (span.from != null)
  3143. min = lineNo(line);
  3144. else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
  3145. updateLineHeight(line, textHeight(cm.display));
  3146. }
  3147. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  3148. var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
  3149. if (len > cm.display.maxLineLength) {
  3150. cm.display.maxLine = visual;
  3151. cm.display.maxLineLength = len;
  3152. cm.display.maxLineChanged = true;
  3153. }
  3154. }
  3155. if (min != null && cm) regChange(cm, min, max + 1);
  3156. this.lines.length = 0;
  3157. this.explicitlyCleared = true;
  3158. if (this.collapsed && this.doc.cantEdit) {
  3159. this.doc.cantEdit = false;
  3160. if (cm) reCheckSelection(cm);
  3161. }
  3162. if (withOp) endOperation(cm);
  3163. signalLater(this, "clear");
  3164. };
  3165. TextMarker.prototype.find = function() {
  3166. var from, to;
  3167. for (var i = 0; i < this.lines.length; ++i) {
  3168. var line = this.lines[i];
  3169. var span = getMarkedSpanFor(line.markedSpans, this);
  3170. if (span.from != null || span.to != null) {
  3171. var found = lineNo(line);
  3172. if (span.from != null) from = Pos(found, span.from);
  3173. if (span.to != null) to = Pos(found, span.to);
  3174. }
  3175. }
  3176. if (this.type == "bookmark") return from;
  3177. return from && {from: from, to: to};
  3178. };
  3179. TextMarker.prototype.getOptions = function(copyWidget) {
  3180. var repl = this.replacedWith;
  3181. return {className: this.className,
  3182. inclusiveLeft: this.inclusiveLeft, inclusiveRight: this.inclusiveRight,
  3183. atomic: this.atomic,
  3184. collapsed: this.collapsed,
  3185. replacedWith: copyWidget ? repl && repl.cloneNode(true) : repl,
  3186. readOnly: this.readOnly,
  3187. startStyle: this.startStyle, endStyle: this.endStyle};
  3188. };
  3189. TextMarker.prototype.attachLine = function(line) {
  3190. if (!this.lines.length && this.doc.cm) {
  3191. var op = this.doc.cm.curOp;
  3192. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  3193. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  3194. }
  3195. this.lines.push(line);
  3196. };
  3197. TextMarker.prototype.detachLine = function(line) {
  3198. this.lines.splice(indexOf(this.lines, line), 1);
  3199. if (!this.lines.length && this.doc.cm) {
  3200. var op = this.doc.cm.curOp;
  3201. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  3202. }
  3203. };
  3204. function markText(doc, from, to, options, type) {
  3205. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  3206. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  3207. var marker = new TextMarker(doc, type);
  3208. if (type == "range" && !posLess(from, to)) return marker;
  3209. if (options) copyObj(options, marker);
  3210. if (marker.replacedWith) {
  3211. marker.collapsed = true;
  3212. marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
  3213. }
  3214. if (marker.collapsed) sawCollapsedSpans = true;
  3215. var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
  3216. doc.iter(curLine, to.line + 1, function(line) {
  3217. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
  3218. updateMaxLine = true;
  3219. var span = {from: null, to: null, marker: marker};
  3220. size += line.text.length;
  3221. if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
  3222. if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
  3223. if (marker.collapsed) {
  3224. if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
  3225. if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
  3226. else updateLineHeight(line, 0);
  3227. }
  3228. addMarkedSpan(line, span);
  3229. ++curLine;
  3230. });
  3231. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  3232. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  3233. });
  3234. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  3235. if (marker.readOnly) {
  3236. sawReadOnlySpans = true;
  3237. if (doc.history.done.length || doc.history.undone.length)
  3238. doc.clearHistory();
  3239. }
  3240. if (marker.collapsed) {
  3241. if (collapsedAtStart != collapsedAtEnd)
  3242. throw new Error("Inserting collapsed marker overlapping an existing one");
  3243. marker.size = size;
  3244. marker.atomic = true;
  3245. }
  3246. if (cm) {
  3247. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  3248. if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed)
  3249. regChange(cm, from.line, to.line + 1);
  3250. if (marker.atomic) reCheckSelection(cm);
  3251. }
  3252. return marker;
  3253. }
  3254. // SHARED TEXTMARKERS
  3255. function SharedTextMarker(markers, primary) {
  3256. this.markers = markers;
  3257. this.primary = primary;
  3258. for (var i = 0, me = this; i < markers.length; ++i) {
  3259. markers[i].parent = this;
  3260. on(markers[i], "clear", function(){me.clear();});
  3261. }
  3262. }
  3263. CodeMirror.SharedTextMarker = SharedTextMarker;
  3264. SharedTextMarker.prototype.clear = function() {
  3265. if (this.explicitlyCleared) return;
  3266. this.explicitlyCleared = true;
  3267. for (var i = 0; i < this.markers.length; ++i)
  3268. this.markers[i].clear();
  3269. signalLater(this, "clear");
  3270. };
  3271. SharedTextMarker.prototype.find = function() {
  3272. return this.primary.find();
  3273. };
  3274. SharedTextMarker.prototype.getOptions = function(copyWidget) {
  3275. var inner = this.primary.getOptions(copyWidget);
  3276. inner.shared = true;
  3277. return inner;
  3278. };
  3279. function markTextShared(doc, from, to, options, type) {
  3280. options = copyObj(options);
  3281. options.shared = false;
  3282. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  3283. var widget = options.replacedWith;
  3284. linkedDocs(doc, function(doc) {
  3285. if (widget) options.replacedWith = widget.cloneNode(true);
  3286. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  3287. for (var i = 0; i < doc.linked.length; ++i)
  3288. if (doc.linked[i].isParent) return;
  3289. primary = lst(markers);
  3290. });
  3291. return new SharedTextMarker(markers, primary);
  3292. }
  3293. // TEXTMARKER SPANS
  3294. function getMarkedSpanFor(spans, marker) {
  3295. if (spans) for (var i = 0; i < spans.length; ++i) {
  3296. var span = spans[i];
  3297. if (span.marker == marker) return span;
  3298. }
  3299. }
  3300. function removeMarkedSpan(spans, span) {
  3301. for (var r, i = 0; i < spans.length; ++i)
  3302. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  3303. return r;
  3304. }
  3305. function addMarkedSpan(line, span) {
  3306. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  3307. span.marker.attachLine(line);
  3308. }
  3309. function markedSpansBefore(old, startCh, isInsert) {
  3310. if (old) for (var i = 0, nw; i < old.length; ++i) {
  3311. var span = old[i], marker = span.marker;
  3312. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  3313. if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
  3314. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  3315. (nw || (nw = [])).push({from: span.from,
  3316. to: endsAfter ? null : span.to,
  3317. marker: marker});
  3318. }
  3319. }
  3320. return nw;
  3321. }
  3322. function markedSpansAfter(old, endCh, isInsert) {
  3323. if (old) for (var i = 0, nw; i < old.length; ++i) {
  3324. var span = old[i], marker = span.marker;
  3325. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  3326. if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
  3327. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  3328. (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
  3329. to: span.to == null ? null : span.to - endCh,
  3330. marker: marker});
  3331. }
  3332. }
  3333. return nw;
  3334. }
  3335. function stretchSpansOverChange(doc, change) {
  3336. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  3337. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  3338. if (!oldFirst && !oldLast) return null;
  3339. var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
  3340. // Get the spans that 'stick out' on both sides
  3341. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  3342. var last = markedSpansAfter(oldLast, endCh, isInsert);
  3343. // Next, merge those two ends
  3344. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  3345. if (first) {
  3346. // Fix up .to properties of first
  3347. for (var i = 0; i < first.length; ++i) {
  3348. var span = first[i];
  3349. if (span.to == null) {
  3350. var found = getMarkedSpanFor(last, span.marker);
  3351. if (!found) span.to = startCh;
  3352. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  3353. }
  3354. }
  3355. }
  3356. if (last) {
  3357. // Fix up .from in last (or move them into first in case of sameLine)
  3358. for (var i = 0; i < last.length; ++i) {
  3359. var span = last[i];
  3360. if (span.to != null) span.to += offset;
  3361. if (span.from == null) {
  3362. var found = getMarkedSpanFor(first, span.marker);
  3363. if (!found) {
  3364. span.from = offset;
  3365. if (sameLine) (first || (first = [])).push(span);
  3366. }
  3367. } else {
  3368. span.from += offset;
  3369. if (sameLine) (first || (first = [])).push(span);
  3370. }
  3371. }
  3372. }
  3373. var newMarkers = [first];
  3374. if (!sameLine) {
  3375. // Fill gap with whole-line-spans
  3376. var gap = change.text.length - 2, gapMarkers;
  3377. if (gap > 0 && first)
  3378. for (var i = 0; i < first.length; ++i)
  3379. if (first[i].to == null)
  3380. (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
  3381. for (var i = 0; i < gap; ++i)
  3382. newMarkers.push(gapMarkers);
  3383. newMarkers.push(last);
  3384. }
  3385. return newMarkers;
  3386. }
  3387. function mergeOldSpans(doc, change) {
  3388. var old = getOldSpans(doc, change);
  3389. var stretched = stretchSpansOverChange(doc, change);
  3390. if (!old) return stretched;
  3391. if (!stretched) return old;
  3392. for (var i = 0; i < old.length; ++i) {
  3393. var oldCur = old[i], stretchCur = stretched[i];
  3394. if (oldCur && stretchCur) {
  3395. spans: for (var j = 0; j < stretchCur.length; ++j) {
  3396. var span = stretchCur[j];
  3397. for (var k = 0; k < oldCur.length; ++k)
  3398. if (oldCur[k].marker == span.marker) continue spans;
  3399. oldCur.push(span);
  3400. }
  3401. } else if (stretchCur) {
  3402. old[i] = stretchCur;
  3403. }
  3404. }
  3405. return old;
  3406. }
  3407. function removeReadOnlyRanges(doc, from, to) {
  3408. var markers = null;
  3409. doc.iter(from.line, to.line + 1, function(line) {
  3410. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3411. var mark = line.markedSpans[i].marker;
  3412. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  3413. (markers || (markers = [])).push(mark);
  3414. }
  3415. });
  3416. if (!markers) return null;
  3417. var parts = [{from: from, to: to}];
  3418. for (var i = 0; i < markers.length; ++i) {
  3419. var mk = markers[i], m = mk.find();
  3420. for (var j = 0; j < parts.length; ++j) {
  3421. var p = parts[j];
  3422. if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
  3423. var newParts = [j, 1];
  3424. if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
  3425. newParts.push({from: p.from, to: m.from});
  3426. if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
  3427. newParts.push({from: m.to, to: p.to});
  3428. parts.splice.apply(parts, newParts);
  3429. j += newParts.length - 1;
  3430. }
  3431. }
  3432. return parts;
  3433. }
  3434. function collapsedSpanAt(line, ch) {
  3435. var sps = sawCollapsedSpans && line.markedSpans, found;
  3436. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3437. sp = sps[i];
  3438. if (!sp.marker.collapsed) continue;
  3439. if ((sp.from == null || sp.from < ch) &&
  3440. (sp.to == null || sp.to > ch) &&
  3441. (!found || found.width < sp.marker.width))
  3442. found = sp.marker;
  3443. }
  3444. return found;
  3445. }
  3446. function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
  3447. function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
  3448. function visualLine(doc, line) {
  3449. var merged;
  3450. while (merged = collapsedSpanAtStart(line))
  3451. line = getLine(doc, merged.find().from.line);
  3452. return line;
  3453. }
  3454. function lineIsHidden(doc, line) {
  3455. var sps = sawCollapsedSpans && line.markedSpans;
  3456. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  3457. sp = sps[i];
  3458. if (!sp.marker.collapsed) continue;
  3459. if (sp.from == null) return true;
  3460. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  3461. return true;
  3462. }
  3463. }
  3464. function lineIsHiddenInner(doc, line, span) {
  3465. if (span.to == null) {
  3466. var end = span.marker.find().to, endLine = getLine(doc, end.line);
  3467. return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
  3468. }
  3469. if (span.marker.inclusiveRight && span.to == line.text.length)
  3470. return true;
  3471. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  3472. sp = line.markedSpans[i];
  3473. if (sp.marker.collapsed && sp.from == span.to &&
  3474. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  3475. lineIsHiddenInner(doc, line, sp)) return true;
  3476. }
  3477. }
  3478. function detachMarkedSpans(line) {
  3479. var spans = line.markedSpans;
  3480. if (!spans) return;
  3481. for (var i = 0; i < spans.length; ++i)
  3482. spans[i].marker.detachLine(line);
  3483. line.markedSpans = null;
  3484. }
  3485. function attachMarkedSpans(line, spans) {
  3486. if (!spans) return;
  3487. for (var i = 0; i < spans.length; ++i)
  3488. spans[i].marker.attachLine(line);
  3489. line.markedSpans = spans;
  3490. }
  3491. // LINE WIDGETS
  3492. var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
  3493. for (var opt in options) if (options.hasOwnProperty(opt))
  3494. this[opt] = options[opt];
  3495. this.cm = cm;
  3496. this.node = node;
  3497. };
  3498. function widgetOperation(f) {
  3499. return function() {
  3500. var withOp = !this.cm.curOp;
  3501. if (withOp) startOperation(this.cm);
  3502. try {var result = f.apply(this, arguments);}
  3503. finally {if (withOp) endOperation(this.cm);}
  3504. return result;
  3505. };
  3506. }
  3507. LineWidget.prototype.clear = widgetOperation(function() {
  3508. var ws = this.line.widgets, no = lineNo(this.line);
  3509. if (no == null || !ws) return;
  3510. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  3511. if (!ws.length) this.line.widgets = null;
  3512. updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
  3513. regChange(this.cm, no, no + 1);
  3514. });
  3515. LineWidget.prototype.changed = widgetOperation(function() {
  3516. var oldH = this.height;
  3517. this.height = null;
  3518. var diff = widgetHeight(this) - oldH;
  3519. if (!diff) return;
  3520. updateLineHeight(this.line, this.line.height + diff);
  3521. var no = lineNo(this.line);
  3522. regChange(this.cm, no, no + 1);
  3523. });
  3524. function widgetHeight(widget) {
  3525. if (widget.height != null) return widget.height;
  3526. if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
  3527. removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
  3528. return widget.height = widget.node.offsetHeight;
  3529. }
  3530. function addLineWidget(cm, handle, node, options) {
  3531. var widget = new LineWidget(cm, node, options);
  3532. if (widget.noHScroll) cm.display.alignWidgets = true;
  3533. changeLine(cm, handle, function(line) {
  3534. (line.widgets || (line.widgets = [])).push(widget);
  3535. widget.line = line;
  3536. if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
  3537. var aboveVisible = heightAtLine(cm, line) < cm.display.scroller.scrollTop;
  3538. updateLineHeight(line, line.height + widgetHeight(widget));
  3539. if (aboveVisible) addToScrollPos(cm, 0, widget.height);
  3540. }
  3541. return true;
  3542. });
  3543. return widget;
  3544. }
  3545. // LINE DATA STRUCTURE
  3546. // Line objects. These hold state related to a line, including
  3547. // highlighting info (the styles array).
  3548. function makeLine(text, markedSpans, estimateHeight) {
  3549. var line = {text: text};
  3550. attachMarkedSpans(line, markedSpans);
  3551. line.height = estimateHeight ? estimateHeight(line) : 1;
  3552. return line;
  3553. }
  3554. function updateLine(line, text, markedSpans, estimateHeight) {
  3555. line.text = text;
  3556. if (line.stateAfter) line.stateAfter = null;
  3557. if (line.styles) line.styles = null;
  3558. if (line.order != null) line.order = null;
  3559. detachMarkedSpans(line);
  3560. attachMarkedSpans(line, markedSpans);
  3561. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  3562. if (estHeight != line.height) updateLineHeight(line, estHeight);
  3563. }
  3564. function cleanUpLine(line) {
  3565. line.parent = null;
  3566. detachMarkedSpans(line);
  3567. }
  3568. // Run the given mode's parser over a line, update the styles
  3569. // array, which contains alternating fragments of text and CSS
  3570. // classes.
  3571. function runMode(cm, text, mode, state, f) {
  3572. var flattenSpans = mode.flattenSpans;
  3573. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  3574. var curText = "", curStyle = null;
  3575. var stream = new StringStream(text, cm.options.tabSize);
  3576. if (text == "" && mode.blankLine) mode.blankLine(state);
  3577. while (!stream.eol()) {
  3578. var style = mode.token(stream, state);
  3579. if (stream.pos > 5000) {
  3580. flattenSpans = false;
  3581. // Webkit seems to refuse to render text nodes longer than 57444 characters
  3582. stream.pos = Math.min(text.length, stream.start + 50000);
  3583. style = null;
  3584. }
  3585. var substr = stream.current();
  3586. stream.start = stream.pos;
  3587. if (!flattenSpans || curStyle != style) {
  3588. if (curText) f(curText, curStyle);
  3589. curText = substr; curStyle = style;
  3590. } else curText = curText + substr;
  3591. }
  3592. if (curText) f(curText, curStyle);
  3593. }
  3594. function highlightLine(cm, line, state) {
  3595. // A styles array always starts with a number identifying the
  3596. // mode/overlays that it is based on (for easy invalidation).
  3597. var st = [cm.state.modeGen];
  3598. // Compute the base array of styles
  3599. runMode(cm, line.text, cm.doc.mode, state, function(txt, style) {st.push(txt, style);});
  3600. // Run overlays, adjust style array.
  3601. for (var o = 0; o < cm.state.overlays.length; ++o) {
  3602. var overlay = cm.state.overlays[o], i = 1;
  3603. runMode(cm, line.text, overlay.mode, true, function(txt, style) {
  3604. var start = i, len = txt.length;
  3605. // Ensure there's a token end at the current position, and that i points at it
  3606. while (len) {
  3607. var cur = st[i], len_ = cur.length;
  3608. if (len_ <= len) {
  3609. len -= len_;
  3610. } else {
  3611. st.splice(i, 1, cur.slice(0, len), st[i+1], cur.slice(len));
  3612. len = 0;
  3613. }
  3614. i += 2;
  3615. }
  3616. if (!style) return;
  3617. if (overlay.opaque) {
  3618. st.splice(start, i - start, txt, style);
  3619. i = start + 2;
  3620. } else {
  3621. for (; start < i; start += 2) {
  3622. var cur = st[start+1];
  3623. st[start+1] = cur ? cur + " " + style : style;
  3624. }
  3625. }
  3626. });
  3627. }
  3628. return st;
  3629. }
  3630. function getLineStyles(cm, line) {
  3631. if (!line.styles || line.styles[0] != cm.state.modeGen)
  3632. line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
  3633. return line.styles;
  3634. }
  3635. // Lightweight form of highlight -- proceed over this line and
  3636. // update state, but don't save a style array.
  3637. function processLine(cm, line, state) {
  3638. var mode = cm.doc.mode;
  3639. var stream = new StringStream(line.text, cm.options.tabSize);
  3640. if (line.text == "" && mode.blankLine) mode.blankLine(state);
  3641. while (!stream.eol() && stream.pos <= 5000) {
  3642. mode.token(stream, state);
  3643. stream.start = stream.pos;
  3644. }
  3645. }
  3646. var styleToClassCache = {};
  3647. function styleToClass(style) {
  3648. if (!style) return null;
  3649. return styleToClassCache[style] ||
  3650. (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
  3651. }
  3652. function lineContent(cm, realLine, measure) {
  3653. var merged, line = realLine, lineBefore, sawBefore, simple = true;
  3654. while (merged = collapsedSpanAtStart(line)) {
  3655. simple = false;
  3656. line = getLine(cm.doc, merged.find().from.line);
  3657. if (!lineBefore) lineBefore = line;
  3658. }
  3659. var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure,
  3660. measure: null, addedOne: false, cm: cm};
  3661. if (line.textClass) builder.pre.className = line.textClass;
  3662. do {
  3663. builder.measure = line == realLine && measure;
  3664. builder.pos = 0;
  3665. builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
  3666. if ((ie || webkit) && cm.getOption("lineWrapping"))
  3667. builder.addToken = buildTokenSplitSpaces(builder.addToken);
  3668. if (measure && sawBefore && line != realLine && !builder.addedOne) {
  3669. measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
  3670. builder.addedOne = true;
  3671. }
  3672. var next = insertLineContent(line, builder, getLineStyles(cm, line));
  3673. sawBefore = line == lineBefore;
  3674. if (next) {
  3675. line = getLine(cm.doc, next.to.line);
  3676. simple = false;
  3677. }
  3678. } while (next);
  3679. if (measure && !builder.addedOne)
  3680. measure[0] = builder.pre.appendChild(simple ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
  3681. if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
  3682. builder.pre.appendChild(document.createTextNode("\u00a0"));
  3683. var order;
  3684. // Work around problem with the reported dimensions of single-char
  3685. // direction spans on IE (issue #1129). See also the comment in
  3686. // cursorCoords.
  3687. if (measure && ie && (order = getOrder(line))) {
  3688. var l = order.length - 1;
  3689. if (order[l].from == order[l].to) --l;
  3690. var last = order[l], prev = order[l - 1];
  3691. if (last.from + 1 == last.to && prev && last.level < prev.level) {
  3692. var span = measure[builder.pos - 1];
  3693. if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
  3694. span.nextSibling);
  3695. }
  3696. }
  3697. signal(cm, "renderLine", cm, realLine, builder.pre);
  3698. return builder.pre;
  3699. }
  3700. var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
  3701. function buildToken(builder, text, style, startStyle, endStyle) {
  3702. if (!text) return;
  3703. if (!tokenSpecialChars.test(text)) {
  3704. builder.col += text.length;
  3705. var content = document.createTextNode(text);
  3706. } else {
  3707. var content = document.createDocumentFragment(), pos = 0;
  3708. while (true) {
  3709. tokenSpecialChars.lastIndex = pos;
  3710. var m = tokenSpecialChars.exec(text);
  3711. var skipped = m ? m.index - pos : text.length - pos;
  3712. if (skipped) {
  3713. content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
  3714. builder.col += skipped;
  3715. }
  3716. if (!m) break;
  3717. pos += skipped + 1;
  3718. if (m[0] == "\t") {
  3719. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  3720. content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  3721. builder.col += tabWidth;
  3722. } else {
  3723. var token = elt("span", "\u2022", "cm-invalidchar");
  3724. token.title = "\\u" + m[0].charCodeAt(0).toString(16);
  3725. content.appendChild(token);
  3726. builder.col += 1;
  3727. }
  3728. }
  3729. }
  3730. if (style || startStyle || endStyle || builder.measure) {
  3731. var fullStyle = style || "";
  3732. if (startStyle) fullStyle += startStyle;
  3733. if (endStyle) fullStyle += endStyle;
  3734. return builder.pre.appendChild(elt("span", [content], fullStyle));
  3735. }
  3736. builder.pre.appendChild(content);
  3737. }
  3738. function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
  3739. var wrapping = builder.cm.options.lineWrapping;
  3740. for (var i = 0; i < text.length; ++i) {
  3741. var ch = text.charAt(i), start = i == 0;
  3742. if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
  3743. ch = text.slice(i, i + 2);
  3744. ++i;
  3745. } else if (i && wrapping &&
  3746. spanAffectsWrapping.test(text.slice(i - 1, i + 1))) {
  3747. builder.pre.appendChild(elt("wbr"));
  3748. }
  3749. var span = builder.measure[builder.pos] =
  3750. buildToken(builder, ch, style,
  3751. start && startStyle, i == text.length - 1 && endStyle);
  3752. // In IE single-space nodes wrap differently than spaces
  3753. // embedded in larger text nodes, except when set to
  3754. // white-space: normal (issue #1268).
  3755. if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
  3756. i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
  3757. span.style.whiteSpace = "normal";
  3758. builder.pos += ch.length;
  3759. }
  3760. if (text.length) builder.addedOne = true;
  3761. }
  3762. function buildTokenSplitSpaces(inner) {
  3763. function split(old) {
  3764. var out = " ";
  3765. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  3766. out += " ";
  3767. return out;
  3768. }
  3769. return function(builder, text, style, startStyle, endStyle) {
  3770. return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle);
  3771. };
  3772. }
  3773. function buildCollapsedSpan(builder, size, widget) {
  3774. if (widget) {
  3775. if (!builder.display) widget = widget.cloneNode(true);
  3776. builder.pre.appendChild(widget);
  3777. if (builder.measure && size) {
  3778. builder.measure[builder.pos] = widget;
  3779. builder.addedOne = true;
  3780. }
  3781. }
  3782. builder.pos += size;
  3783. }
  3784. // Outputs a number of spans to make up a line, taking highlighting
  3785. // and marked text into account.
  3786. function insertLineContent(line, builder, styles) {
  3787. var spans = line.markedSpans;
  3788. if (!spans) {
  3789. for (var i = 1; i < styles.length; i+=2)
  3790. builder.addToken(builder, styles[i], styleToClass(styles[i+1]));
  3791. return;
  3792. }
  3793. var allText = line.text, len = allText.length;
  3794. var pos = 0, i = 1, text = "", style;
  3795. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed;
  3796. for (;;) {
  3797. if (nextChange == pos) { // Update current marker set
  3798. spanStyle = spanEndStyle = spanStartStyle = "";
  3799. collapsed = null; nextChange = Infinity;
  3800. var foundBookmark = null;
  3801. for (var j = 0; j < spans.length; ++j) {
  3802. var sp = spans[j], m = sp.marker;
  3803. if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
  3804. if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
  3805. if (m.className) spanStyle += " " + m.className;
  3806. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  3807. if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
  3808. if (m.collapsed && (!collapsed || collapsed.marker.width < m.width))
  3809. collapsed = sp;
  3810. } else if (sp.from > pos && nextChange > sp.from) {
  3811. nextChange = sp.from;
  3812. }
  3813. if (m.type == "bookmark" && sp.from == pos && m.replacedWith)
  3814. foundBookmark = m.replacedWith;
  3815. }
  3816. if (collapsed && (collapsed.from || 0) == pos) {
  3817. buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
  3818. collapsed.from != null && collapsed.marker.replacedWith);
  3819. if (collapsed.to == null) return collapsed.marker.find();
  3820. }
  3821. if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
  3822. }
  3823. if (pos >= len) break;
  3824. var upto = Math.min(len, nextChange);
  3825. while (true) {
  3826. if (text) {
  3827. var end = pos + text.length;
  3828. if (!collapsed) {
  3829. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  3830. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  3831. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "");
  3832. }
  3833. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  3834. pos = end;
  3835. spanStartStyle = "";
  3836. }
  3837. text = styles[i++]; style = styleToClass(styles[i++]);
  3838. }
  3839. }
  3840. }
  3841. // DOCUMENT DATA STRUCTURE
  3842. function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
  3843. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  3844. function update(line, text, spans) {
  3845. updateLine(line, text, spans, estimateHeight);
  3846. signalLater(line, "change", line, change);
  3847. }
  3848. var from = change.from, to = change.to, text = change.text;
  3849. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  3850. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  3851. // First adjust the line structure
  3852. if (from.ch == 0 && to.ch == 0 && lastText == "") {
  3853. // This is a whole-line replace. Treated specially to make
  3854. // sure line objects move the way they are supposed to.
  3855. for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
  3856. added.push(makeLine(text[i], spansFor(i), estimateHeight));
  3857. update(lastLine, lastLine.text, lastSpans);
  3858. if (nlines) doc.remove(from.line, nlines);
  3859. if (added.length) doc.insert(from.line, added);
  3860. } else if (firstLine == lastLine) {
  3861. if (text.length == 1) {
  3862. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  3863. } else {
  3864. for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
  3865. added.push(makeLine(text[i], spansFor(i), estimateHeight));
  3866. added.push(makeLine(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  3867. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  3868. doc.insert(from.line + 1, added);
  3869. }
  3870. } else if (text.length == 1) {
  3871. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  3872. doc.remove(from.line + 1, nlines);
  3873. } else {
  3874. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  3875. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  3876. for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
  3877. added.push(makeLine(text[i], spansFor(i), estimateHeight));
  3878. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  3879. doc.insert(from.line + 1, added);
  3880. }
  3881. signalLater(doc, "change", doc, change);
  3882. setSelection(doc, selAfter.anchor, selAfter.head, null, true);
  3883. }
  3884. function LeafChunk(lines) {
  3885. this.lines = lines;
  3886. this.parent = null;
  3887. for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
  3888. lines[i].parent = this;
  3889. height += lines[i].height;
  3890. }
  3891. this.height = height;
  3892. }
  3893. LeafChunk.prototype = {
  3894. chunkSize: function() { return this.lines.length; },
  3895. removeInner: function(at, n) {
  3896. for (var i = at, e = at + n; i < e; ++i) {
  3897. var line = this.lines[i];
  3898. this.height -= line.height;
  3899. cleanUpLine(line);
  3900. signalLater(line, "delete");
  3901. }
  3902. this.lines.splice(at, n);
  3903. },
  3904. collapse: function(lines) {
  3905. lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
  3906. },
  3907. insertInner: function(at, lines, height) {
  3908. this.height += height;
  3909. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  3910. for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
  3911. },
  3912. iterN: function(at, n, op) {
  3913. for (var e = at + n; at < e; ++at)
  3914. if (op(this.lines[at])) return true;
  3915. }
  3916. };
  3917. function BranchChunk(children) {
  3918. this.children = children;
  3919. var size = 0, height = 0;
  3920. for (var i = 0, e = children.length; i < e; ++i) {
  3921. var ch = children[i];
  3922. size += ch.chunkSize(); height += ch.height;
  3923. ch.parent = this;
  3924. }
  3925. this.size = size;
  3926. this.height = height;
  3927. this.parent = null;
  3928. }
  3929. BranchChunk.prototype = {
  3930. chunkSize: function() { return this.size; },
  3931. removeInner: function(at, n) {
  3932. this.size -= n;
  3933. for (var i = 0; i < this.children.length; ++i) {
  3934. var child = this.children[i], sz = child.chunkSize();
  3935. if (at < sz) {
  3936. var rm = Math.min(n, sz - at), oldHeight = child.height;
  3937. child.removeInner(at, rm);
  3938. this.height -= oldHeight - child.height;
  3939. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  3940. if ((n -= rm) == 0) break;
  3941. at = 0;
  3942. } else at -= sz;
  3943. }
  3944. if (this.size - n < 25) {
  3945. var lines = [];
  3946. this.collapse(lines);
  3947. this.children = [new LeafChunk(lines)];
  3948. this.children[0].parent = this;
  3949. }
  3950. },
  3951. collapse: function(lines) {
  3952. for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
  3953. },
  3954. insertInner: function(at, lines, height) {
  3955. this.size += lines.length;
  3956. this.height += height;
  3957. for (var i = 0, e = this.children.length; i < e; ++i) {
  3958. var child = this.children[i], sz = child.chunkSize();
  3959. if (at <= sz) {
  3960. child.insertInner(at, lines, height);
  3961. if (child.lines && child.lines.length > 50) {
  3962. while (child.lines.length > 50) {
  3963. var spilled = child.lines.splice(child.lines.length - 25, 25);
  3964. var newleaf = new LeafChunk(spilled);
  3965. child.height -= newleaf.height;
  3966. this.children.splice(i + 1, 0, newleaf);
  3967. newleaf.parent = this;
  3968. }
  3969. this.maybeSpill();
  3970. }
  3971. break;
  3972. }
  3973. at -= sz;
  3974. }
  3975. },
  3976. maybeSpill: function() {
  3977. if (this.children.length <= 10) return;
  3978. var me = this;
  3979. do {
  3980. var spilled = me.children.splice(me.children.length - 5, 5);
  3981. var sibling = new BranchChunk(spilled);
  3982. if (!me.parent) { // Become the parent node
  3983. var copy = new BranchChunk(me.children);
  3984. copy.parent = me;
  3985. me.children = [copy, sibling];
  3986. me = copy;
  3987. } else {
  3988. me.size -= sibling.size;
  3989. me.height -= sibling.height;
  3990. var myIndex = indexOf(me.parent.children, me);
  3991. me.parent.children.splice(myIndex + 1, 0, sibling);
  3992. }
  3993. sibling.parent = me.parent;
  3994. } while (me.children.length > 10);
  3995. me.parent.maybeSpill();
  3996. },
  3997. iterN: function(at, n, op) {
  3998. for (var i = 0, e = this.children.length; i < e; ++i) {
  3999. var child = this.children[i], sz = child.chunkSize();
  4000. if (at < sz) {
  4001. var used = Math.min(n, sz - at);
  4002. if (child.iterN(at, used, op)) return true;
  4003. if ((n -= used) == 0) break;
  4004. at = 0;
  4005. } else at -= sz;
  4006. }
  4007. }
  4008. };
  4009. var nextDocId = 0;
  4010. var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
  4011. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
  4012. if (firstLine == null) firstLine = 0;
  4013. BranchChunk.call(this, [new LeafChunk([makeLine("", null)])]);
  4014. this.first = firstLine;
  4015. this.scrollTop = this.scrollLeft = 0;
  4016. this.cantEdit = false;
  4017. this.history = makeHistory();
  4018. this.frontier = firstLine;
  4019. var start = Pos(firstLine, 0);
  4020. this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
  4021. this.id = ++nextDocId;
  4022. this.modeOption = mode;
  4023. if (typeof text == "string") text = splitLines(text);
  4024. updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
  4025. };
  4026. Doc.prototype = createObj(BranchChunk.prototype, {
  4027. iter: function(from, to, op) {
  4028. if (op) this.iterN(from - this.first, to - from, op);
  4029. else this.iterN(this.first, this.first + this.size, from);
  4030. },
  4031. insert: function(at, lines) {
  4032. var height = 0;
  4033. for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
  4034. this.insertInner(at - this.first, lines, height);
  4035. },
  4036. remove: function(at, n) { this.removeInner(at - this.first, n); },
  4037. getValue: function(lineSep) {
  4038. var lines = getLines(this, this.first, this.first + this.size);
  4039. if (lineSep === false) return lines;
  4040. return lines.join(lineSep || "\n");
  4041. },
  4042. setValue: function(code) {
  4043. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  4044. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  4045. text: splitLines(code), origin: "setValue"},
  4046. {head: top, anchor: top}, true);
  4047. },
  4048. replaceRange: function(code, from, to, origin) {
  4049. from = clipPos(this, from);
  4050. to = to ? clipPos(this, to) : from;
  4051. replaceRange(this, code, from, to, origin);
  4052. },
  4053. getRange: function(from, to, lineSep) {
  4054. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  4055. if (lineSep === false) return lines;
  4056. return lines.join(lineSep || "\n");
  4057. },
  4058. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  4059. setLine: function(line, text) {
  4060. if (isLine(this, line))
  4061. replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
  4062. },
  4063. removeLine: function(line) {
  4064. if (isLine(this, line))
  4065. replaceRange(this, "", Pos(line, 0), clipPos(this, Pos(line + 1, 0)));
  4066. },
  4067. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  4068. getLineNumber: function(line) {return lineNo(line);},
  4069. lineCount: function() {return this.size;},
  4070. firstLine: function() {return this.first;},
  4071. lastLine: function() {return this.first + this.size - 1;},
  4072. clipPos: function(pos) {return clipPos(this, pos);},
  4073. getCursor: function(start) {
  4074. var sel = this.sel, pos;
  4075. if (start == null || start == "head") pos = sel.head;
  4076. else if (start == "anchor") pos = sel.anchor;
  4077. else if (start == "end" || start === false) pos = sel.to;
  4078. else pos = sel.from;
  4079. return copyPos(pos);
  4080. },
  4081. somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
  4082. setCursor: docOperation(function(line, ch, extend) {
  4083. var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
  4084. if (extend) extendSelection(this, pos);
  4085. else setSelection(this, pos, pos);
  4086. }),
  4087. setSelection: docOperation(function(anchor, head) {
  4088. setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor));
  4089. }),
  4090. extendSelection: docOperation(function(from, to) {
  4091. extendSelection(this, clipPos(this, from), to && clipPos(this, to));
  4092. }),
  4093. getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
  4094. replaceSelection: function(code, collapse, origin) {
  4095. makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
  4096. },
  4097. undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
  4098. redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
  4099. setExtending: function(val) {this.sel.extend = val;},
  4100. historySize: function() {
  4101. var hist = this.history;
  4102. return {undo: hist.done.length, redo: hist.undone.length};
  4103. },
  4104. clearHistory: function() {this.history = makeHistory();},
  4105. markClean: function() {
  4106. this.history.dirtyCounter = 0;
  4107. this.history.lastOp = this.history.lastOrigin = null;
  4108. },
  4109. isClean: function () {return this.history.dirtyCounter == 0;},
  4110. getHistory: function() {
  4111. return {done: copyHistoryArray(this.history.done),
  4112. undone: copyHistoryArray(this.history.undone)};
  4113. },
  4114. setHistory: function(histData) {
  4115. var hist = this.history = makeHistory();
  4116. hist.done = histData.done.slice(0);
  4117. hist.undone = histData.undone.slice(0);
  4118. },
  4119. markText: function(from, to, options) {
  4120. return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
  4121. },
  4122. setBookmark: function(pos, options) {
  4123. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  4124. insertLeft: options && options.insertLeft};
  4125. pos = clipPos(this, pos);
  4126. return markText(this, pos, pos, realOpts, "bookmark");
  4127. },
  4128. findMarksAt: function(pos) {
  4129. pos = clipPos(this, pos);
  4130. var markers = [], spans = getLine(this, pos.line).markedSpans;
  4131. if (spans) for (var i = 0; i < spans.length; ++i) {
  4132. var span = spans[i];
  4133. if ((span.from == null || span.from <= pos.ch) &&
  4134. (span.to == null || span.to >= pos.ch))
  4135. markers.push(span.marker.parent || span.marker);
  4136. }
  4137. return markers;
  4138. },
  4139. getAllMarks: function() {
  4140. var markers = [];
  4141. this.iter(function(line) {
  4142. var sps = line.markedSpans;
  4143. if (sps) for (var i = 0; i < sps.length; ++i)
  4144. if (sps[i].from != null) markers.push(sps[i].marker);
  4145. });
  4146. return markers;
  4147. },
  4148. posFromIndex: function(off) {
  4149. var ch, lineNo = this.first;
  4150. this.iter(function(line) {
  4151. var sz = line.text.length + 1;
  4152. if (sz > off) { ch = off; return true; }
  4153. off -= sz;
  4154. ++lineNo;
  4155. });
  4156. return clipPos(this, Pos(lineNo, ch));
  4157. },
  4158. indexFromPos: function (coords) {
  4159. coords = clipPos(this, coords);
  4160. var index = coords.ch;
  4161. if (coords.line < this.first || coords.ch < 0) return 0;
  4162. this.iter(this.first, coords.line, function (line) {
  4163. index += line.text.length + 1;
  4164. });
  4165. return index;
  4166. },
  4167. copy: function(copyHistory) {
  4168. var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
  4169. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  4170. doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
  4171. shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
  4172. if (copyHistory) {
  4173. doc.history.undoDepth = this.history.undoDepth;
  4174. doc.setHistory(this.getHistory());
  4175. }
  4176. return doc;
  4177. },
  4178. linkedDoc: function(options) {
  4179. if (!options) options = {};
  4180. var from = this.first, to = this.first + this.size;
  4181. if (options.from != null && options.from > from) from = options.from;
  4182. if (options.to != null && options.to < to) to = options.to;
  4183. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
  4184. if (options.sharedHist) copy.history = this.history;
  4185. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  4186. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  4187. return copy;
  4188. },
  4189. unlinkDoc: function(other) {
  4190. if (other instanceof CodeMirror) other = other.doc;
  4191. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  4192. var link = this.linked[i];
  4193. if (link.doc != other) continue;
  4194. this.linked.splice(i, 1);
  4195. other.unlinkDoc(this);
  4196. break;
  4197. }
  4198. // If the histories were shared, split them again
  4199. if (other.history == this.history) {
  4200. var splitIds = [other.id];
  4201. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  4202. other.history = makeHistory();
  4203. other.history.done = copyHistoryArray(this.history.done, splitIds);
  4204. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  4205. }
  4206. },
  4207. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  4208. getMode: function() {return this.mode;},
  4209. getEditor: function() {return this.cm;}
  4210. });
  4211. Doc.prototype.eachLine = Doc.prototype.iter;
  4212. // The Doc methods that should be available on CodeMirror instances
  4213. var dontDelegate = "iter insert remove copy getEditor".split(" ");
  4214. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  4215. CodeMirror.prototype[prop] = (function(method) {
  4216. return function() {return method.apply(this.doc, arguments);};
  4217. })(Doc.prototype[prop]);
  4218. function linkedDocs(doc, f, sharedHistOnly) {
  4219. function propagate(doc, skip, sharedHist) {
  4220. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  4221. var rel = doc.linked[i];
  4222. if (rel.doc == skip) continue;
  4223. var shared = sharedHist && rel.sharedHist;
  4224. if (sharedHistOnly && !shared) continue;
  4225. f(rel.doc, shared);
  4226. propagate(rel.doc, doc, shared);
  4227. }
  4228. }
  4229. propagate(doc, null, true);
  4230. }
  4231. function attachDoc(cm, doc) {
  4232. if (doc.cm) throw new Error("This document is already in use.");
  4233. cm.doc = doc;
  4234. doc.cm = cm;
  4235. estimateLineHeights(cm);
  4236. loadMode(cm);
  4237. if (!cm.options.lineWrapping) computeMaxLength(cm);
  4238. cm.options.mode = doc.modeOption;
  4239. regChange(cm);
  4240. }
  4241. // LINE UTILITIES
  4242. function getLine(chunk, n) {
  4243. n -= chunk.first;
  4244. while (!chunk.lines) {
  4245. for (var i = 0;; ++i) {
  4246. var child = chunk.children[i], sz = child.chunkSize();
  4247. if (n < sz) { chunk = child; break; }
  4248. n -= sz;
  4249. }
  4250. }
  4251. return chunk.lines[n];
  4252. }
  4253. function getBetween(doc, start, end) {
  4254. var out = [], n = start.line;
  4255. doc.iter(start.line, end.line + 1, function(line) {
  4256. var text = line.text;
  4257. if (n == end.line) text = text.slice(0, end.ch);
  4258. if (n == start.line) text = text.slice(start.ch);
  4259. out.push(text);
  4260. ++n;
  4261. });
  4262. return out;
  4263. }
  4264. function getLines(doc, from, to) {
  4265. var out = [];
  4266. doc.iter(from, to, function(line) { out.push(line.text); });
  4267. return out;
  4268. }
  4269. function updateLineHeight(line, height) {
  4270. var diff = height - line.height;
  4271. for (var n = line; n; n = n.parent) n.height += diff;
  4272. }
  4273. function lineNo(line) {
  4274. if (line.parent == null) return null;
  4275. var cur = line.parent, no = indexOf(cur.lines, line);
  4276. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  4277. for (var i = 0;; ++i) {
  4278. if (chunk.children[i] == cur) break;
  4279. no += chunk.children[i].chunkSize();
  4280. }
  4281. }
  4282. return no + cur.first;
  4283. }
  4284. function lineAtHeight(chunk, h) {
  4285. var n = chunk.first;
  4286. outer: do {
  4287. for (var i = 0, e = chunk.children.length; i < e; ++i) {
  4288. var child = chunk.children[i], ch = child.height;
  4289. if (h < ch) { chunk = child; continue outer; }
  4290. h -= ch;
  4291. n += child.chunkSize();
  4292. }
  4293. return n;
  4294. } while (!chunk.lines);
  4295. for (var i = 0, e = chunk.lines.length; i < e; ++i) {
  4296. var line = chunk.lines[i], lh = line.height;
  4297. if (h < lh) break;
  4298. h -= lh;
  4299. }
  4300. return n + i;
  4301. }
  4302. function heightAtLine(cm, lineObj) {
  4303. lineObj = visualLine(cm.doc, lineObj);
  4304. var h = 0, chunk = lineObj.parent;
  4305. for (var i = 0; i < chunk.lines.length; ++i) {
  4306. var line = chunk.lines[i];
  4307. if (line == lineObj) break;
  4308. else h += line.height;
  4309. }
  4310. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  4311. for (var i = 0; i < p.children.length; ++i) {
  4312. var cur = p.children[i];
  4313. if (cur == chunk) break;
  4314. else h += cur.height;
  4315. }
  4316. }
  4317. return h;
  4318. }
  4319. function getOrder(line) {
  4320. var order = line.order;
  4321. if (order == null) order = line.order = bidiOrdering(line.text);
  4322. return order;
  4323. }
  4324. // HISTORY
  4325. function makeHistory() {
  4326. return {
  4327. // Arrays of history events. Doing something adds an event to
  4328. // done and clears undo. Undoing moves events from done to
  4329. // undone, redoing moves them in the other direction.
  4330. done: [], undone: [], undoDepth: Infinity,
  4331. // Used to track when changes can be merged into a single undo
  4332. // event
  4333. lastTime: 0, lastOp: null, lastOrigin: null,
  4334. // Used by the isClean() method
  4335. dirtyCounter: 0
  4336. };
  4337. }
  4338. function attachLocalSpans(doc, change, from, to) {
  4339. var existing = change["spans_" + doc.id], n = 0;
  4340. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  4341. if (line.markedSpans)
  4342. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  4343. ++n;
  4344. });
  4345. }
  4346. function historyChangeFromChange(doc, change) {
  4347. var histChange = {from: change.from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4348. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4349. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  4350. return histChange;
  4351. }
  4352. function addToHistory(doc, change, selAfter, opId) {
  4353. var hist = doc.history;
  4354. hist.undone.length = 0;
  4355. var time = +new Date, cur = lst(hist.done);
  4356. if (cur &&
  4357. (hist.lastOp == opId ||
  4358. hist.lastOrigin == change.origin && change.origin &&
  4359. ((change.origin.charAt(0) == "+" && hist.lastTime > time - 600) || change.origin.charAt(0) == "*"))) {
  4360. // Merge this change into the last event
  4361. var last = lst(cur.changes);
  4362. if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
  4363. // Optimized case for simple insertion -- don't want to add
  4364. // new changesets for every character typed
  4365. last.to = changeEnd(change);
  4366. } else {
  4367. // Add new sub-event
  4368. cur.changes.push(historyChangeFromChange(doc, change));
  4369. }
  4370. cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
  4371. } else {
  4372. // Can not be merged, start a new event.
  4373. cur = {changes: [historyChangeFromChange(doc, change)],
  4374. anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
  4375. anchorAfter: selAfter.anchor, headAfter: selAfter.head};
  4376. hist.done.push(cur);
  4377. while (hist.done.length > hist.undoDepth)
  4378. hist.done.shift();
  4379. if (hist.dirtyCounter < 0)
  4380. // The user has made a change after undoing past the last clean state.
  4381. // We can never get back to a clean state now until markClean() is called.
  4382. hist.dirtyCounter = NaN;
  4383. else
  4384. hist.dirtyCounter++;
  4385. }
  4386. hist.lastTime = time;
  4387. hist.lastOp = opId;
  4388. hist.lastOrigin = change.origin;
  4389. }
  4390. function removeClearedSpans(spans) {
  4391. if (!spans) return null;
  4392. for (var i = 0, out; i < spans.length; ++i) {
  4393. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  4394. else if (out) out.push(spans[i]);
  4395. }
  4396. return !out ? spans : out.length ? out : null;
  4397. }
  4398. function getOldSpans(doc, change) {
  4399. var found = change["spans_" + doc.id];
  4400. if (!found) return null;
  4401. for (var i = 0, nw = []; i < change.text.length; ++i)
  4402. nw.push(removeClearedSpans(found[i]));
  4403. return nw;
  4404. }
  4405. // Used both to provide a JSON-safe object in .getHistory, and, when
  4406. // detaching a document, to split the history in two
  4407. function copyHistoryArray(events, newGroup) {
  4408. for (var i = 0, copy = []; i < events.length; ++i) {
  4409. var event = events[i], changes = event.changes, newChanges = [];
  4410. copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
  4411. anchorAfter: event.anchorAfter, headAfter: event.headAfter});
  4412. for (var j = 0; j < changes.length; ++j) {
  4413. var change = changes[j], m;
  4414. newChanges.push({from: change.from, to: change.to, text: change.text});
  4415. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  4416. if (indexOf(newGroup, Number(m[1])) > -1) {
  4417. lst(newChanges)[prop] = change[prop];
  4418. delete change[prop];
  4419. }
  4420. }
  4421. }
  4422. }
  4423. return copy;
  4424. }
  4425. // Rebasing/resetting history to deal with externally-sourced changes
  4426. function rebaseHistSel(pos, from, to, diff) {
  4427. if (to < pos.line) {
  4428. pos.line += diff;
  4429. } else if (from < pos.line) {
  4430. pos.line = from;
  4431. pos.ch = 0;
  4432. }
  4433. }
  4434. // Tries to rebase an array of history events given a change in the
  4435. // document. If the change touches the same lines as the event, the
  4436. // event, and everything 'behind' it, is discarded. If the change is
  4437. // before the event, the event's positions are updated. Uses a
  4438. // copy-on-write scheme for the positions, to avoid having to
  4439. // reallocate them all on every rebase, but also avoid problems with
  4440. // shared position objects being unsafely updated.
  4441. function rebaseHistArray(array, from, to, diff) {
  4442. for (var i = 0; i < array.length; ++i) {
  4443. var sub = array[i], ok = true;
  4444. for (var j = 0; j < sub.changes.length; ++j) {
  4445. var cur = sub.changes[j];
  4446. if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
  4447. if (to < cur.from.line) {
  4448. cur.from.line += diff;
  4449. cur.to.line += diff;
  4450. } else if (from <= cur.to.line) {
  4451. ok = false;
  4452. break;
  4453. }
  4454. }
  4455. if (!sub.copied) {
  4456. sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
  4457. sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
  4458. sub.copied = true;
  4459. }
  4460. if (!ok) {
  4461. array.splice(0, i + 1);
  4462. i = 0;
  4463. } else {
  4464. rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
  4465. rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
  4466. }
  4467. }
  4468. }
  4469. function rebaseHist(hist, change) {
  4470. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4471. rebaseHistArray(hist.done, from, to, diff);
  4472. rebaseHistArray(hist.undone, from, to, diff);
  4473. }
  4474. // EVENT OPERATORS
  4475. function stopMethod() {e_stop(this);}
  4476. // Ensure an event has a stop method.
  4477. function addStop(event) {
  4478. if (!event.stop) event.stop = stopMethod;
  4479. return event;
  4480. }
  4481. function e_preventDefault(e) {
  4482. if (e.preventDefault) e.preventDefault();
  4483. else e.returnValue = false;
  4484. }
  4485. function e_stopPropagation(e) {
  4486. if (e.stopPropagation) e.stopPropagation();
  4487. else e.cancelBubble = true;
  4488. }
  4489. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  4490. CodeMirror.e_stop = e_stop;
  4491. CodeMirror.e_preventDefault = e_preventDefault;
  4492. CodeMirror.e_stopPropagation = e_stopPropagation;
  4493. function e_target(e) {return e.target || e.srcElement;}
  4494. function e_button(e) {
  4495. var b = e.which;
  4496. if (b == null) {
  4497. if (e.button & 1) b = 1;
  4498. else if (e.button & 2) b = 3;
  4499. else if (e.button & 4) b = 2;
  4500. }
  4501. if (mac && e.ctrlKey && b == 1) b = 3;
  4502. return b;
  4503. }
  4504. // EVENT HANDLING
  4505. function on(emitter, type, f) {
  4506. if (emitter.addEventListener)
  4507. emitter.addEventListener(type, f, false);
  4508. else if (emitter.attachEvent)
  4509. emitter.attachEvent("on" + type, f);
  4510. else {
  4511. var map = emitter._handlers || (emitter._handlers = {});
  4512. var arr = map[type] || (map[type] = []);
  4513. arr.push(f);
  4514. }
  4515. }
  4516. function off(emitter, type, f) {
  4517. if (emitter.removeEventListener)
  4518. emitter.removeEventListener(type, f, false);
  4519. else if (emitter.detachEvent)
  4520. emitter.detachEvent("on" + type, f);
  4521. else {
  4522. var arr = emitter._handlers && emitter._handlers[type];
  4523. if (!arr) return;
  4524. for (var i = 0; i < arr.length; ++i)
  4525. if (arr[i] == f) { arr.splice(i, 1); break; }
  4526. }
  4527. }
  4528. function signal(emitter, type /*, values...*/) {
  4529. var arr = emitter._handlers && emitter._handlers[type];
  4530. if (!arr) return;
  4531. var args = Array.prototype.slice.call(arguments, 2);
  4532. for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
  4533. }
  4534. var delayedCallbacks, delayedCallbackDepth = 0;
  4535. function signalLater(emitter, type /*, values...*/) {
  4536. var arr = emitter._handlers && emitter._handlers[type];
  4537. if (!arr) return;
  4538. var args = Array.prototype.slice.call(arguments, 2);
  4539. if (!delayedCallbacks) {
  4540. ++delayedCallbackDepth;
  4541. delayedCallbacks = [];
  4542. setTimeout(fireDelayed, 0);
  4543. }
  4544. function bnd(f) {return function(){f.apply(null, args);};};
  4545. for (var i = 0; i < arr.length; ++i)
  4546. delayedCallbacks.push(bnd(arr[i]));
  4547. }
  4548. function fireDelayed() {
  4549. --delayedCallbackDepth;
  4550. var delayed = delayedCallbacks;
  4551. delayedCallbacks = null;
  4552. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  4553. }
  4554. function hasHandler(emitter, type) {
  4555. var arr = emitter._handlers && emitter._handlers[type];
  4556. return arr && arr.length > 0;
  4557. }
  4558. CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
  4559. // MISC UTILITIES
  4560. // Number of pixels added to scroller and sizer to hide scrollbar
  4561. var scrollerCutOff = 30;
  4562. // Returned or thrown by various protocols to signal 'I'm not
  4563. // handling this'.
  4564. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  4565. function Delayed() {this.id = null;}
  4566. Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
  4567. // Counts the column offset in a string, taking tabs into account.
  4568. // Used mostly to find indentation.
  4569. function countColumn(string, end, tabSize, startIndex, startValue) {
  4570. if (end == null) {
  4571. end = string.search(/[^\s\u00a0]/);
  4572. if (end == -1) end = string.length;
  4573. }
  4574. for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
  4575. if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
  4576. else ++n;
  4577. }
  4578. return n;
  4579. }
  4580. CodeMirror.countColumn = countColumn;
  4581. var spaceStrs = [""];
  4582. function spaceStr(n) {
  4583. while (spaceStrs.length <= n)
  4584. spaceStrs.push(lst(spaceStrs) + " ");
  4585. return spaceStrs[n];
  4586. }
  4587. function lst(arr) { return arr[arr.length-1]; }
  4588. function selectInput(node) {
  4589. if (ios) { // Mobile Safari apparently has a bug where select() is broken.
  4590. node.selectionStart = 0;
  4591. node.selectionEnd = node.value.length;
  4592. } else node.select();
  4593. }
  4594. function indexOf(collection, elt) {
  4595. if (collection.indexOf) return collection.indexOf(elt);
  4596. for (var i = 0, e = collection.length; i < e; ++i)
  4597. if (collection[i] == elt) return i;
  4598. return -1;
  4599. }
  4600. function createObj(base, props) {
  4601. function Obj() {}
  4602. Obj.prototype = base;
  4603. var inst = new Obj();
  4604. if (props) copyObj(props, inst);
  4605. return inst;
  4606. }
  4607. function copyObj(obj, target) {
  4608. if (!target) target = {};
  4609. for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
  4610. return target;
  4611. }
  4612. function emptyArray(size) {
  4613. for (var a = [], i = 0; i < size; ++i) a.push(undefined);
  4614. return a;
  4615. }
  4616. function bind(f) {
  4617. var args = Array.prototype.slice.call(arguments, 1);
  4618. return function(){return f.apply(null, args);};
  4619. }
  4620. var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/;
  4621. function isWordChar(ch) {
  4622. return /\w/.test(ch) || ch > "\x80" &&
  4623. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  4624. }
  4625. function isEmpty(obj) {
  4626. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  4627. return true;
  4628. }
  4629. var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/;
  4630. // DOM UTILITIES
  4631. function elt(tag, content, className, style) {
  4632. var e = document.createElement(tag);
  4633. if (className) e.className = className;
  4634. if (style) e.style.cssText = style;
  4635. if (typeof content == "string") setTextContent(e, content);
  4636. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  4637. return e;
  4638. }
  4639. function removeChildren(e) {
  4640. for (var count = e.childNodes.length; count > 0; --count)
  4641. e.removeChild(e.firstChild);
  4642. return e;
  4643. }
  4644. function removeChildrenAndAdd(parent, e) {
  4645. return removeChildren(parent).appendChild(e);
  4646. }
  4647. function setTextContent(e, str) {
  4648. if (ie_lt9) {
  4649. e.innerHTML = "";
  4650. e.appendChild(document.createTextNode(str));
  4651. } else e.textContent = str;
  4652. }
  4653. function getRect(node) {
  4654. return node.getBoundingClientRect();
  4655. }
  4656. CodeMirror.replaceGetRect = function(f) { getRect = f; };
  4657. // FEATURE DETECTION
  4658. // Detect drag-and-drop
  4659. var dragAndDrop = function() {
  4660. // There is *some* kind of drag-and-drop support in IE6-8, but I
  4661. // couldn't get it to work yet.
  4662. if (ie_lt9) return false;
  4663. var div = elt('div');
  4664. return "draggable" in div || "dragDrop" in div;
  4665. }();
  4666. // For a reason I have yet to figure out, some browsers disallow
  4667. // word wrapping between certain characters *only* if a new inline
  4668. // element is started between them. This makes it hard to reliably
  4669. // measure the position of things, since that requires inserting an
  4670. // extra span. This terribly fragile set of regexps matches the
  4671. // character combinations that suffer from this phenomenon on the
  4672. // various browsers.
  4673. var spanAffectsWrapping = /^$/; // Won't match any two-character string
  4674. if (gecko) spanAffectsWrapping = /$'/;
  4675. else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/;
  4676. else if (webkit) spanAffectsWrapping = /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.]|\?[\w~`@#$%\^&*(_=+{[|><]/;
  4677. var knownScrollbarWidth;
  4678. function scrollbarWidth(measure) {
  4679. if (knownScrollbarWidth != null) return knownScrollbarWidth;
  4680. var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
  4681. removeChildrenAndAdd(measure, test);
  4682. if (test.offsetWidth)
  4683. knownScrollbarWidth = test.offsetHeight - test.clientHeight;
  4684. return knownScrollbarWidth || 0;
  4685. }
  4686. var zwspSupported;
  4687. function zeroWidthElement(measure) {
  4688. if (zwspSupported == null) {
  4689. var test = elt("span", "\u200b");
  4690. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  4691. if (measure.firstChild.offsetHeight != 0)
  4692. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
  4693. }
  4694. if (zwspSupported) return elt("span", "\u200b");
  4695. else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  4696. }
  4697. // See if "".split is the broken IE version, if so, provide an
  4698. // alternative way to split lines.
  4699. var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  4700. var pos = 0, result = [], l = string.length;
  4701. while (pos <= l) {
  4702. var nl = string.indexOf("\n", pos);
  4703. if (nl == -1) nl = string.length;
  4704. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  4705. var rt = line.indexOf("\r");
  4706. if (rt != -1) {
  4707. result.push(line.slice(0, rt));
  4708. pos += rt + 1;
  4709. } else {
  4710. result.push(line);
  4711. pos = nl + 1;
  4712. }
  4713. }
  4714. return result;
  4715. } : function(string){return string.split(/\r\n?|\n/);};
  4716. CodeMirror.splitLines = splitLines;
  4717. var hasSelection = window.getSelection ? function(te) {
  4718. try { return te.selectionStart != te.selectionEnd; }
  4719. catch(e) { return false; }
  4720. } : function(te) {
  4721. try {var range = te.ownerDocument.selection.createRange();}
  4722. catch(e) {}
  4723. if (!range || range.parentElement() != te) return false;
  4724. return range.compareEndPoints("StartToEnd", range) != 0;
  4725. };
  4726. var hasCopyEvent = (function() {
  4727. var e = elt("div");
  4728. if ("oncopy" in e) return true;
  4729. e.setAttribute("oncopy", "return;");
  4730. return typeof e.oncopy == 'function';
  4731. })();
  4732. // KEY NAMING
  4733. var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  4734. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  4735. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  4736. 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
  4737. 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  4738. 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
  4739. 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
  4740. CodeMirror.keyNames = keyNames;
  4741. (function() {
  4742. // Number keys
  4743. for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
  4744. // Alphabetic keys
  4745. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  4746. // Function keys
  4747. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  4748. })();
  4749. // BIDI HELPERS
  4750. function iterateBidiSections(order, from, to, f) {
  4751. if (!order) return f(from, to, "ltr");
  4752. for (var i = 0; i < order.length; ++i) {
  4753. var part = order[i];
  4754. if (part.from < to && part.to > from || from == to && part.to == from)
  4755. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  4756. }
  4757. }
  4758. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  4759. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  4760. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  4761. function lineRight(line) {
  4762. var order = getOrder(line);
  4763. if (!order) return line.text.length;
  4764. return bidiRight(lst(order));
  4765. }
  4766. function lineStart(cm, lineN) {
  4767. var line = getLine(cm.doc, lineN);
  4768. var visual = visualLine(cm.doc, line);
  4769. if (visual != line) lineN = lineNo(visual);
  4770. var order = getOrder(visual);
  4771. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  4772. return Pos(lineN, ch);
  4773. }
  4774. function lineEnd(cm, lineN) {
  4775. var merged, line;
  4776. while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
  4777. lineN = merged.find().to.line;
  4778. var order = getOrder(line);
  4779. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  4780. return Pos(lineN, ch);
  4781. }
  4782. // This is somewhat involved. It is needed in order to move
  4783. // 'visually' through bi-directional text -- i.e., pressing left
  4784. // should make the cursor go left, even when in RTL text. The
  4785. // tricky part is the 'jumps', where RTL and LTR text touch each
  4786. // other. This often requires the cursor offset to move more than
  4787. // one unit, in order to visually move one unit.
  4788. function moveVisually(line, start, dir, byUnit) {
  4789. var bidi = getOrder(line);
  4790. if (!bidi) return moveLogically(line, start, dir, byUnit);
  4791. var moveOneUnit = byUnit ? function(pos, dir) {
  4792. do pos += dir;
  4793. while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
  4794. return pos;
  4795. } : function(pos, dir) { return pos + dir; };
  4796. var linedir = bidi[0].level;
  4797. for (var i = 0; i < bidi.length; ++i) {
  4798. var part = bidi[i], sticky = part.level % 2 == linedir;
  4799. if ((part.from < start && part.to > start) ||
  4800. (sticky && (part.from == start || part.to == start))) break;
  4801. }
  4802. var target = moveOneUnit(start, part.level % 2 ? -dir : dir);
  4803. while (target != null) {
  4804. if (part.level % 2 == linedir) {
  4805. if (target < part.from || target > part.to) {
  4806. part = bidi[i += dir];
  4807. target = part && (dir > 0 == part.level % 2 ? moveOneUnit(part.to, -1) : moveOneUnit(part.from, 1));
  4808. } else break;
  4809. } else {
  4810. if (target == bidiLeft(part)) {
  4811. part = bidi[--i];
  4812. target = part && bidiRight(part);
  4813. } else if (target == bidiRight(part)) {
  4814. part = bidi[++i];
  4815. target = part && bidiLeft(part);
  4816. } else break;
  4817. }
  4818. }
  4819. return target < 0 || target > line.text.length ? null : target;
  4820. }
  4821. function moveLogically(line, start, dir, byUnit) {
  4822. var target = start + dir;
  4823. if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
  4824. return target < 0 || target > line.text.length ? null : target;
  4825. }
  4826. // Bidirectional ordering algorithm
  4827. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  4828. // that this (partially) implements.
  4829. // One-char codes used for character types:
  4830. // L (L): Left-to-Right
  4831. // R (R): Right-to-Left
  4832. // r (AL): Right-to-Left Arabic
  4833. // 1 (EN): European Number
  4834. // + (ES): European Number Separator
  4835. // % (ET): European Number Terminator
  4836. // n (AN): Arabic Number
  4837. // , (CS): Common Number Separator
  4838. // m (NSM): Non-Spacing Mark
  4839. // b (BN): Boundary Neutral
  4840. // s (B): Paragraph Separator
  4841. // t (S): Segment Separator
  4842. // w (WS): Whitespace
  4843. // N (ON): Other Neutrals
  4844. // Returns null if characters are ordered as they appear
  4845. // (left-to-right), or an array of sections ({from, to, level}
  4846. // objects) in the order in which they occur visually.
  4847. var bidiOrdering = (function() {
  4848. // Character types for codepoints 0 to 0xff
  4849. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
  4850. // Character types for codepoints 0x600 to 0x6ff
  4851. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
  4852. function charType(code) {
  4853. if (code <= 0xff) return lowTypes.charAt(code);
  4854. else if (0x590 <= code && code <= 0x5f4) return "R";
  4855. else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
  4856. else if (0x700 <= code && code <= 0x8ac) return "r";
  4857. else return "L";
  4858. }
  4859. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  4860. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  4861. // Browsers seem to always treat the boundaries of block elements as being L.
  4862. var outerType = "L";
  4863. return function(str) {
  4864. if (!bidiRE.test(str)) return false;
  4865. var len = str.length, types = [];
  4866. for (var i = 0, type; i < len; ++i)
  4867. types.push(type = charType(str.charCodeAt(i)));
  4868. // W1. Examine each non-spacing mark (NSM) in the level run, and
  4869. // change the type of the NSM to the type of the previous
  4870. // character. If the NSM is at the start of the level run, it will
  4871. // get the type of sor.
  4872. for (var i = 0, prev = outerType; i < len; ++i) {
  4873. var type = types[i];
  4874. if (type == "m") types[i] = prev;
  4875. else prev = type;
  4876. }
  4877. // W2. Search backwards from each instance of a European number
  4878. // until the first strong type (R, L, AL, or sor) is found. If an
  4879. // AL is found, change the type of the European number to Arabic
  4880. // number.
  4881. // W3. Change all ALs to R.
  4882. for (var i = 0, cur = outerType; i < len; ++i) {
  4883. var type = types[i];
  4884. if (type == "1" && cur == "r") types[i] = "n";
  4885. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  4886. }
  4887. // W4. A single European separator between two European numbers
  4888. // changes to a European number. A single common separator between
  4889. // two numbers of the same type changes to that type.
  4890. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  4891. var type = types[i];
  4892. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  4893. else if (type == "," && prev == types[i+1] &&
  4894. (prev == "1" || prev == "n")) types[i] = prev;
  4895. prev = type;
  4896. }
  4897. // W5. A sequence of European terminators adjacent to European
  4898. // numbers changes to all European numbers.
  4899. // W6. Otherwise, separators and terminators change to Other
  4900. // Neutral.
  4901. for (var i = 0; i < len; ++i) {
  4902. var type = types[i];
  4903. if (type == ",") types[i] = "N";
  4904. else if (type == "%") {
  4905. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  4906. var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
  4907. for (var j = i; j < end; ++j) types[j] = replace;
  4908. i = end - 1;
  4909. }
  4910. }
  4911. // W7. Search backwards from each instance of a European number
  4912. // until the first strong type (R, L, or sor) is found. If an L is
  4913. // found, then change the type of the European number to L.
  4914. for (var i = 0, cur = outerType; i < len; ++i) {
  4915. var type = types[i];
  4916. if (cur == "L" && type == "1") types[i] = "L";
  4917. else if (isStrong.test(type)) cur = type;
  4918. }
  4919. // N1. A sequence of neutrals takes the direction of the
  4920. // surrounding strong text if the text on both sides has the same
  4921. // direction. European and Arabic numbers act as if they were R in
  4922. // terms of their influence on neutrals. Start-of-level-run (sor)
  4923. // and end-of-level-run (eor) are used at level run boundaries.
  4924. // N2. Any remaining neutrals take the embedding direction.
  4925. for (var i = 0; i < len; ++i) {
  4926. if (isNeutral.test(types[i])) {
  4927. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  4928. var before = (i ? types[i-1] : outerType) == "L";
  4929. var after = (end < len - 1 ? types[end] : outerType) == "L";
  4930. var replace = before || after ? "L" : "R";
  4931. for (var j = i; j < end; ++j) types[j] = replace;
  4932. i = end - 1;
  4933. }
  4934. }
  4935. // Here we depart from the documented algorithm, in order to avoid
  4936. // building up an actual levels array. Since there are only three
  4937. // levels (0, 1, 2) in an implementation that doesn't take
  4938. // explicit embedding into account, we can build up the order on
  4939. // the fly, without following the level-based algorithm.
  4940. var order = [], m;
  4941. for (var i = 0; i < len;) {
  4942. if (countsAsLeft.test(types[i])) {
  4943. var start = i;
  4944. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  4945. order.push({from: start, to: i, level: 0});
  4946. } else {
  4947. var pos = i, at = order.length;
  4948. for (++i; i < len && types[i] != "L"; ++i) {}
  4949. for (var j = pos; j < i;) {
  4950. if (countsAsNum.test(types[j])) {
  4951. if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
  4952. var nstart = j;
  4953. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  4954. order.splice(at, 0, {from: nstart, to: j, level: 2});
  4955. pos = j;
  4956. } else ++j;
  4957. }
  4958. if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
  4959. }
  4960. }
  4961. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  4962. order[0].from = m[0].length;
  4963. order.unshift({from: 0, to: m[0].length, level: 0});
  4964. }
  4965. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  4966. lst(order).to -= m[0].length;
  4967. order.push({from: len - m[0].length, to: len, level: 0});
  4968. }
  4969. if (order[0].level != lst(order).level)
  4970. order.push({from: len, to: len, level: order[0].level});
  4971. return order;
  4972. };
  4973. })();
  4974. // THE END
  4975. CodeMirror.version = "3.11";
  4976. return CodeMirror;
  4977. })();