Codemirror — Scrollbar на сайте .ru


Содержание

CodeMirror. Отключение вертикальной полосы прокрутки

В настоящее время я использую CodeMirror для редактирования CODE в текстовой области в браузере. Если у меня больше 20 строк кода, добавляется вертикальная полоса прокрутки вправо. Но мне не нужна эта полоса прокрутки. Вместо этого мне нужно, чтобы размер редактора увеличивался вертикально.

Может ли кто-нибудь помочь?

В CodeMirror 3 есть опция отключения полос прокрутки: scrollbarStyle: «null»

Выбирает реализацию прокрутки. Значение по умолчанию — «native», показывающее собственные полосы прокрутки. Основная библиотека также предоставляет «нулевой» стиль, который полностью скрывает полосы прокрутки. Аддоны могут реализовывать дополнительные модели прокрутки.

Объединяя это с:

  • автоматическая высота: height: auto и viewportMargin: Infinity (пример: http://codemirror.net/demo/resize.html)
  • оберточные строки: lineWrapping: true

И тогда управление высотой/шириной родительского div хорошо работает

CodeMirror doco рассказывает о стиле CodeMirror-scroll, который определяет, появится ли полоса прокрутки и будет ли текстовая область расширяется, чтобы соответствовать содержимому. В частности, он говорит:

CodeMirror прокруткиПрокручивается ли редактор (переполнение: авто + фиксированная высота). По умолчанию это делается. Установка класса CodeMirror для высоты: auto и предоставление этого класса overflow-x: auto; overflow-y: скрыто; приведет к изменению размера редактора в соответствии с его содержимым.

Таким образом, идея состоит в том, чтобы добавить к вашему собственному CSS что-то вроде:

как показано здесь в официальной демонстрации, которая сопровождает документацию по стилю Прокрутка кода .

Что сработало для меня:

Для моей личной ситуации с использованием CodeMirror 2.34 все, что я сделал, это добавить следующий стиль в мою собственную таблицу стилей:

CodeMirror 3:

В моем кратком первоначальном тестировании CodeMirror 3 оба вышеупомянутых метода не работали, и у меня все еще есть полосы прокрутки. Интересно, так как вы думаете, что официальная doco по теме будет действительной — если CodeMirror 3 не изменит свои стили немного, а doco еще не догнал.

Javascript → CodeMirror — библиотека для удобного редактирования кода

Описание

CodeMirror это Javascript библиотека, которая превращает textarea в подобие IDE, с подсветкой синтаксиса, табуляцией, автоотступами, автодополнением и другими полезными фишками.

Поддерживает подсветку основных языков программирования — C, C#, CSS, Javascript, HTML, PHP, SQL.

Библиотека знаменита тем, что используется в Google Code Playground.

Использование

1. Подключаем основной скрипт библиотеки и скрипты языков, редактирование которых будет осуществляться:


Некоторые языки зависят от других, например чтобы редактировать PHP код, нужно помимо mode/php/php.js подключить mode/clike/clike.js .

2. Подключаем основной CSS файл библиотеки и одну из тем:

3. Превращаем textarea в нормальный редактор:

Стилизация пользовательского скроллбара с помощью CSS и Jquery

Наверняка вы видели сайты с оригинальными полосами прокрутки. Это достигается с помощью нового CSS scroll свойства webKit-scrollbar . К сожалению, оно работает только в браузерах на движке WebKit . Но поддерживается jQuery почти во всех обозревателях. Давайте выполним стилизацию скроллбара.

Данное свойство поддерживается версиями Google Chrome для настольных компьютеров и мобильных устройств, Apple Safari , Flock , OmniWeb . Даже если вы создаете дизайн только для этих браузеров без использования jQuery , то сможете охватить только 72% пользователей интернета. Но если у вас нет аллергии на программирование, то можете быть уверены, что каждый ваш посетитель увидит красиво стилизованный скроллбар.

Стилизация скроллбара

Полосы прокрутки реализованы там, где длина контента превышает ширину окна контейнера. Благодаря этому вы получаете возможность стилизовать iframe , элементы div и поле ввода текста. В iframe и текстовой области окна браузеры автоматически добавляют полосу прокрутки в нижней части, когда содержимое выходит за пределы видимой области. Тем не менее, в контейнерах необходимо предоставлять дополнительную информацию для браузеров. Установка свойству overflow значения scroll говорит браузерам о том, что нужно выводить полосы прокрутки в случае переполнения окна контентом:

Это код scrolling CSS покажет полосу прокрутки такой (справа)

Использование псевдоэлементов CSS для настройки скроллбара

IE5.5 был первым браузером, поддерживающим основные стили для скроллинга. Используя свойство scrollbar-face-color , можно были изменить цвет полос прокрутки. Хотя это и не добавляло большого разнообразия, но все же лучше, чем стандартная полоса прокрутки в браузере. Поскольку это свойство по-прежнему поддерживается в Internet Explorer , его можно использовать для пользователей, предпочитающих этот браузер.

Для WebKit-браузерах в CSS существует множество вариантов стилизации: изменение цвета и ширины полосы прокрутки, ползунков. Элементы скроллинга можно выбрать с помощью следующих псевдоэлементов.

  1. ::webkit-scrollbar — позволяет настроить ширину и цвет полосы прокрутки. Когда этот псевдоэлемент указан, WebKit выключает свой встроенный рендеринг скроллбара и использует настройки, указанные для div scroll CSS . Обратите внимание, что при этом будут выбраны все полосы прокрутки, присутствующие на странице. Если нужно настроить скроллбар для определенного элемента, необходимо применить это свойство к конкретному элементу:
  1. ::-webkit-scrollbar-thumb – Это ползунок скроллбара ( чем вы держите и прокручиваете страницу ). Он может иметь цвет или использовать градиент в качестве фона. Пример реализации:
  1. ::-webkit-scrollbar-track – позволяет настроить трек скроллбара ( путь движения ползунка ). Синтаксис псевдоэлемента для CSS scroll :
  1. ::-webkit-scrollbar-button – разработчики CSS3 не упускают из виду маленькие кнопки на концах полосы прокрутки. Их также можно настроить, так как они помогают, когда страница длинная и скроллбар становится слишком маленьким для прокрутки. Это свойство стиля верхнего и нижнего углов ( или левого и правого для горизонтальных полос прокрутки ):

  1. ::-webkit-scrollbar-corner – позволяет справиться с ситуацией, когда появляются обе полосы прокрутки и пересекаются в углу:

Вот несколько примеров, которые демонстрируют силу свойства scrolling CSS .

Настройка скроллбара с помощью Jquery

Если вам нравится программирование front-end , вы можете использовать Jquery-плагин JScrollPane . Он довольно прост в использовании. После того, как вы загрузили и подключили соответствующие файлы в заголовке документа, нужно вызвать одну Javascript-функцию для инициализации панели прокрутки. Вы можете легко изменить дизайн полосы прокрутки с помощью CSS или выбрать одну из существующих тем.

С помощью этого плагина вы можете создавать скроллинг для всех типов браузеров. Так что я бы посоветовал вам воспользоваться им, чтобы сэкономить время и охватить сразу все браузеры:

Если вы захотите изменить настройки CSS scroll по умолчанию, предоставленные JScrollPane , нужно редактировать стили соответствующих элементов:

Вывод

Пользовательские скроллбары больше не являются редкостью. Вы найдете их на большинстве сайтов и блогов. А с JScrollPane стало гораздо проще создавать и отображать стилизованные полосы прокрутки во всех браузерах. Надеюсь, этот урок оказался для вас полезным.

Данная публикация представляет собой перевод статьи « Scrollbar styling using CSS and Jquery » , подготовленной дружной командой проекта Интернет-технологии.ру

Скроллбар

04.02.2013, 10:44

Скроллбар Google Chrome [New]
Здравствуйте, помогите пожалуйста, как сделать такой скроллбар на сайте, как у Google Chrome? .

Скроллбар для DIV
Всем привет. Использую CSS. ::-webkit-scrollbar < width: 12px; >.

Когда стилизовать скроллбар?
Заранее прошу прощения, если ошибся форумом, но посчитал что тут самое ему место. Разрабатываю.

Как кастомизировать скроллбар у селекта?
Как кастомизировать скроллбар у селекта? Селект в виде раскрывающегося списка с 24 пунктами.

Почему скроллбар не является границей сайта?
Расклад такой: Ширина хедера 960 пикселей. В хедере есть блок, который прижат к правому краю.

Принуждение CodeMirror ScrollBars в видимости программно

У меня есть текстовое поле CodeMirror внутри диалогового окна JQuery.

По какой-то причине, полосы прокрутки CodeMirror отказываются показать, пока символ не будет введен, даже если я изменить размер окна, пока код в CodeMirror не прикрыт.

Есть ли крюк в CodeMirror API программно сделать шоу вверх?

Как примечание, я lineWrapping установлен в ложь, и я звоню событие изменения размера CodeMirror х, когда срабатывает событие изменения размера диалогового JQuery в.


Получил ответ на форумах CodeMirror:

Все, что вам нужно сделать, это вызвать SetSize (NULL, NULL) на вашем экземпляре CodeMirror.

Настройки редактора CodeMirror. Вкладка «Параметры отображения»

Разобравшись с общим расположением элементов управления окна с настройками редактора CodeMirror в «Менеджере плагинов» в админке Joomla 3, разберём вкладку «Параметры отображения»: какие поля для управления отображением плагина в ней содержатся, их возможные значения и на что они влияют. Всего во вкладке «Параметры отображения» семь полей и каждое отвечает за отдельное свойство отображения информации, выдаваемой плагином. Рассмотрим их ниже.

Внешний вид Вкладки «Параметры отображения» редактора CodeMirror в «Менеджере плагинов» Joomla 3

Лучше один раз увидеть на картинке, чем 100500 раз прочитать описание, поэтому сначала картинка, как выглядит Вкладка «Параметры отображения» редактора CodeMirror в «Менеджере плагинов» Joomla 3:

How to disable vertical scrollbar in v3?

How to disable vertical scrollbar in v3?



You are receiving this because you are currently a member of the CodeMirror Google group. To send something to list, use [hidden email], to unsubscribe, send a message to [hidden email].

You received this message because you are subscribed to the Google Groups «CodeMirror» group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/groups/opt_out.

Re: How to disable vertical scrollbar in v3?

Are you looking for the effect described in
http://codemirror.net/demo/resize.html ? If so, simply doing what that
demo page does, CSS-wise, should be all it takes.

On Fri, May 24, 2013 at 3:43 AM, Michael Zhou
wrote:



You are receiving this because you are currently a member of the CodeMirror Google group. To send something to list, use [hidden email], to unsubscribe, send a message to [hidden email].

You received this message because you are subscribed to the Google Groups «CodeMirror» group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/groups/opt_out.

Re: How to disable vertical scrollbar in v3?

Are you looking for the effect described in
http://codemirror.net/demo/ resize.html ? If so, simply doing what that
demo page does, CSS-wise, should be all it takes.

On Fri, May 24, 2013 at 3:43 AM, Michael Zhou
wrote:



You are receiving this because you are currently a member of the CodeMirror Google group. To send something to list, use [hidden email], to unsubscribe, send a message to [hidden email].

You received this message because you are subscribed to the Google Groups «CodeMirror» group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/groups/opt_out.

Re: How to disable vertical scrollbar in v3?

> Does «viewportMargin» have to be «Infinity» to make this happen? Could it just be a large number for most documents?

What’s wrong with Infinity?



You are receiving this because you are currently a member of the CodeMirror Google group. To send something to list, use [hidden email], to unsubscribe, send a message to [hidden email].

You received this message because you are subscribed to the Google Groups «CodeMirror» group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/groups/opt_out.

Re: How to disable vertical scrollbar in v3?

It doesn’t work. the vertical scrollbar is still there. I checked the applied style and found that overflow-y is ‘hidden’.

On Fr >> Does «viewportMargin» have to be «Infinity» to make this happen? Could it just be a large number for most documents?


What’s wrong with Infinity?

Codemirror — Scrollbar на сайте .ru

CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides only the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the addons included in the distribution, and the list of externally hosted addons, for reusable implementations of extra features.

CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the mode/ directory), and it isn’t hard to write new ones for other languages.

