codemirror.js 225 KB

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