|
|
咆哮的冰棍 · 知立市公園グランド紹介/知立市 ...· 3 月前 · |
|
|
不开心的消防车 · 《扫黑风暴》中的反派,现实都怎么样了?· 4 月前 · |
|
|
善良的煎饼果子 · js 对象数组转单值数组 - CSDN文库· 1 年前 · |
|
|
刚毅的皮带 · No converter found ...· 2 年前 · |
|
|
坚强的伤痕 · 中年夫妻之间,默许以下的事,就是离心了 - 知乎· 2 年前 · |
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.
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:
<script src="lib/codemirror.js"></script> <link rel="stylesheet" href="lib/codemirror.css"> <script src="mode/javascript/javascript.js"></script>
(Alternatively, use a module loader. More about that later. )
Having done this, an editor instance can be created like this:
var myCodeMirror = CodeMirror(document.body);
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:
var myCodeMirror = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
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:
var myCodeMirror = CodeMirror(function(elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});
However, for this use case, which is a common way to use
CodeMirror, the library provides a much more powerful
shortcut:
var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
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.
Module loaders
The files in the CodeMirror distribution contain shims for
loading them (and their dependencies) in AMD or CommonJS
environments. If the variables exports
and module exist and have type object, CommonJS-style
require will be used. If not, but there is a
function define with an amd property
present, AMD-style (RequireJS) will be used.
It is possible to
use Browserify or similar
tools to statically build modules using CodeMirror. Alternatively,
use RequireJS to dynamically
load dependencies at runtime. Both of these approaches have the
advantage that they don't use the global namespace and can, thus,
do things like load multiple versions of CodeMirror alongside each
other.
Here's a simple example of using RequireJS to load CodeMirror:
require([
"cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed"
], function(CodeMirror) {
CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "htmlmixed"
It will automatically load the modes that the mixed HTML mode
depends on (XML, JavaScript, and CSS). Do not use
RequireJS' paths option to configure the path to
CodeMirror, since it will break loading submodules through
relative paths. Use
the packages
configuration option instead, as in:
require.config({
packages: [{
name: "codemirror",
location: "../path/to/codemirror",
main: "lib/codemirror"
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.Docmode: string|objectname property that names the mode (for
example {name: "javascript", json: true}). 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.lineSeparator: string|nullnull), the document will be split on CRLFs
as well as lone CRs and LFs, and a single LF will be used as
line separator in all output (such
as getValue). When a
specific string is given, lines will only be split on that
string, and output will, by default, use that same
separator.theme: string.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: integersmartIndent: booleantabSize: integerindentWithTabs: booleantabSize
spaces should be replaced by N tabs. Default is false.electricChars: booleanspecialChars: RegExp/[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/.specialCharPlaceholder: function(char) → ElementspecialChars
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: booleanfalse
on Windows, and true on other platforms.keyMap: string"default", which is the only key map defined
in codemirror.js itself. Extra key maps are found in
the key map directory. See
the section on key maps for more
information.extraKeys: objectkeyMap. Should be
either null, or a valid key map value.lineWrapping: booleanfalse (scroll).lineNumbers: booleanfirstLineNumber: integerlineNumberFormatter: function(line: integer) → stringgutters: array<string>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: booleanscrollbarStyle: string"native", showing native scrollbars. The core
library also provides the "null" style, which
completely hides the
scrollbars. Addons can
implement additional scrollbar models.coverGutterNextToScrollbar: booleanfixedGutter
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.inputStyle: string"textarea"
and "contenteditable" input models. On mobile
browsers, the default is "contenteditable". On
desktop browsers, the default is "textarea".
Support for IME and screen readers is better in
the "contenteditable" model. The intention is to
make it the default on modern desktop browsers in the
future.readOnly: boolean|string"nocursor" is given (instead of
simply true), focusing of the editor is also
disallowed.showCursorWhenSelecting: booleanlineWiseCopyCut: booleanundoDepth: integerhistoryEventDelay: integertabindex: integerautofocus: booleanfromTextArea 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: booleanallowDropFileTypes: array<string>null) only files whose
type is in the array can be dropped into the editor. The strings
should be MIME types, and will be checked against
the type
of the File object as reported by the browser.cursorBlinkRate: numbercursorScrollMargin: numbercursorHeight: number0.85),
which causes the cursor to not reach all the way to the bottom
of the line, looks betterresetSelectionOnContextMenu: booleantrue.workTime, workDelay: numberworkTime 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.pollInterval: numberflattenSpans: booleanaddModeClass: boolean"cm-m-". For example, tokens from the XML mode
will get the cm-m-xml class.maxHighlightLength: numberInfinity to turn off
this behavior.viewportMargin: integerInfinity 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.Various CodeMirror-related objects emit events, which allow
client code to react to various situations. Handlers for such
events can be registered 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)changeObj is a {from, to, text, removed,
origin} 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 {ch:0, line:18} 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. This event is
fired before the end of
an operation, before the DOM updates
happen."changes" (instance: CodeMirror, changes: array<object>)"change"
event, but batched per operation,
passing an array containing all the changes that happened in the
operation. This event is fired after the operation finished, and
display changes it makes will trigger a new operation."beforeChange" (instance: CodeMirror, changeObj: object)changeObj object
has from, to, and text
properties, as with
the "change" event. 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)"keyHandled" (instance: CodeMirror, name: string, event: Event)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)"electricInput" (instance: CodeMirror, line: integer)"beforeSelectionChange" (instance: CodeMirror, obj: {ranges, origin, update}){anchor, head} objects in
the ranges property of the obj
argument, and optionally change them by calling
the update method on this object, passing an array
of ranges in the same format. The object also contains
an origin property holding the origin string passed
to the selection-changing method, if any. 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)from and to arguments
give the new start and end of the viewport."swapDoc" (instance: CodeMirror, oldDoc: Doc)swapDoc
method."gutterClick" (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)mousedown event object as
fourth argument."gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)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)"blur" (instance: CodeMirror)"scroll" (instance: CodeMirror)"scrollCursorIntoView" (instance: CodeMirror, event: Event)preventDefault method called, CodeMirror will
not itself try to scroll the window."update" (instance: CodeMirror)"renderLine" (instance: CodeMirror, line: LineHandle, element: Element)"mousedown",
"dblclick", "touchstart", "contextmenu",
"keydown", "keypress",
"keyup", "cut", "copy", "paste",
"dragstart", "dragenter",
"dragover", "dragleave",
"drop"
(instance: CodeMirror, event: Event)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)changeObj has a similar type as the
object passed to the
editor's "change"
event."beforeChange" (doc: CodeMirror.Doc, change: object)"cursorActivity" (doc: CodeMirror.Doc)"beforeSelectionChange" (doc: CodeMirror.Doc, selection: {head, anchor})Line handles (as returned by, for
example, getLineHandle)
support these events:
"delete" ()"change" (line: LineHandle, changeObj: object)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" ()"clear" (from: {line, ch}, to: {line, ch})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" ()"unhide" ()Line widgets (CodeMirror.LineWidget), returned
by addLineWidget, fire
these events:
"redraw" ()Key maps are ways to associate keys with functionality. A key map is an object mapping strings that identify the keys to functions that implement their functionality.
The CodeMirror distributions comes with Emacs, Vim, and Sublime Text-style keymaps.
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- 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.
editor.setOption("extraKeys", { Tab: function(cm) { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces);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.
Multi-stroke key bindings can be specified
by separating the key names by spaces in the property name, for
example Ctrl-X Ctrl-V. When a map contains
multi-stoke bindings or keys with modifiers that are not specified
in the default order (Shift-Cmd-Ctrl-Alt), you must
call CodeMirror.normalizeKeyMap on it before it can
be used. This function takes a keymap and modifies it to normalize
modifier order and properly recognize multi-stroke bindings. It
will return the keymap itself.
The CodeMirror.keyMap object associates key maps
with names. User code and key map definitions can assign extra
properties to this object. Anywhere where a key map is expected, a
string can be given, which will be looked up in this object. It
also contains the "default" key map holding the
default bindings.
The values of properties in key maps can be either functions of
a single argument (the CodeMirror instance), strings, or
false. Strings refer
to commands, which are described below. 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" or to functions that have a
truthy motion property (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.
Key maps 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 key map or an array of
key maps.
When a key map needs to set something up when it becomes
active, or tear something down when deactivated, it can
contain attach and/or detach properties,
which should hold functions that take the editor instance and the
next or previous keymap. Note that this only works for the
top-level keymap, not for fallthrough
maps or maps added
with extraKeys
or addKeyMap.
Commands are parameter-less actions that can be performed on an
editor. Their main use is for key bindings. Commands are defined by
adding properties to the CodeMirror.commands object.
A number of common commands are defined by the library itself,
most of them used by the default key bindings. The value of a
command property must be a function of one argument (an editor
instance).
Some of the commands below are referenced in the default key map, but not defined by the core library. These are intended to be defined by user code or addons.
Commands can also be run with
the execCommand
method.
selectAllCtrl-A (PC), Cmd-A (Mac)singleSelectionEsckillLineCtrl-K (Mac)deleteLineCtrl-D (PC), Cmd-D (Mac)delLineLeftdelWrappedLineLeftCmd-Backspace (Mac)delWrappedLineRightCmd-Delete (Mac)undoCtrl-Z (PC), Cmd-Z (Mac)redoCtrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)undoSelectionCtrl-U (PC), Cmd-U (Mac)redoSelectionAlt-U (PC), Shift-Cmd-U (Mac)goDocStartCtrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)goDocEndCtrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)goLineStartAlt-Left (PC), Ctrl-A (Mac)goLineStartSmartHomegoLineEndAlt-Right (PC), Ctrl-E (Mac)goLineRightCmd-Right (Mac)goLineLeftCmd-Left (Mac)goLineLeftSmartgoLineStartSmart.goLineUpUp, Ctrl-P (Mac)goLineDownDown, Ctrl-N (Mac)goPageUpPageUp, Shift-Ctrl-V (Mac)goPageDownPageDown, Ctrl-V (Mac)goCharLeftLeft, Ctrl-B (Mac)goCharRightRight, Ctrl-F (Mac)goColumnLeftgoColumnRightgoWordLeftAlt-B (Mac)goWordRightAlt-F (Mac)goGroupLeftCtrl-Left (PC), Alt-Left (Mac)goGroupRightCtrl-Right (PC), Alt-Right (Mac)delCharBeforeShift-Backspace, Ctrl-H (Mac)delCharAfterDelete, Ctrl-D (Mac)delWordBeforeAlt-Backspace (Mac)delWordAfterAlt-D (Mac)delGroupBeforeCtrl-Backspace (PC), Alt-Backspace (Mac)delGroupAfterCtrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)indentAutoShift-TabindentMoreCtrl-] (PC), Cmd-] (Mac)indentLessCtrl-[ (PC), Cmd-[ (Mac)insertTabinsertSoftTabdefaultTabTabtransposeCharsCtrl-T (Mac)newlineAndIndentEntertoggleOverwriteInsertsaveCtrl-S (PC), Cmd-S (Mac)findCtrl-F (PC), Cmd-F (Mac)findNextCtrl-G (PC), Cmd-G (Mac)findPrevShift-Ctrl-G (PC), Shift-Cmd-G (Mac)replaceShift-Ctrl-F (PC), Cmd-Alt-F (Mac)replaceAllShift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)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:
CodeMirrorheight style to auto will
make the editor resize to fit its
content (it is recommended to also set
the viewportMargin
option to Infinity when doing this.CodeMirror-focusedCodeMirror-guttersCodeMirror-linenumbersCodeMirror-linenumberCodeMirror-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-linesCodeMirror-cursorCodeMirror-selectedspan elements
with this class.CodeMirror-matchingbracket,
CodeMirror-nonmatchingbracketIf 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.
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.
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.
doc.getValue(?separator: string) → string"\n").doc.setValue(content: string)doc.getRange(from: {line, ch}, to: {line, ch}, ?separator: string) → string{line, ch} objects. An optional third
argument can be given to indicate the line separator string to
use (defaults to "\n").doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)from
and to with the given string. from
and to must be {line, ch}
objects. to can be left off to simply insert the
string at position from. When origin
is given, it will be passed on
to "change" events, and
its first letter will be used to determine whether this change
can be merged with previous history events, in the way described
for selection origins.doc.getLine(n: integer) → stringn.doc.lineCount() → integerdoc.firstLine() → integerdoc.lastLine() → integerdoc.lineCount() - 1,
but for linked sub-views,
it might return other values.doc.getLineHandle(num: integer) → LineHandledoc.getLineNumber(handle: LineHandle) → integernull when it is no longer in the
document).doc.eachLine(f: (line: LineHandle))doc.eachLine(start: integer, end: integer, f: (line: LineHandle))start
and end line numbers are given, the range
from start up to (not including) end,
and call f for each line, passing the line handle.
This is a faster way to visit a range of line handlers than
calling getLineHandle
for each of them. Note that line handles have
a text property containing the line's content (as a
string).doc.markClean()changeGeneration,
which allows multiple subsystems to track different notions of
cleanness without interfering.doc.changeGeneration(?closeEvent: boolean) → integerisClean to test whether
any edits were made (and not undone) in the meantime.
If closeEvent is true, the current history event
will be ‘closed’, meaning it can't be combined with further
changes (rapid typing or deleting events are typically
combined).doc.isClean(?generation: integer) → booleanmarkClean if no
argument is passed, or since the matching call
to changeGeneration
if a generation value is given.doc.getSelection(?lineSep: string) → stringlineSep in between.doc.getSelections(?lineSep: string) → array<string>doc.replaceSelection(replacement: string, ?select: string)select argument can be used to change
this—passing "around" will cause the new text to be
selected, passing "start" will collapse the
selection to the start of the inserted text.doc.replaceSelections(replacements: array<string>, ?select: string)select argument works the same as
in replaceSelection.doc.getCursor(?start: string) → {line, ch}start is an optional string indicating
which end of the selection to return. It may
be "from", "to", "head"
(the side of the selection that moves when you press
shift+arrow), or "anchor" (the fixed side of the
selection). Omitting the argument is the same as
passing "head". A {line, ch} object
will be returned.doc.listSelections() → array<{anchor, head}>anchor
and head properties referring to {line,
ch} objects.doc.somethingSelected() → booleandoc.setCursor(pos: {line, ch}|number, ?ch: number, ?options: object){line, ch} object, or the line and the
character as two separate parameters. Will replace all
selections with a single, empty selection at the given position.
The supported options are the same as for setSelection.doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)anchor
and head should be {line, ch}
objects. head defaults to anchor when
not given. These options are supported:
scroll: booleanorigin: string+, and the last recorded selection had
the same origin and was similar (close
in time, both
collapsed or both non-collapsed), the new one will replace the
old one. When it starts with *, it will always
replace the previous event (if that had the same origin).
Built-in motion uses the "+move" origin. User input uses the "+input" origin.bias: numberdoc.setSelections(ranges: array<{anchor, head}>, ?primary: integer, ?options: object)primary is a
number, it determines which selection is the primary one. When
it is not given, the primary index is taken from the previous
selection, or set to the last range if the previous selection
had less ranges than the new one. Supports the same options
as setSelection.doc.addSelection(anchor: {line, ch}, ?head: {line, ch})doc.extendSelection(from: {line, ch}, ?to: {line, ch}, ?options: object)setSelection, but
will, if shift is held or
the extending flag is set, move the
head of the selection while leaving the anchor at its current
place. to is optional, and can be passed to ensure
a region (for example a word or paragraph) will end up selected
(in addition to whatever lies between that region and the
current anchor). When multiple selections are present, all but
the primary selection will be dropped by this method.
Supports the same options as setSelection.doc.extendSelections(heads: array<{line, ch}>, ?options: object)extendSelection
that acts on all selections at once.doc.extendSelectionsBy(f: function(range: {anchor, head}) → {line, ch}), ?options: object)extendSelections
on the result.doc.setExtending(value: boolean)extendSelection
to leave the selection anchor in place.doc.getExtending() → booleancm.hasFocus() → booleancm.findPosH(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}start is a {line, ch}
object, amount an integer (may be negative),
and unit one of the
string "char", "column",
or "word". Will return a position that is produced
by moving amount times the distance specified
by unit. When visually is true, motion
in right-to-left text will be visual rather than logical. When
the motion was clipped by hitting the end or start of the
document, the returned value will have a hitSide
property set to true.cm.findPosV(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}findPosH,
but used for vertical motion. unit may
be "line" or "page". The other
arguments and the returned value have the same interpretation as
they have in findPosH.cm.findWordAt(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}cm.setOption(option: string, value: any)option
should the name of an option,
and value should be a valid value for that
option.cm.getOption(option: string) → anycm.addKeyMap(map: object, bottom: boolean)extraKeys
option. Maps added in this way have a higher precedence than
the extraKeys
and keyMap options,
and between them, the maps added earlier have a lower precedence
than those added later, unless the bottom argument
was passed, in which case they end up below other key maps added
with this method.cm.removeKeyMap(map: object)addKeyMap. Either
pass in the key map object itself, or a string, which will be
compared against the name property of the active
key maps.cm.addOverlay(mode: string|object, ?options: object)mode can be a mode
spec or a mode object (an object with
a token method).
The options parameter is optional. If given, it
should be an object. Currently, only the opaque
option is recognized. This defaults to off, but can be given to
allow the overlay styling, when not null, to
override the styling of the base mode entirely, instead of the
two being applied together.cm.removeOverlay(mode: string|object)mode
parameter to addOverlay,
or a string that corresponds to the name property of
that value, to remove an overlay again.cm.on(type: string, func: (...args))CodeMirror.on(object, type, func) version
that allows registering of events on any object.cm.off(type: string, func: (...args))CodeMirror.off(object, type,
func) also exists.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() → Docdoc.getEditor() → CodeMirrornull.cm.swapDoc(doc: CodeMirror.Doc) → Docdoc.copy(copyHistory: boolean) → DoccopyHistory is true, the history will also be
copied. Can not be called directly on an editor.doc.linkedDoc(options: object) → DocsharedHist: booleanfrom: integerto: integermode: string|objectdoc.unlinkDoc(doc: CodeMirror.Doc)doc.iterLinkedDocs(function: (doc: CodeMirror.Doc, sharedHist: boolean))doc.undo()doc.redo()doc.undoSelection()doc.redoSelection()doc.historySize() → {undo: integer, redo: integer}{undo, redo} properties,
both of which hold integers, indicating the amount of stored
undo and redo operations.doc.clearHistory()doc.getHistory() → objectdoc.setHistory(history: object)getHistory. Note that
this will have entirely undefined results if the editor content
isn't also the same as it was when getHistory was
called.doc.markText(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarkerfrom and to should
be {line, ch} objects. The options
parameter is optional. When given, it should be an object that
may contain the following configuration options:
className: stringinclusiveLeft: booleaninclusiveRight: booleaninclusiveLeft,
but for the right side.atomic: booleaninclusiveLeft
and inclusiveRight have a different meaning—they
will prevent the cursor from being placed respectively
directly before and directly after the range.collapsed: booleanclearOnEnter: boolean"clear" event
fired on the range handle can be used to be notified when this
happens.clearWhenEmpty: booleanreplacedWith: ElementhandleMouseEvents: booleanreplacedWith is given, this determines
whether the editor will capture mouse and drag events
occurring in this widget. Default is false—the events will be
left alone for the default browser handler, or specific
handlers on the widget, to capture.readOnly: booleansetValue to reset
the whole document. Note: adding a read-only span
currently clears the undo history of the editor, because
existing undo events being partially nullified by read-only
spans would corrupt the history (in the current
implementation).addToHistory: booleanstartStyle: stringendStyle: stringstartStyle, but for the rightmost span.css: string"color: #fe3".title:
stringtitle attribute with the
given value.shared: booleanshared to true to make the
marker appear in all documents. By default, a marker appears
only in its target document.CodeMirror.TextMarker), which
exposes three methods:
clear(), to remove the mark,
find(), which returns
a {from, to} object (both holding document
positions), indicating the current position of the marked range,
or undefined if the marker is no longer in the
document, and finally changed(),
which you can call if you've done something that might change
the size of the marker (for example changing the content of
a replacedWith
node), and want to cheaply update the display.
doc.setBookmark(pos: {line, ch}, ?options: object) → TextMarkerfind() and clear(). The first
returns the current position of the bookmark, if it is still in
the document, and the second explicitly removes the bookmark.
The options argument is optional. If given, the following
properties are recognized:
widget: ElementreplacedWith
option to markText).insertLeft: booleanshared: booleanmarkText.handleMouseEvents: booleanmarkText,
this determines whether mouse events on the widget inserted
for this bookmark are handled by CodeMirror. The default is
false.doc.findMarks(from: {line, ch}, to: {line, ch}) → array<TextMarker>doc.findMarksAt(pos: {line, ch}) → array<TextMarker>doc.getAllMarks() → array<TextMarker>cm.setGutterMarker(line: integer|LineHandle, gutterID: string, value: Element) → LineHandlegutters option)
to the given value. Value can be either null, to
clear the marker, or a DOM element, to set it. The DOM element
will be shown in the specified gutter next to the specified
line.cm.clearGutter(gutterID: string)doc.addLineClass(line: integer|LineHandle, where: string, class: string) → LineHandleline
can be a number or a line handle. where determines
to which element this class should be applied, can can be one
of "text" (the text element, which lies in front of
the selection), "background" (a background element
that will be behind the selection), "gutter" (the
line's gutter space), or "wrap" (the wrapper node
that wraps all of the line's elements, including gutter
elements). class should be the name of the class to
apply.doc.removeLineClass(line: integer|LineHandle, where: string, class: string) → LineHandleline can be a
line handle or number. where should be one
of "text", "background",
or "wrap"
(see addLineClass). class
can be left off to remove all classes for the specified node, or
be a string to remove only a specific class.cm.lineInfo(line: integer|LineHandle) → object{line, handle, text,
gutterMarkers, textClass, bgClass, wrapClass, widgets},
where gutterMarkers is an object mapping gutter IDs
to marker elements, and widgets is an array
of line widgets attached to this
line, and the various class properties refer to classes added
with addLineClass.cm.addWidget(pos: {line, ch}, node: Element, scrollIntoView: boolean)node, which should be an absolutely
positioned DOM node, into the editor, positioned right below the
given {line, ch} position.
When scrollIntoView is true, the editor will ensure
that the entire node is visible (if possible). To remove the
widget again, simply use DOM methods (move it somewhere else, or
call removeChild on its parent).doc.addLineWidget(line: integer|LineHandle, node: Element, ?options: object) → LineWidgetline should be either an integer or a
line handle, and node should be a DOM node, which
will be displayed below the given line. options,
when given, should be an object that configures the behavior of
the widget. The following options are supported (all default to
false):
coverGutter: booleannoHScroll: booleanabove: booleanhandleMouseEvents: booleaninsertAt: integerline property
pointing at the line handle that it is associated with, and the following methods:
clear()changed()cm.setSize(width: number|string, height: number|string)width and height
can be either numbers (interpreted as pixels) or CSS units
("100%", for example). You can
pass null for either of them to indicate that that
dimension should not be changed.cm.scrollTo(x: number, y: number)null
or undefined to have no effect.cm.getScrollInfo() → {left, top, width, height, clientWidth, clientHeight}{left, top, width, height, clientWidth,
clientHeight} object that represents the current scroll
position, the size of the scrollable area, and the size of the
visible area (minus scrollbars).cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)what may
be null to scroll the cursor into view,
a {line, ch} position to scroll a character into
view, a {left, top, right, bottom} pixel range (in
editor-local coordinates), or a range {from, to}
containing either two character positions or two pixel squares.
The margin parameter is optional. When given, it
indicates the amount of vertical pixels around the given area
that should be made visible as well.cm.cursorCoords(where: boolean|{line, ch}, mode: string) → {left, top, bottom}{left, top, bottom} object
containing the coordinates of the cursor position.
If mode is "local", they will be
relative to the top-left corner of the editable document. If it
is "page" or not given, they are relative to the
top-left corner of the page. If mode
is "window", the coordinates are relative to the
top-left corner of the currently visible (scrolled)
window. where can be a boolean indicating whether
you want the start (true) or the end
(false) of the selection, or, if a {line,
ch} object is given, it specifies the precise position at
which you want to measure.cm.charCoords(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}pos should be a {line, ch}
object. This differs from cursorCoords in that
it'll give the size of the whole character, rather than just the
position that the cursor would have when it would sit at that
position.cm.coordsChar(object: {left, top}, ?mode: string) → {line, ch}{left, top} object, returns
the {line, ch} position that corresponds to it. The
optional mode parameter determines relative to what
the coordinates are interpreted. It may
be "window", "page" (the default),
or "local".cm.lineAtHeight(height: number, ?mode: string) → numbermode can be one of the same strings
that coordsChar
accepts.cm.heightAtLine(line: integer|LineHandle, ?mode: string) → numbermode
(see coordsChar), which
defaults to "page". When a line below the bottom of
the document is specified, the returned value is the bottom of
the last line in the document.cm.defaultTextHeight() → numbercm.defaultCharWidth() → numbercm.getViewport() → {from: number, to: number}{from, to} object indicating the
start (inclusive) and end (exclusive) of the currently rendered
part of the document. In big documents, when most content is
scrolled out of view, CodeMirror will only render the visible
part, and a margin around it. See also
the viewportChange
event.cm.refresh()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() → objectgetOption("mode"), which gives you
the mode specification, rather than the resolved, instantiated
mode object.cm.getModeAt(pos: {line, ch}) → objectgetMode for
simple modes, but will return an inner mode for nesting modes
(such as htmlmixed).cm.getTokenAt(pos: {line, ch}, ?precise: boolean) → object{line, ch} object). The
returned object has the following properties:
startendstringtype"keyword"
or "comment" (may also be null).stateprecise 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.getLineTokens(line: integer, ?precise: boolean) → array<{start, end, string, type, state}>getTokenAt, but
collects all tokens for a given line into an array. It is much
cheaper than repeatedly calling getTokenAt, which
re-parses the part of the line before the token for every call.cm.getTokenTypeAt(pos: {line, ch}) → stringgetTokenAt 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.getHelpers(pos: {line, ch}, type: string) → array<helper>type argument provides
the helper namespace (see
registerHelper), in
which the values will be looked up. When the mode itself has a
property that corresponds to the type, that
directly determines the keys that are used to look up the helper
values (it may be either a single string, or an array of
strings). Failing that, the mode's helperType
property and finally the mode's name are used.fold containing "brace". When
the brace-fold addon is loaded, that defines a
helper named brace in the fold
namespace. This is then used by
the foldcode addon to
figure out that it can use that folding function to fold
JavaScript code.cm.getHelper(pos: {line, ch}, type: string) → helpergetHelpers.cm.getStateAfter(?line: integer, ?precise: boolean) → objectprecise is defined
as in getTokenAt().cm.operation(func: () → any) → anycm.indentLine(line: integer, ?dir: string|integer)"smart") may be one of:
"prev""smart""prev" otherwise."add""subtract"<integer>cm.toggleOverwrite(?value: boolean)cm.isReadOnly() → booleandoc.lineSeparator()null, the
string "\n" is returned.cm.execCommand(name: string)doc.posFromIndex(index: integer) → {line, ch}{line, ch} object for a
zero-based index who's value is relative to the start of the
editor's text. If the index is out of range of the text then
the returned object is clipped to start or end of the text
respectively.doc.indexFromPos(object: {line, ch}) → integerposFromIndex.cm.focus()cm.getInputField() → ElementinputStyle
option.cm.getWrapperElement() → Elementcm.getScrollerElement() → Elementcm.getGutterElement() → ElementThe CodeMirror object itself provides
several useful properties.
CodeMirror.version: string"major.minor.patch",
where patch is zero for releases, and something
else (usually one) for dev snapshots.CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object)cm.save()cm.toTextArea()cm.getTextArea() → TextAreaElementCodeMirror.defaults: objectCodeMirror.defineExtension(name: string, value: any)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)defineExtension,
but the method will be added to the interface
for Doc objects instead.CodeMirror.defineOption(name: string,
default: any, updateFunc: function)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)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)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.registerGlobalHelper(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)registerHelper,
but also registers this helper as 'global', meaning that it will
be included by getHelpers
whenever the given predicate returns true when
called with the local mode and editor.
CodeMirror.Pos(line: integer, ?ch: integer){line, ch} objects that
are used to represent positions in editor documents.CodeMirror.changeEnd(change: object) → {line, ch}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.The addon directory in the distribution contains a
number of reusable components that implement extra editor
functionality (on top of extension functions
like defineOption, defineExtension,
and registerHelper). In
brief, they are:
dialog/dialog.jsopenDialog(template, callback, options) →
closeFunction 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
or button tag), and a callback function that is called
when the user presses enter. It returns a function closeFunction
which, if called, will close the dialog immediately.
openDialog takes the following options:
closeOnEnter:true.onKeyDown:(event, value, closeFunction)
that will be called whenever keydown fires in the
dialog's input. If your callback returns true,
the dialog will not do any further processing of the event.onKeyUp:onKeyDown but for the
keyup event.onInput:onKeyDown but for the
input event.onClose:(dialogInstance)
that will be called after the dialog has been closed and
removed from the DOM. No return value.Also adds an openNotification(template, options) →
closeFunction function that simply shows an HTML
fragment as a notification at the top of the editor. It takes a
single option: duration, the amount of time after
which the notification will be automatically closed. If
duration is zero, the dialog will not be closed automatically.
Depends on addon/dialog/dialog.css.
search/searchcursor.jsgetSearchCursor(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 {line, ch} 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() → booleanfindPrevious() → booleanmatch method, in case you
want to extract matched groups.from() → {line, ch}to() → {line, ch}findNext or findPrevious did
not return false. They will return {line, ch}
objects pointing at the start and end of the match.replace(text: string, ?origin: string)search/search.jssearchcursor.js, and will make use
of openDialog when
available to make prompting for search queries less ugly.search/jump-to-line.jsjumpToLine command and binding Alt-G to it.
Accepts linenumber, +/-linenumber, line:char,
scroll% and :linenumber formats.
This will make use of openDialog
when available to make prompting for line number neater.search/matchesonscrollbar.jsshowMatchesOnScrollbar method to editor
instances, which should be given a query (string or regular
expression), optionally a case-fold flag (only applicable for
strings), and optionally a class name (defaults
to CodeMirror-search-match) as arguments. When
called, matches of the given query will be displayed on the
editor's vertical scrollbar. The method returns an object with
a clear method that can be called to remove the
matches. Depends on
the annotatescrollbar
addon, and
the matchesonscrollbar.css
file provides a default (transparent yellowish) definition of
the CSS class applied to the matches. Note that the matches are
only perfectly aligned if your scrollbar does not have buttons
at the top and bottom. You can use
the simplescrollbar
addon to make sure of this. If this addon is loaded,
the search addon will
automatically use it.edit/matchbrackets.jsmatchBrackets 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.jsautoCloseBrackets 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.jsmatchTags 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 matching
the one under the cursor. Depends on
the addon/fold/xml-fold.js
addon. Demo here.edit/trailingspace.jsshowTrailingSpace 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.jsautoCloseTags option that will
auto-close XML tags when '>' or '/'
is typed, and
a closeTag command that
closes the nearest open tag. Depends on
the fold/xml-fold.js addon. See
the demo.edit/continuelist.js"newlineAndIndentContinueMarkdownList" command
that can be bound to enter to automatically
insert the leading characters for continuing a list. See
the Markdown mode
demo.comment/comment.jstoggleComment(from: {line, ch}, to: {line, ch}, ?options: object)lineComment(from: {line, ch}, to: {line, ch}, ?options: object)blockComment when no line comment
style is defined for the mode.blockComment(from: {line, ch}, to: {line, ch}, ?options: object)lineComment when no block comment
style is defined for the mode.uncomment(from: {line, ch}, to: {line, ch}, ?options: object) → booleantrue if a comment range was found and
removed, false otherwise.options object accepted by these methods may
have the following properties:
blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: stringpadding: stringcommentBlankLines: booleanindent: booleanfullLines: booleantrue.toggleComment command,
which is a shorthand command for calling
toggleComment with no options.
fold/foldcode.jsfoldCode 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)CodeMirror.fold.auto, which
uses getHelpers with
a "fold" type to find folding functions
appropriate for the local 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|ElementCodeMirror-foldmarker, or a DOM node.scanUp: booleanminFoldSize: integerfold/foldgutter.jsfoldGutter, 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"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"CodeMirror-foldgutter-open".indicatorFolded: string | Element"CodeMirror-foldgutter-folded".rangeFinder: fn(CodeMirror, Pos)CodeMirror.fold.auto
will be used as default.foldOptions editor option can be set to an
object to provide an editor-wide default configuration.
Demo here.
runmode/runmode.jsbin/source-highlight for an example of using the latter).runmode/colorize.jsrunmode 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.jsCodeMirror.overlayMode, which is used to
create such a mode. See this
demo for a detailed example.mode/multiplex.jsCodeMirror.multiplexingMode which, when
given as first argument a mode object, and as other arguments
any number of {open, close, mode [, delimStyle, innerStyle, parseDelimiters]}
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.
delimStyle is specified, it will be the token
style returned for the delimiter tokens (as well as
[delimStyle]-open on the opening token and
[delimStyle]-close on the closing token).innerStyle is specified, it will be the token
style added for each inner mode token.parseDelimiters is true, the content of
the delimiters will also be passed to the inner mode.
(And delimStyle is ignored.)hint/show-hint.jseditor.showHint, which takes an optional
options object, and pops up a widget that allows the user to
select a completion. Finding hints is done with a hinting
functions (the hint option), which is a function
that take an editor instance and options object, and return
a {list, from, to} 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 {line, ch}
objects. An optional selectedHint property (an
integer) can be added to the completion object to control the
initially selected hint.CodeMirror.hint.auto, which
calls getHelpers with
the "hint" type to find applicable hinting
functions, and tries them one by one. If that fails, it looks
for a "hintWords" helper to fetch a list of
completable words for the mode, and
uses CodeMirror.hint.fromList to complete from
those.text: stringdisplayText: stringclassName: stringrender: fn(Element, self, data)hint: fn(CodeMirror, self, data)from: {line, ch}from position that will be used by pick() instead
of the global one passed with the full list of completions.to: {line, ch}to position that will be used by pick() instead
of the global one passed with the full list of completions.hint: functionasync property on a hinting function to
true, in which case it will be called with
arguments (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.
The hinting function can also return a promise, and the completion
interface will only be popped when the promise resolves.
By default, hinting only works when there is no
selection. You can give a hinting function
a supportsSelection property with a truthy value
to indicate that it supports selections.completeSingle: booleanalignWithWord: booleancloseOnUnfocus: booleancustomKeys: keymapmoveFocus(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. Additionally menuSize()
can give you access to the size of the current dropdown menu,
length give you the number of available completions, and
data give you full access to the completion returned by the
hinting function.extraKeys: keymapcustomKeys above, but the bindings will
be added to the set of default bindings, instead of replacing
them."shown" ()"select" (completion, Element)"pick" (completion)"close" ()addon/hint/show-hint.css. Check
out the demo for an
example.
hint/javascript-hint.jsCodeMirror.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.jsCodeMirror.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)."!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.jsCodeMirror.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.jsCodeMirror.hint.css.hint/anyword-hint.jsCodeMirror.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.jsCodeMirror.hint.sql.
Takes two optional options, tables, a object with
table names as keys and array of respective column names as values,
and defaultTable, a string corresponding to a
table name in tables for autocompletion.search/match-highlighter.jshighlightSelectionMatches 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), trim, which
controls whether whitespace is trimmed from the selection,
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.jshtml-lint.js,
json-lint.js,
javascript-lint.js,
coffeescript-lint.js,
and css-lint.js
in the same directory). Defines a lint option that
can be set to an annotation source (for
example CodeMirror.lint.javascript), to an options
object (in which case the getAnnotations field is
used as annotation source), or simply to true. When
no annotation source is
specified, getHelper with
type "lint" is used to find an annotation function.
An annotation source function should, when given a document
string, an options object, and an editor instance, return an
array of {message, severity, from, to} objects
representing problems. When the function has
an async property with a truthy value, it will be
called with an additional second argument, which is a callback
to pass the array to. By default, the linter will run
(debounced) whenever the document is changed. You can pass
a lintOnChange: false option to disable that.
Depends on addon/lint/lint.css. A demo can be
found here.selection/mark-selection.jsCodeMirror-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.jsstyleActiveLine option that, when enabled,
gives the wrapper of the active line the class CodeMirror-activeline,
adds a background with the class CodeMirror-activeline-background,
and adds the class CodeMirror-activeline-gutter to the
line's gutter space is enabled. See the
demo.selection/selection-pointer.jsselectionPointer option which you can
use to control the mouse cursor appearance when hovering over
the selection. It can be set to a string,
like "pointer", or to true, in which case
the "default" (arrow) cursor will be used. You can
see a demo here.mode/loadmode.jsCodeMirror.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.mode/meta.jsCodeMirror.modeInfo, an array of objects
with {name, mime, mode} properties,
where name is the human-readable
name, mime the MIME type, and mode the
name of the mode file that defines this MIME. There are optional
properties mimes, which holds an array of MIME
types for modes with multiple MIMEs associated,
and ext, which holds an array of file extensions
associated with this mode. Four convenience
functions, CodeMirror.findModeByMIME,
CodeMirror.findModeByExtension,
CodeMirror.findModeByFileName
and CodeMirror.findModeByName are provided, which
return such an object given a MIME, extension, file name or mode name
string. Note that, for historical reasons, this file resides in the
top-level mode directory, not
under addon. Demo.comment/continuecomment.jscontinueComments option, which sets whether the
editor will make the next line continue a comment when you press Enter
inside a comment block. Can be set to a boolean to enable/disable this
functionality. Set to a string, it will continue comments using a custom
shortcut. Set to an object, it will use the key property for
a custom shortcut and the boolean continueLineComment
property to determine whether single-line comments should be continued
(defaulting to true).display/placeholder.jsplaceholder option that can be used to
make content appear in the editor when it is empty and not
focused. It can hold either a string or a DOM node. Also gives
the editor a CodeMirror-empty CSS class whenever it
doesn't contain any text.
See the demo.display/fullscreen.jsfullScreen 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.display/autorefresh.jsrefresh when the editor
becomes visible. It defines an option autoRefresh
which you can set to true to ensure that, if the editor wasn't
visible on initialization, it will be refreshed the first time
it becomes visible. This is done by polling every 250
milliseconds (you can pass a value like {delay:
500} as the option value to configure this). Note that
this addon will only refresh the editor once when it
first becomes visible, and won't take care of further restyling
and resizing.scroll/simplescrollbars.js"simple" and "overlay"
(see demo) that can
be selected with
the scrollbarStyle
option. Depends
on simplescrollbars.css,
which can be further overridden to style your own
scrollbars.scroll/annotatescrollbar.jsannotateScrollbar to editor instances that
can be called, with a CSS class name as argument, to create a
set of annotations. The method returns an object
whose update method can be called with an array
of {from: Pos, to: Pos} objects marking the ranges
to be highlighted. To detach the annotations, call the
object's clear method.display/rulers.jsrulers option, which can be used to show
one or more vertical rulers in the editor. The option, if
defined, should be given an array of {column [, className,
color, lineStyle, width]} objects or numbers (which
indicate a column). The ruler will be displayed at the column
indicated by the number or the column property.
The className property can be used to assign a
custom style to a ruler. Demo
here.display/panel.jsaddPanel method for CodeMirror
instances, which places a DOM node above or below an editor, and
shrinks the editor to make room for the node. The method takes
as first argument as DOM node, and as second an optional options
object. The Panel object returned by this method
has a clear method that is used to remove the
panel, and a changed method that can be used to
notify the addon when the size of the panel's DOM node has
changed.position : stringtop (default)after-topbottombefore-bottombefore : Panelafter : Panelreplace : Panelafter, before or replace options,
if the panel doesn't exists or has been removed,
the value of the position option will be used as a fallback.
A demo of the addon is available here.
wrap/hardwrap.jswrapParagraph(?pos: {line, ch}, ?options: object)pos is not given, it defaults to the cursor
position.wrapRange(from: {line, ch}, to: {line, ch}, ?options: object)wrapParagraphsInRange(from: {line, ch}, to: {line, ch}, ?options: object)paragraphStart, paragraphEnd: RegExpcolumn: numberwrapOn: RegExpkillTrailingSpace: booleanmerge/merge.jsCodeMirror.MergeView
constructor takes arguments similar to
the CodeMirror
constructor, first a node to append the interface to, and then
an options object. Options are passed through to the editors
inside the view. These extra options are recognized:
origLeft and origRight: stringrevertButtons: booleanconnect: string"align", the smaller chunk is padded to
align with the bigger chunk instead.collapseIdentical: boolean|numberallowEditingOriginals: booleanshowDifferences: boolean"goNextDiff"
and "goPrevDiff" to quickly jump to the next
changed chunk. Demo
here.
tern/tern.jsModes 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.
This section describes the low-level mode interface. Many modes are written directly against this, since it offers a lot of control, but for a quick mode definition, you might want to use the simple mode addon.
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() → booleansol() → booleanpeek() → stringnull at the end of the
line.next() → stringnull when no more characters are
available.eat(match: string|regexp|function(char: string) → boolean) → stringmatch 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) → booleaneat with the given argument,
until it fails. Returns true if any characters were eaten.eatSpace() → booleaneatWhile when matching
white-space.skipToEnd()skipTo(ch: string) → booleanmatch(pattern: string, ?consume: boolean, ?caseFold: boolean) → booleanmatch(pattern: regexp, ?consume: boolean) → array<string>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)n characters. Backing it up
further than the start of the current token will cause things to
break, so be careful.column() → integerindentation() → integercurrent() → stringBy 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 either
an electricChars or an electricInput
property, which are used to automatically reindent the line when
certain patterns are typed and
the electricChars
option is enabled. electricChars may be a string, and
will trigger a reindent whenever one of the characters in that
string are typed. Often, it is more appropriate to
use electricInput, which should hold a regular
expression, and will trigger indentation when the part of the
line before the cursor matches the expression. It should
usually end with a $ character, so that it only
matches when the indentation-changing pattern was just typed, not when something was
typed after the pattern.
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 {state, mode} 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.
It is possible, and encouraged, to associate
your mode, or a certain configuration of your mode, with
a MIME type. For
example, the JavaScript mode associates itself
with text/javascript, and its JSON variant
with application/json. To do this,
call CodeMirror.defineMIME(mime,
modeSpec), where modeSpec can be a string or
object specifying a mode, as in
the mode option.
If a mode specification wants to add some properties to the
resulting mode object, typically for use
with getHelpers, it may
contain a modeProps property, which holds an object.
This object's properties will be copied to the actual mode
object.
Sometimes, it is useful to add or override mode
object properties from external code.
The CodeMirror.extendMode function
can be used to add properties to mode objects produced for a
specific mode. Its first argument is the name of the mode, its
second an object that specifies the properties that should be
added. This is mostly useful to add utilities that can later be
looked up through getMode.
CodeMirror has a robust VIM mode that attempts to faithfully
emulate VIM's most useful features. It can be enabled by
including keymap/vim.js
and setting the keyMap option to
"vim".
VIM mode accepts configuration options for customizing
behavior at run time. These methods can be called at any time
and will affect all existing CodeMirror instances unless
specified otherwise. The methods are exposed on the
CodeMirror.Vim object.
setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)name should
be the name of an option. If cfg.scope is not set
and cm is provided, then sets the global and
instance values of the option. Otherwise, sets either the
global or instance value of the option depending on whether
cfg.scope is global or
local.getOption(name: string, ?cm: CodeMirror: ?cfg: object)cfg.scope is not set and cm is
provided, then gets the instance value of the option, falling
back to the global value if not set. If cfg.scope is provided, then gets the global or
local value without checking the other.map(lhs: string, rhs: string, ?context: string):map command. To map ; to : in VIM would be
:map ; :. That would translate to
CodeMirror.Vim.map(';', ':');.
The context can be normal,
visual, or insert, which correspond
to :nmap, :vmap, and
:imap
respectively.mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)motion,
operator, or action type command.
The args object is passed through to the command when it is
invoked by the provided key sequence.
extras.context can be normal,
visual, or insert, to map the key
sequence only in the corresponding mode.
extras.isEdit is applicable only to actions,
determining whether it is recorded for replay for the
. single-repeat command.
CodeMirror's VIM mode implements a large subset of VIM's core
editing functionality. But since there's always more to be
desired, there is a set of APIs for extending VIM's
functionality. As with the configuration API, the methods are
exposed on CodeMirror.Vim and may
be called at any time.
defineOption(name: string, default: any, type: string, ?aliases: array<string>, ?callback: function (?value: any, ?cm: CodeMirror) → ?any):set command. Type can be boolean or
string, used for validation and by
:set to determine which syntax to accept. If a
callback is passed in, VIM does not store the value of the
option itself, but instead uses the callback as a setter/getter. If the
first argument to the callback is undefined, then the
callback should return the value of the option. Otherwise, it should set
instead. Since VIM options have global and instance values, whether a
CodeMirror instance is passed in denotes whether the global
or local value should be used. Consequently, it's possible for the
callback to be called twice for a single setOption or
getOption call. Note that right now, VIM does not support
defining buffer-local options that do not have global values. If an
option should not have a global value, either always ignore the
cm parameter in the callback, or always pass in a
cfg.scope to setOption and
getOption.defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})head
is the current position of the cursor. It can differ from
cm.getCursor('head') if VIM is in visual mode.
motionArgs is the object passed into
mapCommand().defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array<{anchor, head}>) → ?{line, ch})
defineMotion. ranges is the range
of text the operator should operate on. If the cursor should
be set to a certain position after the operation finishes, it
can return a cursor object.defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))defineMotion. Action commands
can have arbitrary behavior, making them more flexible than
motions and operators, at the loss of orthogonality.defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object)):name.
If a prefix is provided, it, and any prefixed substring of the
name beginning with the prefix can
be used to invoke the command. If the prefix is
falsy, then name is used as the prefix.
params.argString contains the part of the prompted
string after the command name. params.args is
params.argString split by whitespace. If the
command was prefixed with a
line range,
params.line and params.lineEnd will
be set.
|
|
不开心的消防车 · 《扫黑风暴》中的反派,现实都怎么样了? 4 月前 |
|
|
善良的煎饼果子 · js 对象数组转单值数组 - CSDN文库 1 年前 |
|
|
刚毅的皮带 · No converter found for return value of type: org.springframework.http.converter.HttpMessageNotWritableException: No converter foun 2 年前 |
|
|
坚强的伤痕 · 中年夫妻之间,默许以下的事,就是离心了 - 知乎 2 年前 |