Basic Usage

The easiest way to use CodeMirror is to simply load the script and style sheet found under lib/ in the distribution, plus a mode script from one of the mode/ directories. (See the compression helper for an easy way to combine scripts.) For example:

Having done this, an editor instance can be created like this:

The editor will be appended to the document body, will start empty, and will use the mode that we loaded. To have more control over the new editor, a configuration object can be passed to CodeMirror as a second argument:

This will initialize the editor with a piece of code already in it, and explicitly tell it to use the JavaScript mode (which is useful when multiple modes are loaded). See below for a full discussion of the configuration options that CodeMirror accepts.

In cases where you don’t want to append the editor to an element, and need more control over the way it is inserted, the first argument to the CodeMirror function can also be a function that, when given a DOM element, inserts it into the document somewhere. This could be used to, for example, replace a textarea with a real editor:

However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:

This will, among other things, ensure that the textarea’s value is updated with the editor’s contents when the form (if it is part of a form) is submitted. See the API reference for a full description of this method.

Configuration

Both the CodeMirror function and its fromTextArea method take as second (optional) argument an object containing configuration options. Any option not supplied like this will be taken from CodeMirror.defaults , an object containing the default options. You can update this object to change the defaults on your page.

Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.

These are the supported options:

value: string|CodeMirror.Doc The starting value of the editor. Can be a string, or a document object. mode: string|object The mode to use. When not given, this will default to the first mode that was loaded. It may be a string, which either simply names the mode or is a MIME type associated with the mode. Alternatively, it may be an object containing configuration options for the mode, with a name property that names the mode (for example ). The demo pages for each mode contain information about what configuration parameters the mode supports. You can ask CodeMirror which modes and MIME types have been defined by inspecting the CodeMirror.modes and CodeMirror.mimeModes objects. The first maps mode names to their constructors, and the second maps MIME types to mode specs. theme: string The theme to style the editor with. You must make sure the CSS file defining the corresponding .cm-s-[name] styles is loaded (see the theme directory in the distribution). The default is «default» , for which colors are included in codemirror.css . It is possible to use multiple theming classes at once—for example «foo bar» will assign both the cm-s-foo and the cm-s-bar classes to the editor. indentUnit: integer How many spaces a block (whatever that means in the edited language) should be indented. The default is 2. smartIndent: boolean Whether to use the context-sensitive indentation that the mode provides (or just indent the same as the line before). Defaults to true. tabSize: integer The width of a tab character. Defaults to 4. indentWithTabs: boolean Whether, when indenting, the first N* tabSize spaces should be replaced by N tabs. Default is false. electricChars: boolean Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). Default is true. specialChars: RegExp A regular expression used to determine which characters should be replaced by a special placeholder. Mostly useful for non-printing special characters. The default is /[\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/ . specialCharPlaceholder: function(char)В в†’В Element A function that, given a special character identified by the specialChars option, produces a DOM node that is used to represent the character. By default, a red dot ( • ) is shown, with a title tooltip to indicate the character code. rtlMoveVisually: boolean Determines whether horizontal cursor movement through right-to-left (Arabic, Hebrew) text is visual (pressing the left arrow moves the cursor left) or logical (pressing the left arrow moves to the next lower index in the string, which is visually right in right-to-left text). The default is false on Windows, and true on other platforms. keyMap: string Configures the keymap to use. The default is «default» , which is the only keymap defined in codemirror.js itself. Extra keymaps are found in the keymap directory. See the section on keymaps for more information. extraKeys: object Can be used to specify extra keybindings for the editor, alongside the ones defined by keyMap . Should be either null, or a valid keymap value. lineWrapping: boolean Whether CodeMirror should scroll or wrap for long lines. Defaults to false (scroll). lineNumbers: boolean Whether to show line numbers to the left of the editor. firstLineNumber: integer At which number to start counting lines. Default is 1. lineNumberFormatter: function(line: integer) в†’ string A function used to format line numbers. The function is passed the line number, and should return a string that will be shown in the gutter. gutters: array Can be used to add extra gutters (beyond or instead of the line number gutter). Should be an array of CSS class names, each of which defines a width (and optionally a background), and which will be used to draw the background of the gutters. May include the CodeMirror-linenumbers class, in order to explicitly set the position of the line number gutter (it will default to be to the right of all other gutters). These class names are the keys passed to setGutterMarker . fixedGutter: boolean Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). coverGutterNextToScrollbar: boolean When fixedGutter is on, and there is a horizontal scrollbar, by default the gutter will be visible to the left of this scrollbar. If this option is set to true, it will be covered by an element with class CodeMirror-gutter-filler . readOnly: boolean|string This disables editing of the editor content by the user. If the special value «nocursor» is given (instead of simply true ), focusing of the editor is also disallowed. showCursorWhenSelecting: boolean Whether the cursor should be drawn when a selection is active. Defaults to false. undoDepth: integer The maximum number of undo levels that the editor stores. Defaults to 40. historyEventDelay: integer The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. Defaults to 500. tabindex: integer The tab index to assign to the editor. If not given, no tab index will be assigned. autofocus: boolean Can be used to make CodeMirror focus itself on initialization. Defaults to off. When fromTextArea is used, and no explicit value is given for this option, it will be set to true when either the source textarea is focused, or it has an autofocus attribute and no other element is focused.

