1
0

codemirror.js 214 KB

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