2
0

codemirror.js 204 KB

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