Below this a few more specialized, low-level options are listed. These are only useful in very specific situations, you might want to skip them the first time you read this manual.

dragDrop: boolean Controls whether drag-and-drop is enabled. On by default. onDragEvent: function(instance: CodeMirror, event: Event) в†’ boolean Deprecated! See these event handlers for the current recommended approach.
When given, this will be called when the editor is handling a dragenter , dragover , or drop event. It will be passed the editor instance and the event object as arguments. The callback can choose to handle the event itself, in which case it should return true to indicate that CodeMirror should not do anything further. onKeyEvent: function(instance: CodeMirror, event: Event) в†’ boolean Deprecated! See these event handlers for the current recommended approach.
This provides a rather low-level hook into CodeMirror’s key handling. If provided, this function will be called on every keydown , keyup , and keypress event that CodeMirror captures. It will be passed two arguments, the editor instance and the key event. This key event is pretty much the raw key event, except that a stop() method is always added to it. You could feed it to, for example, jQuery.Event to further normalize it.
This function can inspect the key event, and handle it if it wants to. It may return true to tell CodeMirror to ignore the event. Be wary that, on some browsers, stopping a keydown does not stop the keypress from firing, whereas on others it does. If you respond to an event, you should probably inspect its type property and only do something when it is keydown (or keypress for actions that need character data). cursorBlinkRate: number Half-period in milliseconds used for cursor blinking. The default blink rate is 530ms. By setting this to zero, blinking can be disabled. cursorScrollMargin: number How much extra space to always keep above and below the cursor when approaching the top or bottom of the visible view in a scrollable document. Default is 0. cursorHeight: number Determines the height of the cursor. Default is 1, meaning it spans the whole height of the line. For some fonts (and by some tastes) a smaller height (for example 0.85 ), which causes the cursor to not reach all the way to the bottom of the line, looks better resetSelectionOnContextMenu: boolean Controls whether, when the context menu is opened with a click outside of the current selection, the cursor is moved to the point of the click. Defaults to true . workTime, workDelay: number Highlighting is done by a pseudo background-thread that will work for workTime milliseconds, and then use timeout to sleep for workDelay milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive. workDelay: number See workTime . pollInterval: number Indicates how quickly CodeMirror should poll its input textarea for changes (when focused). Most input is captured by events, but some things, like IME input on some browsers, don’t generate events that allow CodeMirror to properly detect it. Thus, it polls. Default is 100 milliseconds. flattenSpans: boolean By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. This will result in a simpler DOM tree, and thus perform better. With some kinds of styling (such as rounded corners), this will change the way the document looks. You can set this option to false to disable this behavior. maxHighlightLength: number When highlighting long lines, in order to stay responsive, the editor will give up and simply style the rest of the line as plain text when it reaches a certain position. The default is 10 000. You can set this to Infinity to turn off this behavior. crudeMeasuringFrom: number When measuring the character positions in long lines, any line longer than this number (default is 10 000), when line wrapping is off, will simply be assumed to consist of same-sized characters. This means that, on the one hand, measuring will be inaccurate when characters of varying size, right-to-left text, markers, or other irregular elements are present. On the other hand, it means that having such a line won’t freeze the user interface because of the expensiveness of the measurements. viewportMargin: integer Specifies the amount of lines that are rendered above and below the part of the document that’s currently scrolled into view. This affects the amount of updates needed when scrolling, and the amount of work that such an update does. You should usually leave it at its default, 10. Can be set to Infinity to make sure the whole document is always rendered, and thus the browser’s text search works on it. This will have bad effects on performance of big documents.

Events

Various CodeMirror-related objects emit events, which allow client code to react to various situations. Handlers for such events can be registed with the on and off methods on the objects that the event fires on. To fire your own events, use CodeMirror.signal(target, name, args. ) , where target is a non-DOM-node object.

An editor instance fires the following events. The instance argument always refers to the editor itself.

