An editor view represents the editor's user interface. It holds
the editable DOM surface, and possibly other elements such as the
line number gutter. It handles events and dispatches state
transactions for editing actions.
-
new EditorView(config?: Object = {})
Construct a new view. You'll usually want to put view.dom into
your document after creating a view, so that the user can see
it.
-
config
Initialization options.
-
state?: EditorState
The view's initial state. Defaults to an extension-less state
with an empty document.
-
root?: Document | ShadowRoot
If the view is going to be mounted in a shadow root or document
other than the one held by the global variable document (the
default), you should pass it here. If you provide parent, but
not this option, the editor will automatically look up a root
from the parent.
-
dispatch?: fn(tr: Transaction)
Override the transaction dispatch
function for this editor view, which
is the way updates get routed to the view. Your implementation,
if provided, should probably call the view's update
method.
-
parent?: Element | DocumentFragment
When given, the editor is immediately appended to the given
element on creation. (Otherwise, you'll have to place the view's
dom element in the document yourself.)
-
state: EditorState
The current editor state.
-
viewport: {from: number, to: number}
To be able to display large documents without consuming too much
memory or overloading the browser, CodeMirror only draws the
code that is visible (plus a margin around it) to the DOM. This
property tells you the extent of the current drawn viewport, in
document positions.
-
visibleRanges: readonly {from: number, to: number}[]
When there are, for example, large collapsed ranges in the
viewport, its size can be a lot bigger than the actual visible
content. Thus, if you are doing something like styling the
content in the viewport, it is preferable to only do so for
these ranges, which are the subset of the viewport that is
actually drawn.
-
inView: boolean
Returns false when the editor is entirely scrolled out of view
or otherwise hidden.
-
composing: boolean
Indicates whether the user is currently composing text via
IME, and at least
one change has been made in the current composition.
-
compositionStarted: boolean
Indicates whether the user is currently in composing state. Note
that on some platforms, like Android, this will be the case a
lot, since just putting the cursor on a word starts a
composition there.
-
root: DocumentOrShadowRoot
The document or shadow root that the view lives in.
-
dom: HTMLElement
The DOM element that wraps the entire editor view.
-
scrollDOM: HTMLElement
The DOM element that can be styled to scroll. (Note that it may
not have been, so you can't assume this is scrollable.)
-
contentDOM: HTMLElement
The editable DOM element holding the editor content. You should
not, usually, interact with this content directly though the
DOM, since the editor will immediately undo most of the changes
you make. Instead, dispatch
transactions to modify content, and
decorations to style it.
-
dispatch(tr: Transaction)
All regular editor state updates should go through this. It
takes a transaction or transaction spec and updates the view to
show the new state produced by that transaction. Its
implementation can be overridden with an
option. This
function is bound to the view instance, so it does not have to
be called as a method.
-
update(transactions: readonly Transaction[])
Update the view for the given array of transactions. This will
update the visible document and selection to match the state
produced by the transactions, and notify view plugins of the
change. You should usually call
dispatch instead, which uses this
as a primitive.
-
setState(newState: EditorState)
Reset the view to the given state. (This will cause the entire
document to be redrawn and all view plugins to be reinitialized,
so you should probably only use it when the new state isn't
derived from the old state. Otherwise, use
dispatch instead.)
-
themeClasses: string
Get the CSS classes for the currently active editor themes.
-
requestMeasure<T>(request?: Object)
Schedule a layout measurement, optionally providing callbacks to
do custom DOM measuring followed by a DOM write phase. Using
this is preferable reading DOM layout directly from, for
example, an event handler, because it'll make sure measuring and
drawing done by other components is synchronized, avoiding
unnecessary DOM layout computations.
-
request
-
read(view: EditorView) → T
Called in a DOM read phase to gather information that requires
DOM layout. Should not mutate the document.
-
write?: fn(measure: T, view: EditorView)
Called in a DOM write phase to update the document. Should not
do anything that triggers DOM layout.
-
key?: any
When multiple requests with the same key are scheduled, only the
last one will actually be ran.
-
pluginField<T>(field: PluginField<T>) → readonly T[]
Collect all values provided by the active plugins for a given
field.
-
plugin<T>(plugin: ViewPlugin<T>) → T | null
Get the value of a specific plugin, if present. Note that
plugins that crash can be dropped from a view, so even when you
know you registered a given plugin, it is recommended to check
the return value of this method.
-
documentTop: number
The top position of the document, in screen coordinates. This
may be negative when the editor is scrolled down. Points
directly to the top of the first line, not above the padding.
-
documentPadding: {top: number, bottom: number}
Reports the padding above and below the document.
-
blockAtHeight(height: number, docTop?: number) → BlockInfo
Find the line or block widget at the given vertical position.
By default, this position is interpreted as a screen position,
meaning docTop is set to the DOM top position of the editor
content (forcing a layout). You can pass a different docTop
value—for example 0 to interpret height as a document-relative
position, or a precomputed document top
(view.contentDOM.getBoundingClientRect().top) to limit layout
queries.
Deprecated: use elementAtHeight instead.
-
elementAtHeight(height: number) → BlockInfo
Find the text line or block widget at the given vertical
position (which is interpreted as relative to the top of the
document
-
visualLineAtHeight(height: number, docTop?: number) → BlockInfo
Find information for the visual line (see
visualLineAt) at the given
vertical position. The resulting block info might hold another
array of block info structs in its type field if this line
consists of more than one block.
Defaults to treating height as a screen position. See
blockAtHeight for the
interpretation of the docTop parameter.
Deprecated: use lineBlockAtHeight instead.
-
lineBlockAtHeight(height: number) → BlockInfo
Find the line block (see
lineBlockAt at the given
height.
-
viewportLines(f: fn(line: BlockInfo), docTop?: number)
Iterate over the height information of the visual lines in the
viewport. The heights of lines are reported relative to the
given document top, which defaults to the screen position of the
document (forcing a layout).
Deprecated: use viewportLineBlocks instead.
-
viewportLineBlocks: BlockInfo[]
Get the extent and vertical position of all line
blocks in the viewport. Positions
are relative to the top of the
document;
-
visualLineAt(pos: number, docTop?: number = 0) → BlockInfo
Find the extent and height of the visual line (a range delimited
on both sides by either non-hidden
line breaks, or the start/end of the document) at the given position.
Vertical positions are computed relative to the docTop
argument, which defaults to 0 for this method. You can pass
view.contentDOM.getBoundingClientRect().top here to get screen
coordinates.
Deprecated: use lineBlockAt instead.
-
lineBlockAt(pos: number) → BlockInfo
Find the line block around the given document position. A line
block is a range delimited on both sides by either a
non-hidden line breaks, or the
start/end of the document. It will usually just hold a line of
text, but may be broken into multiple textblocks by block
widgets.
-
contentHeight: number
The editor's total content height.
-
moveByChar() → SelectionRange
Move a cursor position by grapheme
cluster. forward determines whether
the motion is away from the line start, or towards it. Motion in
bidirectional text is in visual order, in the editor's text
direction. When the start
position was the last one on the line, the returned position
will be across the line break. If there is no further line, the
original position is returned.
By default, this method moves over a single cluster. The
optional by argument can be used to move across more. It will
be called with the first cluster as argument, and should return
a predicate that determines, for each subsequent cluster,
whether it should also be moved over.
-
moveByGroup(start: SelectionRange, forward: boolean) → SelectionRange
Move a cursor position across the next group of either
letters or non-letter
non-whitespace characters.
-
moveToLineBoundary() → SelectionRange
Move to the next line boundary in the given direction. If
includeWrap is true, line wrapping is on, and there is a
further wrap point on the current line, the wrap point will be
returned. Otherwise this function will return the start or end
of the line.
-
moveVertically() → SelectionRange
Move a cursor position vertically. When distance isn't given,
it defaults to moving to the next line (including wrapped
lines). Otherwise, distance should provide a positive distance
in pixels.
When start has a
goalColumn, the vertical
motion will use that as a target horizontal position. Otherwise,
the cursor's own horizontal position is used. The returned
cursor will have its goal column set to whichever column was
used.
-
scrollPosIntoView(pos: number)
-
domAtPos(pos: number) → {node: Node, offset: number}
Find the DOM parent node and offset (child offset if node is
an element, character offset when it is a text node) at the
given document position.
Note that for positions that aren't currently in
visibleRanges, the resulting DOM position isn't necessarily
meaningful (it may just point before or after a placeholder
element).
-
posAtDOM(node: Node, offset?: number = 0) → number
Find the document position at the given DOM node. Can be useful
for associating positions with DOM events. Will raise an error
when node isn't part of the editor content.
-
posAtCoords() → number
Get the document position at the given screen coordinates. For
positions not covered by the visible viewport's DOM structure,
this will return null, unless false is passed as second
argument, in which case it'll return an estimated position that
would be near the coordinates if it were rendered.
-
coordsAtPos(pos: number, side?: -1 | 1 = 1) → Rect | null
Get the screen coordinates at the given document position.
side determines whether the coordinates are based on the
element before (-1) or after (1) the position (if no element is
available on the given side, the method will transparently use
another strategy to get reasonable coordinates).
-
defaultCharacterWidth: number
The default width of a character in the editor. May not
accurately reflect the width of all characters (given variable
width fonts or styling of invididual ranges).
-
defaultLineHeight: number
The default height of a line in the editor. May not be accurate
for all lines.
-
textDirection: Direction
The text direction
(direction
CSS property) of the editor.
-
lineWrapping: boolean
Whether this editor wraps lines
(as determined by the
white-space
CSS property of its content element).
-
bidiSpans(line: Line) → readonly BidiSpan[]
Returns the bidirectional text structure of the given line
(which should be in the current document) as an array of span
objects. The order of these spans matches the text
direction—if that is
left-to-right, the leftmost spans come first, otherwise the
rightmost spans come first.
-
hasFocus: boolean
Check whether the editor has focus.
-
focus()
Put focus on the editor.
-
destroy()
Clean up this editor view, removing its element from the
document, unregistering event handlers, and notifying
plugins. The view instance can no longer be used after
calling this.
-
static scrollTo: StateEffectType<SelectionRange>
Effect that can be added to a
transaction to make it scroll the given range into view.
Deprecated. Use scrollIntoView instead.
-
static centerOn: StateEffectType<SelectionRange>
Effect that makes the editor scroll the given range to the
center of the visible view.
Deprecated. Use scrollIntoView instead.
-
static scrollIntoView() → StateEffect<unknown>
Returns an effect that can be
added to a transaction to
cause it to scroll the given position or range into view.
-
options
-
y?: "nearest" | "start" | "end" | "center"
By default ("nearest") the position will be vertically
scrolled only the minimal amount required to move the given
position into view. You can set this to "start" to move it
to the top of the view, "end" to move it to the bottom, or
"center" to move it to the center.
-
x?: "nearest" | "start" | "end" | "center"
Effect similar to
y, but for the
horizontal scroll position.
-
yMargin?: number
Extra vertical distance to add when moving something into
view. Not used with the "center" strategy. Defaults to 5.
-
xMargin?: number
Extra horizontal distance to add. Not used with the "center"
strategy. Defaults to 5.
-
static styleModule: Facet<StyleModule>
Facet to add a style
module to
an editor view. The view will ensure that the module is
mounted in its document
root.
-
static domEventHandlers(handlers: DOMEventHandlers<any>) → Extension
Facet that can be used to add DOM event handlers. The value
should be an object mapping event names to handler functions. The
first such function to return true will be assumed to have handled
that event, and no other handlers or built-in behavior will be
activated for it.
These are registered on the content
element, except for scroll
handlers, which will be called any time the editor's scroll
element or one of its parent nodes
is scrolled.
-
static inputHandler: Facet<>
An input handler can override the way changes to the editable
DOM content are handled. Handlers are passed the document
positions between which the change was found, and the new
content. When one returns true, no further input handlers are
called and the default behavior is prevented.
-
static exceptionSink: Facet<fn(exception: any)>
Allows you to provide a function that should be called when the
library catches an exception from an extension (mostly from view
plugins, but may be used by other extensions to route exceptions
from user-code-provided callbacks). This is mostly useful for
debugging and logging. See logException.
-
static updateListener: Facet<fn(update: ViewUpdate)>
A facet that can be used to register a function to be called
every time the view updates.
-
static editable: Facet<boolean, boolean>
Facet that controls whether the editor content DOM is editable.
When its highest-precedence value is false, the element will
not longer have its contenteditable attribute set. (Note that
this doesn't affect API calls that change the editor content,
even when those are bound to keys or buttons. See the
readOnly facet for that.)
-
static mouseSelectionStyle: Facet<>
Allows you to influence the way mouse selection happens. The
functions in this facet will be called for a mousedown event
on the editor, and can return an object that overrides the way a
selection is computed from that mouse click or drag.
-
static dragMovesSelection: Facet<fn(event: MouseEvent) → boolean>
Facet used to configure whether a given selection drag event
should move or copy the selection. The given predicate will be
called with the mousedown event, and can return true when
the drag should move the content.
-
static clickAddsSelectionRange: Facet<fn(event: MouseEvent) → boolean>
Facet used to configure whether a given selecting click adds
a new range to the existing selection or replaces it entirely.
-
static decorations: Facet<DecorationSet>
A facet that determines which decorations
are shown in the view. See also view
plugins, which have a separate
mechanism for providing decorations.
-
static theme() → Extension
Create a theme extension. The first argument can be a
style-mod
style spec providing the styles for the theme. These will be
prefixed with a generated class for the style.
Because the selectors will be prefixed with a scope class, rule
that directly match the editor's wrapper
element—to which the scope class will be
added—need to be explicitly differentiated by adding an & to
the selector for that element—for example
&.cm-focused.
When dark is set to true, the theme will be marked as dark,
which will cause the &dark rules from base
themes to be used (as opposed to
&light when a light theme is active).
-
static darkTheme: Facet<boolean, boolean>
This facet records whether a dark theme is active. The extension
returned by theme automatically
includes an instance of this when the dark option is set to
true.
-
static baseTheme(spec: Object<StyleSpec>) → Extension
Create an extension that adds styles to the base theme. Like
with theme, use & to indicate the
place of the editor wrapper element when directly targeting
that. You can also use &dark or &light instead to only
target editors with a dark or light theme.
-
static contentAttributes: Facet<>
Facet that provides additional DOM attributes for the editor's
editable DOM element.
-
static editorAttributes: Facet<>
Facet that provides DOM attributes for the editor's outer
element.
-
static lineWrapping: Extension
An extension that enables line wrapping in the editor (by
setting CSS white-space to pre-wrap in the content).
-
static announce: StateEffectType<string>
State effect used to include screen reader announcements in a
transaction. These will be added to the DOM in a visually hidden
element with aria-live="polite" set, and should be used to
describe effects that are visually obvious but may not be
noticed by screen reader users (such as moving to the next
search match).