DC Team 的 Laravel 基底框架、資料庫描述、開發規範、環境佈署、版控規範

codemirror.js 236KB

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