codemirrorepl.js 300 KB

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