«change» (instance: CodeMirror, changeObj: object) Fires every time the content of the editor is changed. The changeObj is a object containing information about the changes that occurred as second argument. from and to are the positions (in the pre-change coordinate system) where the change started and ended (for example, it might be if the position is at the beginning of line #19). text is an array of strings representing the text that replaced the changed range (split by line). removed is the text that used to be between from and to , which is overwritten by this change. If multiple changes happened during a single operation, the object will have a next property pointing to another change object (which may point to another, etc). «beforeChange» (instance: CodeMirror, changeObj: object) This event is fired before a change is applied, and its handler may choose to modify or cancel the change. The changeObj object has from , to , and text properties, as with the «change» event, but never a next property, since this is fired for each individual change, and not batched per operation. It also has a cancel() method, which can be called to cancel the change, and, if the change isn’t coming from an undo or redo event, an update(from, to, text) method, which may be used to modify the change. Undo or redo changes can’t be modified, because they hold some metainformation for restoring old marked ranges that is only valid for that specific change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. Note: you may not do anything from a «beforeChange» handler that would cause changes to the document or its visualization. Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, probably cause the editor to become corrupted. «cursorActivity» (instance: CodeMirror) Will be fired when the cursor or selection moves, or any change is made to the editor content. «keyHandled» (instance: CodeMirror, name: string, event: Event) Fired after a key is handled through a keymap. name is the name of the handled key (for example «Ctrl-X» or «‘q'» ), and event is the DOM keydown or keypress event. «inputRead» (instance: CodeMirror, changeObj: object) Fired whenever new input is read from the hidden textarea (typed or pasted by the user). «beforeSelectionChange» (instance: CodeMirror, selection: ) This event is fired before the selection is moved. Its handler may modify the resulting selection head and anchor. The selection parameter is an object with head and anchor properties holding objects, which the handler can read and update. Handlers for this event have the same restriction as «beforeChange» handlers — they should not do anything to directly update the state of the editor. «viewportChange» (instance: CodeMirror, from: number, to: number) Fires whenever the view port of the editor changes (due to scrolling, editing, or any other factor). The from and to arguments give the new start and end of the viewport. «swapDoc» (instance: CodeMirror, oldDoc: Doc) This is signalled when the editor’s document is replaced using the swapDoc method. «gutterClick» (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event) Fires when the editor gutter (the line-number area) is clicked. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw mousedown event object as fourth argument. «gutterContextMenu» (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event) Fires when the editor gutter (the line-number area) receives a contextmenu event. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw contextmenu mouse event object as fourth argument. You can preventDefault the event, to signal that CodeMirror should do no further handling. «focus» (instance: CodeMirror) Fires whenever the editor is focused. «blur» (instance: CodeMirror) Fires whenever the editor is unfocused. «scroll» (instance: CodeMirror) Fires when the editor is scrolled. «update» (instance: CodeMirror) Will be fired whenever CodeMirror updates its DOM display. «renderLine» (instance: CodeMirror, line: LineHandle, element: Element) Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. «mousedown», «dblclick», «contextmenu», «keydown», «keypress», «keyup», «dragstart», «dragenter», «dragover», «drop» (instance: CodeMirror, event: Event) Fired when CodeMirror is handling a DOM event of this type. You can preventDefault the event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.

Document objects (instances of CodeMirror.Doc ) emit the following events:


«change» (doc: CodeMirror.Doc, changeObj: object) Fired whenever a change occurs to the document. changeObj has a similar type as the object passed to the editor’s «change» event, but it never has a next property, because document change events are not batched (whereas editor change events are). «beforeChange» (doc: CodeMirror.Doc, change: object) See the description of the same event on editor instances. «cursorActivity» (doc: CodeMirror.Doc) Fired whenever the cursor or selection in this document changes. «beforeSelectionChange» (doc: CodeMirror.Doc, selection: ) Equivalent to the event by the same name as fired on editor instances.

Line handles (as returned by, for example, getLineHandle ) support these events:

«delete» () Will be fired when the line object is deleted. A line object is associated with the start of the line. Mostly useful when you need to find out when your gutter markers on a given line are removed. «change» (line: LineHandle, changeObj: object) Fires when the line’s text content is changed in any way (but the line is not deleted outright). The change object is similar to the one passed to change event on the editor object.

Marked range handles ( CodeMirror.TextMarker ), as returned by markText and setBookmark , emit the following events:

«beforeCursorEnter» () Fired when the cursor enters the marked range. From this event handler, the editor state may be inspected but not modified, with the exception that the range on which the event fires may be cleared. «clear» (from: , to: ) Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method. Will only be fired once per handle. Note that deleting the range through text editing does not fire this event, because an undo action might bring the range back into existence. from and to give the part of the document that the range spanned when it was cleared. «hide» () Fired when the last part of the marker is removed from the document by editing operations. «unhide» () Fired when, after the marker was removed by editing, a undo operation brought the marker back.

Line widgets ( CodeMirror.LineWidget ), returned by addLineWidget , fire these events:

«redraw» () Fired whenever the editor re-adds the widget to the DOM. This will happen once right after the widget is added (if it is scrolled into view), and then again whenever it is scrolled out of view and back in again, or when changes to the editor options or the line the widget is on require the widget to be redrawn.

Keymaps

Keymaps are ways to associate keys with functionality. A keymap is an object mapping strings that identify the keys to functions that implement their functionality.

Keys are identified either by name or by character. The CodeMirror.keyNames object defines names for common keys and associates them with their key codes. Examples of names defined here are Enter , F5 , and Q . These can be prefixed with Shift- , Cmd- , Ctrl- , and Alt- (in that order!) to specify a modifier. So for example, Shift-Ctrl-Space would be a valid key identifier.

Common example: map the Tab key to insert spaces instead of a tab character.

Alternatively, a character can be specified directly by surrounding it in single quotes, for example ‘$’ or ‘q’ . Due to limitations in the way browsers fire key events, these may not be prefixed with modifiers.

The CodeMirror.keyMap object associates keymaps with names. User code and keymap definitions can assign extra properties to this object. Anywhere where a keymap is expected, a string can be given, which will be looked up in this object. It also contains the «default» keymap holding the default bindings.

The values of properties in keymaps can be either functions of a single argument (the CodeMirror instance), strings, or false . Such strings refer to properties of the CodeMirror.commands object, which defines a number of common commands that are used by the default keybindings, and maps them to functions. If the property is set to false , CodeMirror leaves handling of the key up to the browser. A key handler function may return CodeMirror.Pass to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.

Keys mapped to command names that start with the characters «go» (which should be used for cursor-movement actions) will be fired even when an extra Shift modifier is present (i.e. «Up»: «goLineUp» matches both up and shift-up). This is used to easily implement shift-selection.

Keymaps can defer to each other by defining a fallthrough property. This indicates that when a key is not found in the map itself, one or more other maps should be searched. It can hold either a single keymap or an array of keymaps.

When a keymap contains a nofallthrough property set to true , keys matched against that map will be ignored if they don’t match any of the bindings in the map (no further child maps will be tried). When the disableInput property is set to true , the default effect of inserting a character will be suppressed when the keymap is active as the top-level map.

Customized Styling

Up to a certain extent, CodeMirror’s look can be changed by modifying style sheet files. The style sheets supplied by modes simply provide the colors for that mode, and can be adapted in a very straightforward way. To style the editor itself, it is possible to alter or override the styles defined in codemirror.css .

Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. Adjusting colors should be safe, of course, and with some care a lot of other things can be changed as well. The CSS classes defined in this file serve the following roles:

CodeMirror The outer element of the editor. This should be used for the editor width, height, borders and positioning. Can also be used to set styles that should hold for everything inside the editor (such as font and font size), or to set a background. CodeMirror-scroll Whether the editor scrolls ( overflow: auto + fixed height). By default, it does. Setting the CodeMirror class to have height: auto and giving this class overflow-x: auto; overflow-y: hidden; will cause the editor to resize to fit its content. CodeMirror-focused Whenever the editor is focused, the top element gets this class. This is used to hide the cursor and give the selection a different color when the editor is not focused. CodeMirror-gutters This is the backdrop for all gutters. Use it to set the default gutter background color, and optionally add a border on the right of the gutters. CodeMirror-linenumbers Use this for giving a background or width to the line number gutter. CodeMirror-linenumber Used to style the actual individual line numbers. These won’t be children of the CodeMirror-linenumbers (plural) element, but rather will be absolutely positioned to overlay it. Use this to set alignment and text properties for the line numbers. CodeMirror-lines The visible lines. This is where you specify vertical padding for the editor content. CodeMirror-cursor The cursor is a block element that is absolutely positioned. You can make it look whichever way you want. CodeMirror-selected The selection is represented by span elements with this class. CodeMirror-matchingbracket , CodeMirror-nonmatchingbracket These are used to style matched (or unmatched) brackets.

If your page’s style sheets do funky things to all div or pre elements (you probably shouldn’t do that), you’ll have to define rules to cancel these effects out again for elements under the CodeMirror class.

Themes are also simply CSS files, which define colors for various syntactic elements. See the files in the theme directory.

Programming API


A lot of CodeMirror features are only available through its API. Thus, you need to write code (or use addons) if you want to expose them to your users.

Whenever points in the document are represented, the API uses objects with line and ch properties. Both are zero-based. CodeMirror makes sure to ‘clip’ any positions passed by client code so that they fit inside the document, so you shouldn’t worry too much about sanitizing your coordinates. If you give ch a value of null , or don’t specify it, it will be replaced with the length of the specified line.

Methods prefixed with doc. can, unless otherwise specified, be called both on CodeMirror (editor) instances and CodeMirror.Doc instances. Methods prefixed with cm. are only available on CodeMirror instances.

Constructor

Constructing an editor instance is done with the CodeMirror(place: Element|fn(Element), ?option: object) constructor. If the place argument is a DOM element, the editor will be appended to it. If it is a function, it will be called, and is expected to place the editor into the document. options may be an element mapping option names to values. The options that it doesn’t explicitly specify (or all options, if it is not passed) will be taken from CodeMirror.defaults .

Note that the options object passed to the constructor will be mutated when the instance’s options are changed, so you shouldn’t share such objects between instances.

See CodeMirror.fromTextArea for another way to construct an editor instance.

Content manipulation methods

Cursor and selection methods

Configuration methods

Document management methods

Each editor is associated with an instance of CodeMirror.Doc , its document. A document represents the editor content, plus a selection, an undo history, and a mode. A document can only be associated with a single editor at a time. You can create new documents by calling the CodeMirror.Doc(text, mode, firstLineNumber) constructor. The last two arguments are optional and can be used to set a mode for the document and make it start at a line number other than 0, respectively.

cm.getDoc() в†’ Doc Retrieve the currently active document from an editor. doc.getEditor() в†’ CodeMirror Retrieve the editor associated with a document. May return null . cm.swapDoc(doc: CodeMirror.Doc) в†’ Doc Attach a new document to the editor. Returns the old document, which is now no longer associated with an editor. doc.copy(copyHistory: boolean) в†’ Doc Create an identical copy of the given doc. When copyHistory is true, the history will also be copied. Can not be called directly on an editor. doc.linkedDoc(options: object) в†’ Doc Create a new document that’s linked to the target document. Linked documents will stay in sync (changes to one are also applied to the other) until unlinked. These are the options that are supported: sharedHist: boolean When turned on, the linked copy will share an undo history with the original. Thus, something done in one of the two can be undone in the other, and vice versa. from: integer to: integer Can be given to make the new document a subview of the original. Subviews only show a given range of lines. Note that line coordinates inside the subview will be consistent with those of the parent, so that for example a subview starting at line 10 will refer to its first line as line 10, not 0. mode: string|object By default, the new document inherits the mode of the parent. This option can be set to a mode spec to give it a different mode. doc.unlinkDoc(doc: CodeMirror.Doc) Break the link between two documents. After calling this, changes will no longer propagate between the documents, and, if they had a shared history, the history will become separate. doc.iterLinkedDocs(function: (doc: CodeMirror.Doc, sharedHist: boolean)) Will call the given function for all documents linked to the target document. It will be passed two arguments, the linked document and a boolean indicating whether that document shares history with the target.

Text-marking methods

Returns an array of all the bookmarks and marked ranges present at the given position. doc.getAllMarks() в†’ array

Returns an array containing all marked ranges in the document.

Widget, gutter, and decoration methods

Sizing, scrolling and positioning methods

When writing language-aware functionality, it can often be useful to hook into the knowledge that the CodeMirror language mode has. See the section on modes for a more detailed description of how these work.

doc.getMode() в†’ object Gets the (outer) mode object for the editor. Note that this is distinct from getOption(«mode») , which gives you the mode specification, rather than the resolved, instantiated mode object. doc.getModeAt(pos: ) в†’ object Gets the inner mode at a given position. This will return the same as getMode for simple modes, but will return an inner mode for nesting modes (such as htmlmixed ). cm.getTokenAt(pos: , ?precise: boolean) в†’ object Retrieves information about the token the current mode found before the given position (a object). The returned object has the following properties: start The character (on the given line) at which the token starts. end The character at which the token ends. string The token’s string. type The token type the mode assigned to the token, such as «keyword» or «comment» (may also be null). state The mode’s state at the end of this token. If precise is true, the token will be guaranteed to be accurate based on recent edits. If false or not specified, the token will use cached state information, which will be faster but might not be accurate if edits were recently made and highlighting has not yet completed. cm.getTokenTypeAt(pos: ) в†’ string This is a (much) cheaper version of getTokenAt useful for when you just need the type of the token at a given position, and no other information. Will return null for unstyled tokens, and a string, potentially containing multiple space-separated style names, otherwise. cm.getHelper(pos: , type: string) в†’ helper Fetch appropriate helper for the given position. Helpers provide a way to look up functionality appropriate for a mode. The type argument provides the helper namespace (see also registerHelper ), in which the value will be looked up. The key that is used depends on the mode active at the given position. If the mode object contains a property with the same name as the type argument, that is tried first. Next, the mode’s helperType , if any, is tried. And finally, the mode’s name. cm.getStateAfter(?line: integer, ?precise: boolean) в†’ object Returns the mode’s parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line. precise is defined as in getTokenAt() .

Miscellaneous methods

Static properties


The CodeMirror object itself provides several useful properties.

CodeMirror.version: string It contains a string that indicates the version of the library. This is a triple of integers «major.minor.patch» , where patch is zero for releases, and something else (usually one) for dev snapshots. CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object) The method provides another way to initialize an editor. It takes a textarea DOM node as first argument and an optional configuration object as second. It will replace the textarea with a CodeMirror instance, and wire up the form of that textarea (if any) to make sure the editor contents are put into the textarea when the form is submitted. The text in the textarea will provide the content for the editor. A CodeMirror instance created this way has three additional methods: cm.save() Copy the content of the editor into the textarea. cm.toTextArea() Remove the editor, and restore the original textarea (with the editor’s current content). cm.getTextArea() в†’ TextAreaElement Returns the textarea that the instance was based on. CodeMirror.defaults: object An object containing default values for all options. You can assign to its properties to modify defaults (though this won’t affect editors that have already been created). CodeMirror.defineExtension(name: string, value: any) If you want to define extra methods in terms of the CodeMirror API, it is possible to use defineExtension . This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on. CodeMirror.defineDocExtension(name: string, value: any) Like defineExtension , but the method will be added to the interface for Doc objects instead. CodeMirror.defineOption(name: string, default: any, updateFunc: function) Similarly, defineOption can be used to define new options for CodeMirror. The updateFunc will be called with the editor instance and the new value when an editor is initialized, and whenever the option is modified through setOption . CodeMirror.defineInitHook(func: function) If your extention just needs to run some code whenever a CodeMirror instance is initialized, use CodeMirror.defineInitHook . Give it a function as its only argument, and from then on, that function will be called (with the instance as argument) whenever a new CodeMirror instance is initialized. CodeMirror.registerHelper(type: string, name: string, value: helper) Registers a helper value with the given name in the given namespace ( type ). This is used to define functionality that may be looked up by mode. Will create (if it doesn’t already exist) a property on the CodeMirror object for the given type , pointing to an object that maps names to values. I.e. after doing CodeMirror.registerHelper(«hint», «foo», myFoo) , the value CodeMirror.hint.foo will point to myFoo . CodeMirror.Pos(line: integer, ?ch: integer) A constructor for the objects that are used to represent positions in editor documents. CodeMirror.changeEnd(change: object) в†’ Utility function that computes an end position from a change (an object with from , to , and text properties, as passed to various event handlers). The returned position will be the end of the changed range, after the change is applied.

