codemirror.js 183 KB

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