Addons

The addon directory in the distribution contains a number of reusable components that implement extra editor functionality. In brief, they are:

dialog/dialog.js Provides a very simple way to query users for text input. Adds an openDialog method to CodeMirror instances, which can be called with an HTML fragment or a detached DOM node that provides the prompt (should include an input tag), and a callback function that is called when text has been entered. Also adds an openNotification function that simply shows an HTML fragment as a notification. Depends on addon/dialog/dialog.css . search/searchcursor.js Adds the getSearchCursor(query, start, caseFold) в†’ cursor method to CodeMirror instances, which can be used to implement search/replace functionality. query can be a regular expression or a string (only strings will match across lines—if they contain newlines). start provides the starting position of the search. It can be a object, or can be left off to default to the start of the document. caseFold is only relevant when matching a string. It will cause the search to be case-insensitive. A search cursor has the following methods: findNext() в†’ boolean findPrevious() в†’ boolean Search forward or backward from the current position. The return value indicates whether a match was found. If matching a regular expression, the return value will be the array returned by the match method, in case you want to extract matched groups. from() в†’ to() в†’ These are only valid when the last call to findNext or findPrevious did not return false. They will return objects pointing at the start and end of the match. replace(text: string) Replaces the currently found match with the given text and adjusts the cursor position to reflect the replacement. search/search.js Implements the search commands. CodeMirror has keys bound to these by default, but will not do anything with them unless an implementation is provided. Depends on searchcursor.js , and will make use of openDialog when available to make prompting for search queries less ugly. edit/matchbrackets.js Defines an option matchBrackets which, when set to true, causes matching brackets to be highlighted whenever the cursor is next to them. It also adds a method matchBrackets that forces this to happen once, and a method findMatchingBracket that can be used to run the bracket-finding algorithm that this uses internally. edit/closebrackets.js Defines an option autoCloseBrackets that will auto-close brackets and quotes when typed. By default, it’ll auto-close ()[]<>»»» , but you can pass it a string similar to that (containing pairs of matching characters), or an object with pairs and optionally explode properties to customize it. explode should be a similar string that gives the pairs of characters that, when enter is pressed between them, should have the second character also moved to its own line. Demo here. edit/matchtags.js Defines an option matchTags that, when enabled, will cause the tags around the cursor to be highlighted (using the CodeMirror-matchingtag class). Also defines a command toMatchingTag , which you can bind a key to in order to jump to the tag mathing the one under the cursor. Depends on the addon/fold/xml-fold.js addon. Demo here.edit/trailingspace.js Adds an option showTrailingSpace which, when enabled, adds the CSS class cm-trailingspace to stretches of whitespace at the end of lines. The demo has a nice squiggly underline style for this class. edit/closetag.js Provides utility functions for adding automatic tag closing to XML modes. See the demo. edit/continuelist.js Markdown specific. Defines a «newlineAndIndentContinueMarkdownList» command command that can be bound to enter to automatically insert the leading characters for continuing a list. See the Markdown mode demo. comment/comment.js Addon for commenting and uncommenting code. Adds three methods to CodeMirror instances: lineComment(from: , to: , ?options: object) Set the lines in the given range to be line comments. Will fall back to blockComment when no line comment style is defined for the mode. blockComment(from: , to: , ?options: object) Wrap the code in the given range in a block comment. Will fall back to lineComment when no block comment style is defined for the mode. uncomment(from: , to: , ?options: object) в†’ boolean Try to uncomment the given range. Returns true if a comment range was found and removed, false otherwise. The options object accepted by these methods may have the following properties: blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string Override the comment string properties of the mode with custom comment strings. padding: string A string that will be inserted after opening and before closing comment markers. Defaults to a single space. commentBlankLines: boolean Whether, when adding line comments, to also comment lines that contain only whitespace. indent: boolean When adding line comments and this is turned on, it will align the comment block to the current indentation of the first line of the block. fullLines: boolean When block commenting, this controls whether the whole lines are indented, or only the precise range that is given. Defaults to true . The addon also defines a toggleComment command, which will try to uncomment the current selection, and if that fails, line-comments it. fold/foldcode.js Helps with code folding. Adds a foldCode method to editor instances, which will try to do a code fold starting at the given line, or unfold the fold that is already present. The method takes as first argument the position that should be folded (may be a line number or a Pos ), and as second optional argument either a range-finder function, or an options object, supporting the following properties: rangeFinder: fn(CodeMirror, Pos) The function that is used to find foldable ranges. If this is not directly passed, it will call getHelper with a «fold» type to find one that’s appropriate for the mode. There are files in the addon/fold/ directory providing CodeMirror.fold.brace , which finds blocks in brace languages (JavaScript, C, Java, etc), CodeMirror.fold.indent , for languages where indentation determines block structure (Python, Haskell), and CodeMirror.fold.xml , for XML-style languages, and CodeMirror.fold.comment , for folding comment blocks. widget: string|Element The widget to show for folded ranges. Can be either a string, in which case it’ll become a span with class CodeMirror-foldmarker , or a DOM node. scanUp: boolean When true (default is false), the addon will try to find foldable ranges on the lines above the current one if there isn’t an eligible one on the given line. minFoldSize: integer The minimum amount of lines that a fold should span to be accepted. Defaults to 0, which also allows single-line folds. See the demo for an example. fold/foldgutter.js Provides an option foldGutter , which can be used to create a gutter with markers indicating the blocks that can be folded. Create a gutter using the gutters option, giving it the class CodeMirror-foldgutter or something else if you configure the addon to use a different class, and this addon will show markers next to folded and foldable blocks, and handle clicks in this gutter. Note that CSS styles should be applied to make the gutter, and the fold markers within it, visible. A default set of CSS styles are available in: addon/fold/foldgutter.css . The option can be either set to true , or an object containing the following optional option fields: gutter: string The CSS class of the gutter. Defaults to «CodeMirror-foldgutter» . You will have to style this yourself to give it a width (and possibly a background). See the default gutter style rules above. indicatorOpen: string | Element A CSS class or DOM element to be used as the marker for open, foldable blocks. Defaults to «CodeMirror-foldgutter-open» . indicatorFolded: string | Element A CSS class or DOM element to be used as the marker for folded blocks. Defaults to «CodeMirror-foldgutter-folded» . rangeFinder: fn(CodeMirror, Pos) The range-finder function to use when determining whether something can be folded. When not given, getHelper will be used to determine a default. Demo here. runmode/runmode.js Can be used to run a CodeMirror mode over text without actually opening an editor instance. See the demo for an example. There are alternate versions of the file avaible for running stand-alone (without including all of CodeMirror) and for running under node.js. runmode/colorize.js Provides a convenient way to syntax-highlight code snippets in a webpage. Depends on the runmode addon (or its standalone variant). Provides a CodeMirror.colorize function that can be called with an array (or other array-ish collection) of DOM nodes that represent the code snippets. By default, it’ll get all pre tags. Will read the data-lang attribute of these nodes to figure out their language, and syntax-color their content using the relevant CodeMirror mode (you’ll have to load the scripts for the relevant modes yourself). A second argument may be provided to give a default mode, used when no language attribute is found for a node. Used in this manual to highlight example code. mode/overlay.js Mode combinator that can be used to extend a mode with an ‘overlay’ — a secondary mode is run over the stream, along with the base mode, and can color specific pieces of text without interfering with the base mode. Defines CodeMirror.overlayMode , which is used to create such a mode. See this demo for a detailed example. mode/multiplex.js Mode combinator that can be used to easily ‘multiplex’ between several modes. Defines CodeMirror.multiplexingMode which, when given as first argument a mode object, and as other arguments any number of objects, will return a mode object that starts parsing using the mode passed as first argument, but will switch to another mode as soon as it encounters a string that occurs in one of the open fields of the passed objects. When in a sub-mode, it will go back to the top mode again when the close string is encountered. Pass «\n» for open or close if you want to switch on a blank line.

  • When delimStyle is specified, it will be the token style returned for the delimiter tokens.
  • When innerStyle is specified, it will be the token style added for each inner mode token.

The outer mode will not see the content between the delimiters. See this demo for an example. hint/show-hint.js Provides a framework for showing autocompletion hints. Defines CodeMirror.showHint , which takes a CodeMirror instance, a hinting function, and optionally an options object, and pops up a widget that allows the user to select a completion. Hinting functions are function that take an editor instance and an optional options object, and return a object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as objects. If no hinting function is given, the addon will try to use getHelper with the «hint» type to find one. When completions aren’t simple strings, they should be objects with the folowing properties: text: string The completion text. This is the only required property. displayText: string The text that should be displayed in the menu. className: string A CSS class name to apply to the completion’s line in the menu. render: fn(Element, self, data) A method used to create the DOM structure for showing the completion by appending it to its first argument. hint: fn(CodeMirror, self, data) A method used to actually apply the completion, instead of the default behavior. The plugin understands the following options (the options object will also be passed along to the hinting function, which may understand additional options): async: boolean When set to true, the hinting function’s signature should be (cm, callback, ?options) , and the completion interface will only be popped up when the hinting function calls the callback, passing it the object holding the completions. completeSingle: boolean Determines whether, when only a single completion is available, it is completed without showing the dialog. Defaults to true. alignWithWord: boolean Whether the pop-up should be horizontally aligned with the start of the word (true, default), or with the cursor (false). closeOnUnfocus: boolean When enabled (which is the default), the pop-up will close when the editor is unfocused. customKeys: keymap Allows you to provide a custom keymap of keys to be active when the pop-up is active. The handlers will be called with an extra argument, a handle to the completion menu, which has moveFocus(n) , setFocus(n) , pick() , and close() methods (see the source for details), that can be used to change the focused element, pick the current element or close the menu. extraKeys: keymap Like customKeys above, but the bindings will be added to the set of default bindings, instead of replacing them. The following events will be fired on the completions object during completion: «shown» () Fired when the pop-up is shown. «select» (completion, Element) Fired when a completion is selected. Passed the completion value (string or object) and the DOM node that represents it in the menu. «close» () Fired when the completion is finished. This addon depends styles from addon/hint/show-hint.css . Check out the demo for an example. hint/javascript-hint.js Defines a simple hinting function for JavaScript ( CodeMirror.hint.javascript ) and CoffeeScript ( CodeMirror.hint.coffeescript ) code. This will simply use the JavaScript environment that the editor runs in as a source of information about objects and their properties. hint/xml-hint.js Defines CodeMirror.hint.xml , which produces hints for XML tagnames, attribute names, and attribute values, guided by a schemaInfo option (a property of the second argument passed to the hinting function, or the third argument passed to CodeMirror.showHint ).
The schema info should be an object mapping tag names to information about these tags, with optionally a «!top» property containing a list of the names of valid top-level tags. The values of the properties should be objects with optional properties children (an array of valid child element names, omit to simply allow all tags to appear) and attrs (an object mapping attribute names to null for free-form attributes, and an array of valid values for restricted attributes). Demo here.hint/html-hint.js Provides schema info to the xml-hint addon for HTML documents. Defines a schema object CodeMirror.htmlSchema that you can pass to as a schemaInfo option, and a CodeMirror.hint.html hinting function that automatically calls CodeMirror.hint.xml with this schema data. See the demo. hint/css-hint.js A minimal hinting function for CSS code. Defines CodeMirror.hint.css . hint/python-hint.js A very simple hinting function for Python code. Defines CodeMirror.hint.python . hint/anyword-hint.js A very simple hinting function ( CodeMirror.hint.anyword ) that simply looks for words in the nearby code and completes to those. Takes two optional options, word , a regular expression that matches words (sequences of one or more character), and range , which defines how many lines the addon should scan when completing (defaults to 500). hint/sql-hint.js A simple SQL hinter. Defines CodeMirror.hint.sql . hint/pig-hint.js A simple hinter for Pig Latin. Defines CodeMirror.hint.pig . search/match-highlighter.js Adds a highlightSelectionMatches option that can be enabled to highlight all instances of a currently selected word. Can be set either to true or to an object containing the following options: minChars , for the minimum amount of selected characters that triggers a highlight (default 2), style , for the style to be used to highlight the matches (default «matchhighlight» , which will correspond to CSS class cm-matchhighlight ), and showToken which can be set to true or to a regexp matching the characters that make up a word. When enabled, it causes the current word to be highlighted when nothing is selected (defaults to off). Demo here. lint/lint.js Defines an interface component for showing linting warnings, with pluggable warning sources (see json-lint.js , javascript-lint.js , and css-lint.js in the same directory). Defines a lint option that can be set to a warning source (for example CodeMirror.lint.javascript ), or to true , in which case getHelper with type «lint» is used to determined a validator function. Depends on addon/lint/lint.css . A demo can be found here. selection/mark-selection.js Causes the selected text to be marked with the CSS class CodeMirror-selectedtext when the styleSelectedText option is enabled. Useful to change the colour of the selection (in addition to the background), like in this demo. selection/active-line.js Defines a styleActiveLine option that, when enabled, gives the wrapper of the active line the class CodeMirror-activeline , and adds a background with the class CodeMirror-activeline-background . is enabled. See the demo. mode/loadmode.js Defines a CodeMirror.requireMode(modename, callback) function that will try to load a given mode and call the callback when it succeeded. You’ll have to set CodeMirror.modeURL to a string that mode paths can be constructed from, for example «mode/%N/%N.js» —the %N ‘s will be replaced with the mode name. Also defines CodeMirror.autoLoadMode(instance, mode) , which will ensure the given mode is loaded and cause the given editor instance to refresh its mode when the loading succeeded. See the demo. comment/continuecomment.js Adds an continueComments option, which can be set to true to have the editor prefix new lines inside C-like block comments with an asterisk when Enter is pressed. It can also be set to a string in order to bind this functionality to a specific key.. display/placeholder.js Adds a placeholder option that can be used to make text appear in the editor when it is empty and not focused. Also gives the editor a CodeMirror-empty CSS class whenever it doesn’t contain any text. See the demo. display/fullscreen.js Defines an option fullScreen that, when set to true , will make the editor full-screen (as in, taking up the whole browser window). Depends on fullscreen.css . Demo here. wrap/hardwrap.js Addon to perform hard line wrapping/breaking for paragraphs of text. Adds these methods to editor instances: wrapParagraph(?pos: , ?options: object) Wraps the paragraph at the given position. If pos is not given, it defaults to the cursor position. wrapRange(from: , to: , ?options: object) Wraps the given range as one big paragraph. wrapParagraphsInRange(from: , to: , ?options: object) Wrapps the paragraphs in (and overlapping with) the given range individually. The following options are recognized: paragraphStart, paragraphEnd: RegExp Blank lines are always considered paragraph boundaries. These options can be used to specify a pattern that causes lines to be considered the start or end of a paragraph. column: number The column to wrap at. Defaults to 80. wrapOn: RegExp A regular expression that matches only those two-character strings that allow wrapping. By default, the addon wraps on whitespace and after dash characters. killTrailingSpace: boolean Whether trailing space caused by wrapping should be preserved, or deleted. Defaults to true. A demo of the addon is available here. merge/merge.js Implements an interface for merging changes, using either a 2-way or a 3-way view. The CodeMirror.MergeView constructor takes arguments similar to the CodeMirror constructor, first a node to append the interface to, and then an options object. Two extra optional options are recognized, origLeft and origRight , which may be strings that provide original versions of the document, which will be shown to the left and right of the editor in non-editable CodeMirror instances. The merge interface will highlight changes between the editable document and the original(s) (demo). tern/tern.js Provides integration with the Tern JavaScript analysis engine, for completion, definition finding, and minor refactoring help. See the demo for a very simple integration. For more involved scenarios, see the comments at the top of the addon and the implementation of the (multi-file) demonstration on the Tern website.

Writing CodeMirror Modes

Modes typically consist of a single JavaScript file. This file defines, in the simplest case, a lexer (tokenizer) for your language—a function that takes a character stream as input, advances it past a token, and returns a style for that token. More advanced modes can also handle indentation for the language.

The mode script should call CodeMirror.defineMode to register itself with CodeMirror. This function takes two arguments. The first should be the name of the mode, for which you should use a lowercase string, preferably one that is also the name of the files that define the mode (i.e. «xml» is defined in xml.js ). The second argument should be a function that, given a CodeMirror configuration object (the thing passed to the CodeMirror function) and an optional mode configuration object (as in the mode option), returns a mode object.

Typically, you should use this second argument to defineMode as your module scope function (modes should not leak anything into the global scope!), i.e. write your whole mode inside this function.

The main responsibility of a mode script is parsing the content of the editor. Depending on the language and the amount of functionality desired, this can be done in really easy or extremely complicated ways. Some parsers can be stateless, meaning that they look at one element (token) of the code at a time, with no memory of what came before. Most, however, will need to remember something. This is done by using a state object, which is an object that is always passed when reading a token, and which can be mutated by the tokenizer.

Modes that use a state must define a startState method on their mode object. This is a function of no arguments that produces a state object to be used at the start of a document.

The most important part of a mode object is its token(stream, state) method. All modes must define this method. It should read one token from the stream it is given as an argument, optionally update its state, and return a style string, or null for tokens that do not have to be styled. For your styles, you are encouraged to use the ‘standard’ names defined in the themes (without the cm- prefix). If that fails, it is also possible to come up with your own and write your own CSS theme file.

A typical token string would be «variable» or «comment» . Multiple styles can be returned (separated by spaces), for example «string error» for a thing that looks like a string but is invalid somehow (say, missing its closing quote). When a style is prefixed by «line-» or «line-background-» , the style will be applied to the whole line, analogous to what the addLineClass method does—styling the «text» in the simple case, and the «background» element when «line-background-» is prefixed.

The stream object that’s passed to token encapsulates a line of code (tokens may never span lines) and our current position in that line. It has the following API:

eol() в†’ boolean Returns true only if the stream is at the end of the line. sol() в†’ boolean Returns true only if the stream is at the start of the line. peek() в†’ string Returns the next character in the stream without advancing it. Will return an null at the end of the line. next() в†’ string Returns the next character in the stream and advances it. Also returns null when no more characters are available. eat(match: string|regexp|function(char: string) в†’ boolean) в†’ string match can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream ‘matches’ the given argument, it is consumed and returned. Otherwise, undefined is returned. eatWhile(match: string|regexp|function(char: string) в†’ boolean) в†’ boolean Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten. eatSpace() в†’ boolean Shortcut for eatWhile when matching white-space. skipToEnd() Moves the position to the end of the line. skipTo(ch: string) в†’ boolean Skips to the next occurrence of the given character, if found on the current line (doesn’t advance the stream if the character does not occur on the line). Returns true if the character was found. match(pattern: string, ?consume: boolean, ?caseFold: boolean) в†’ boolean match(pattern: regexp, ?consume: boolean) в†’ array Act like a multi-character eat —if consume is true or not given—or a look-ahead that doesn’t update the stream position—if it is false. pattern can be either a string or a regular expression starting with ^ . When it is a string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by match , in case you need to extract matched groups. backUp(n: integer) Backs up the stream n characters. Backing it up further than the start of the current token will cause things to break, so be careful. column() в†’ integer Returns the column (taking into account tabs) at which the current token starts. indentation() в†’ integer Tells you how far the current line has been indented, in spaces. Corrects for tab characters. current() в†’ string Get the string between the start of the current token and the current stream position.

By default, blank lines are simply skipped when tokenizing a document. For languages that have significant blank lines, you can define a blankLine(state) method on your mode that will get called whenever a blank line is passed over, so that it can update the parser state.

Because state object are mutated, and CodeMirror needs to keep valid versions of a state around so that it can restart a parse at any line, copies must be made of state objects. The default algorithm used is that a new state object is created, which gets all the properties of the old object. Any properties which hold arrays get a copy of these arrays (since arrays tend to be used as mutable stacks). When this is not correct, for example because a mode mutates non-array properties of its state object, a mode object should define a copyState method, which is given a state and should return a safe copy of that state.

If you want your mode to provide smart indentation (through the indentLine method and the indentAuto and newlineAndIndent commands, to which keys can be bound), you must define an indent(state, textAfter) method on your mode object.

The indentation method should inspect the given state object, and optionally the textAfter string, which contains the text on the line that is being indented, and return an integer, the amount of spaces to indent. It should usually take the indentUnit option into account. An indentation method may return CodeMirror.Pass to indicate that it could not come up with a precise indentation.

To work well with the commenting addon, a mode may define lineComment (string that starts a line comment), blockCommentStart , blockCommentEnd (strings that start and end block comments), and blockCommentLead (a string to put at the start of continued lines in a block comment). All of these are optional.

Finally, a mode may define an electricChars property, which should hold a string containing all the characters that should trigger the behaviour described for the electricChars option.

So, to summarize, a mode must provide a token method, and it may provide startState , copyState , and indent methods. For an example of a trivial mode, see the diff mode, for a more involved example, see the C-like mode.

Sometimes, it is useful for modes to nest—to have one mode delegate work to another mode. An example of this kind of mode is the mixed-mode HTML mode. To implement such nesting, it is usually necessary to create mode objects and copy states yourself. To create a mode object, there are CodeMirror.getMode(options, parserConfig) , where the first argument is a configuration object as passed to the mode constructor function, and the second argument is a mode specification as in the mode option. To copy a state object, call CodeMirror.copyState(mode, state) , where mode is the mode that created the given state.

In a nested mode, it is recommended to add an extra method, innerMode which, given a state object, returns a object with the inner mode and its state for the current position. These are used by utility scripts such as the tag closer to get context information. Use the CodeMirror.innerMode helper function to, starting from a mode and a state, recursively walk down to the innermost mode and state.

To make indentation work properly in a nested parser, it is advisable to give the startState method of modes that are intended to be nested an optional argument that provides the base indentation for the block of code. The JavaScript and CSS parser do this, for example, to allow JavaScript and CSS code inside the mixed-mode HTML mode to be properly indented.

CodeMirror показать 2 прокрутки

Я хочу использовать CodeMirror в своем проекте. Это загрузка, но редактор показывает 2 прокрутки, одну справа CodeMirror и одну слева css overflow-y: scroll . Это проблема, потому что направление страницы или что-то еще?
Как устранить эту проблему или отключить один из свитков?

1 ответ

Я нашел решение! Проблема из-за направления страницы. Исправляю проблему с change CodeMirror css и заменяю right:0 на left:0 in .CodeMirror-scrollbar css class.

CodeMirror показать 2 прокрутки

Я хочу использовать CodeMirror в своем проекте. Это загрузка, но редактор показывает 2 прокрутки, одну справа CodeMirror и одну слева css overflow-y: scroll . Это проблема, потому что направление страницы или что-то еще?
Как устранить эту проблему или отключить один из свитков?

1 ответ

Я нашел решение! Проблема из-за направления страницы. Исправляю проблему с change CodeMirror css и заменяю right:0 на left:0 in .CodeMirror-scrollbar css class.

Цукерберг рекомендует:  Верстка - Работа верстальщика
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих