Expand all

CodeMirror

Interface for the CodeMirror editor.

This class is a wrapper around the CodeMirror library, providing a simplified interface for creating and managing CodeMirror instances in MediaWiki.

Lifecycle

Example

// Creating a new CodeMirror instance.
const require = await mw.loader.using( [ 'ext.CodeMirror', 'ext.CodeMirror.mode.mediawiki' ] );
const CodeMirror = require( 'ext.CodeMirror' );
const { mediawiki } = require( 'ext.CodeMirror.mode.mediawiki' );
const cm = new CodeMirror( myTextarea, mediawiki() );
cm.initialize();

// Integrating with an existing CodeMirror instance.
mw.hook( 'ext.CodeMirror.ready', ( cm ) => {
  cm.applyExtension( myExtension );
} );

Constructor

new CodeMirror(textarea, [langSupport]) #

Instantiate a new CodeMirror instance.

Parameters:

Name Type Attributes Description
textarea HTMLTextAreaElement | jQuery | string | ve.ui.Surface

Textarea or VisualEditor surface to add syntax highlighting to.

langSupport CodeMirrorMode | LanguageSupport optional

Language support and its extension(s).

Implements:
Source:

Properties

$textarea :jQuery.<(HTMLTextAreaElement|ve.ui.Surface)> #

jQuery instance of the textarea or VE surface for use with jQuery plugins.

Type:

Source:
jQuery instance of the textarea or VE surface for use with jQuery plugins.

activeLineExtension :Extension #

Extension for highlighting the active line.

Type:

Source:
Extension for highlighting the active line.

bracketMatchingConfig :Config|undefined #

The extended configuration for bracket matching. Setting this will update the bracket matching extension

Example

// Highlight matching angle brackets in addition to the default.
mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
  const config = cm.bracketMatchingConfig || {};
  config.brackets = ( config.brackets || '()[]{}' ) + '<>';
  cm.bracketMatchingConfig = config;
} );

Type:

Source:
The extended configuration for bracket matching.

bracketMatchingExtension :Extension #

This extension adds bracket matching to the CodeMirror editor.

Type:

Source:
This extension adds bracket matching to the CodeMirror editor.

child :CodeMirrorChild #

Get a CodeMirrorChild object for use on other textareas that should have preferences synced with this CodeMirror instance.

Type:

Source:

Get a CodeMirrorChild object for use on other textareas that should have preferences synced with this CodeMirror instance.

closeBracketsExtension :Extension #

This extension adds automatic closing of brackets to the CodeMirror editor.

Type:

Source:
This extension adds automatic closing of brackets to the CodeMirror editor.

columnGuideExtension :Extensionprotected #

This extension adds a vertical column guide to the editor at column 80.

Type:

Source:
This extension adds a vertical column guide to the editor at column 80.

compactPanelsExtension :Extension #

Extension for the compact panel design. The class it adds makes the search and go-to line panels float over the editor instead of pushing the contents down.

Type:

Source:
Extension for the compact panel design.

container :HTMLDivElement #

The .ext-codemirror-wrapper container. This houses both the original textarea and the CodeMirror editor.

Type:

Source:
The .ext-codemirror-wrapper container.

contentAttributesExtension :Extensionprotected #

This specifies which attributes get added to the CodeMirror contenteditable .cm-content. Subclasses are safe to override this method, but attributes here are considered vital.

Type:

Source:
See:
This specifies which attributes get added to the CodeMirror contenteditable .cm-content.

defaultExtensions :Extension #

Default extensions used by CodeMirror. Extensions here should be applicable to all theoretical uses of CodeMirror in MediaWiki. This getter can be overridden to apply additional extensions before initialization. To apply a new extension after initialization, use applyExtension(), or through CodeMirrorExtensionRegistry using register() if it needs to be reconfigured (such as toggling on and off).

Type:

Source:
See:
Default extensions used by CodeMirror.

dirCompartment :Compartment #

Compartment to control the direction of the editor.

Type:

Source:
Compartment to control the direction of the editor.

dirExtension :Extensionprotected #

This extension adds the ability to change the direction of the editor.

Type:

Source:
This extension adds the ability to change the direction of the editor.

domEventHandlersExtension :Extensionprotected #

Extension to bubble some DOM events to the original textarea.

The CodeMirror events are natively fired on the EditorView's .cm-content element, which is accessible through view.contentDOM. The scroll event is fired on the .cm-scroller element, which is accessible through view.scrollDOM.

Type:

Source:
Extension to bubble some DOM events to the original textarea.

editRecoveryExtension #

Edit Recovery support.

editorAttributesExtension :Extensionprotected #

This specifies which attributes get added to the .cm-editor element (the entire editor). Subclasses are safe to override this method, but attributes here are considered vital.

Type:

Source:
See:
This specifies which attributes get added to the .cm-editor element (the entire editor).

extensionRegistry :CodeMirrorExtensionRegistry #

Registry of CodeMirror Extensions.

Type:

Source:
Registry of CodeMirror Extensions.

extensionRegistryDefaults :Object.<Extension>protected #

The Extensions to register with the CodeMirrorExtensionRegistry at construction, keyed by preference name. Subclasses may override this to restrict or extend which preference-backed extensions are available in their integration.

NOTE: This is called by the CodeMirror constructor, so overrides must not reference instance properties that are only set after super() has been called.

Type:

Source:

The Extensions to register with the CodeMirrorExtensionRegistry at construction, keyed by preference name.

gotoLine :CodeMirrorGotoLine #

The go-to line panel.

Type:

Source:
The go-to line panel.

hasFocus :boolean #

Whether the editor has focus.

Type:

  • boolean
Source:
Whether the editor has focus.

heightExtension :Extension #

This extension sets the height of the CodeMirror editor to match the textarea. This getter can be overridden to change the height of the editor, but it's usually simpler to set the height of the textarea using CSS prior to initialization.

Type:

Source:

This extension sets the height of the CodeMirror editor to match the textarea.

indentGuidesExtension :Extension #

This extension adds indent guides to the CodeMirror editor.

Type:

Source:
This extension adds indent guides to the CodeMirror editor.

initialReadOnly :booleanprotected #

The read-only state to use before there is a view, which is what readOnlyExtension seeds the state with. Integrations bound to something other than a textarea should override this.

Type:

  • boolean
Source:

The read-only state to use before there is a view, which is what readOnlyExtension seeds the state with.

isActive :boolean #

Whether the CodeMirror instance is active.

Type:

  • boolean
Source:
Whether the CodeMirror instance is active.

keymap :CodeMirrorKeymap #

CodeMirror key mappings and help dialog.

Type:

Source:
CodeMirror key mappings and help dialog.

langExtension :LanguageSupport #

Language support and its extension(s).

Type:

Source:
Language support and its extension(s).

lineNumberingExtension :Extension #

Extension for line numbering.

Type:

Source:
Extension for line numbering.

lineWrappingExtension :Extension #

Extension for line wrapping.

Type:

Source:
Extension for line wrapping.

lintApi :LintSource|undefined #

The function to lint the code in the editor using a MediaWiki API. It can be disabled by setting this.lintApi.disabled = true.

Example

mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
  if ( cm.lintApi ) {
    cm.lintApi.disabled = true;
  }
} );

Type:

Source:
The function to lint the code in the editor using a MediaWiki API.

lintExtension :Extensionprotected #

This extension adds the ability to lint the code in the editor.

Type:

Source:
This extension adds the ability to lint the code in the editor.

lintSource :LintSource|undefined #

The function to lint the code in the editor using a web worker. It can be disabled by setting this.lintSource.disabled = true.

Example

mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
  if ( cm.lintSource ) {
    cm.lintSource.disabled = true;
  }
} );

Type:

Source:
The function to lint the code in the editor using a web worker.

mode :string #

The CodeMirror "mode" (language).

Type:

  • string
Source:
The CodeMirror "mode" (language).

persistPreferences :booleanprotected #

Whether to save preference changes to the user's options. Subclasses that are not the user's main editor should override this and return false, so that the editor does not change preferences the user set elsewhere. Preferences are still read, and still apply for the life of the editor.

Note this is distinct from locked preferences, which force a specific PrefValue for the life of the editor.

Type:

  • boolean
Source:
Whether to save preference changes to the user's options.

phrasesExtension :Extensionprotected #

Overrides for the CodeMirror library's internalization system.

Type:

Source:
See:
Overrides for the CodeMirror library's internalization system.

preferences :CodeMirrorPreferences #

The CodeMirror preferences dialog.

Type:

Source:
The CodeMirror preferences dialog.

readOnly :boolean #

Whether the editor is read-only. Assigning to this reconfigures the editor in place, so it can be changed at any time after initialization. Before then it comes from initialReadOnly.

A read-only editor is still focusable and its contents still selectable. Use EditorView.editable to make it non-editable.

Type:

  • boolean
Source:
Whether the editor is read-only.

readOnlyExtension :Extensionprotected #

The read-only state of the editor, in a Compartment so that readOnly can reconfigure it after initialization.

Type:

Source:

The read-only state of the editor, in a Compartment so that readOnly can reconfigure it after initialization.

The CodeMirror search panel.

searchExtension :Extension #

Extension for search and goto line functionality.

Type:

Source:
Extension for search and goto line functionality.

sortLines :CodeMirrorSortLines #

CodeMirror line sorting functionality.

Type:

Source:
CodeMirror line sorting functionality.

specialCharsExtension :Extensionprotected #

We give a small subset of special characters a tooltip explaining what they are. The messages and for what characters are defined here. Any character that does not have a message will instead use CM6 defaults, which is the localization of 'codemirror-control-character' followed by the Unicode number.

Type:

Source:
See:
We give a small subset of special characters a tooltip explaining what they are.

state :EditorState|undefined #

The current EditorState of the CodeMirror editor. This is given by the EditorView instance, which is only available after initialization.

Type:

Source:
The current EditorState of the CodeMirror editor.

supportedExtensions :Array.<string>|nullprotected #

Names that CodeMirrorExtensionRegistry#register will accept, or null to accept any name. Subclasses that can only support some extensions should override this, so that extensions registered later — by a gadget, or by applyLinter() — are refused as well.

NOTE: This is called by the CodeMirror constructor, so overrides must not reference instance properties that are only set after super() has been called.

Type:

Source:

Names that CodeMirrorExtensionRegistry#register will accept, or null to accept any name.

textSelection :CodeMirrorTextSelection #

jQuery.textSelection overrides for CodeMirror.

Type:

Source:
jQuery.textSelection overrides for CodeMirror.

textarea :HTMLTextAreaElement|ve.ui.Surface #

The textarea or VE surface that CodeMirror is bound to.

Type:

Source:
The textarea or VE surface that CodeMirror is bound to.

themes :CodeMirrorThemes #

The CodeMirror themes manager.

Type:

Source:
The CodeMirror themes manager.

trailingWhitespaceExtension #

This extension highlights trailing whitespace characters.

Source:
This extension highlights trailing whitespace characters.

updateExtension :Extension #

This extension listens for changes in the CodeMirror editor and fires the ext.CodeMirror.input hook with the ViewUpdate object.

Type:

Source:

Fires:

This extension listens for changes in the CodeMirror editor and fires the ext.CodeMirror.input hook with the ViewUpdate object.

view :EditorView #

The editor user interface.

Type:

Source:
The editor user interface.

whitespaceExtension #

This extension highlights whitespace characters.

Source:
This extension highlights whitespace characters.

wrappedElement :HTMLElementprotected #

The element that container is wrapped around, and which the container hides. Integrations bound to something other than a textarea should override this, so that the view is added beside the right element.

Type:

Source:

The element that container is wrapped around, and which the container hides.

modeModules :Object.<string, string>staticconstant #

The ResourceLoader module that provides each mode, keyed by mode name.

Type:

Source:
The ResourceLoader module that provides each mode, keyed by mode name.

Methods

activate()protected #

Activate CodeMirror on the textarea. This shows the editor view, hiding the original textarea.

initialize is expected to be called before this method.

Source:
Activate CodeMirror on the textarea.

addEditRecoveryHandler()protected #

Set a new edit recovery handler.

Source:
Set a new edit recovery handler.

addFormSubmitHandler()protected #

Sync the CodeMirror editor with the original textarea on form submission.

Source:
Sync the CodeMirror editor with the original textarea on form submission.

addMwHook(hook, fn)protected #

Add a handler for the given Hook. This method is used to ensure no hook handlers are duplicated across lifecycle methods, All handlers will be removed during deactivation.

Parameters:

Name Type Description
hook string
fn function
Source:
Add a handler for the given Hook.

addTextAreaJQueryHook()protected #

Define jQuery hook for .val() on the textarea.

Source:
See:
Define jQuery hook for .val() on the textarea.

addToDOM(extensions)protected #

Add the CodeMirror EditorView to the DOM, wrapping wrappedElement in the container element.

Parameters:

Name Type Description
extensions Extension
Source:

Add the CodeMirror EditorView to the DOM, wrapping wrappedElement in the container element.

applyExtension(extension) #

Apply an Extension to the CodeMirror editor. This is accomplished through top-level reconfiguration of the EditorView.

If the extension needs to be reconfigured (such as toggling on and off), use the extensionRegistry instead.

Example

const require = await mw.loader.using( 'ext.CodeMirror' );
mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
  const { EditorView, Prec } = require( 'ext.CodeMirror.lib' );
  // Disable spellchecking. Use Prec.high() to override the
  // contentAttributesExtension which adds spellcheck="true".
  cm.applyExtension( Prec.high( EditorView.contentAttributes.of( {
    spellcheck: 'false'
  } ) ) );
} );

Parameters:

Name Type Description
extension Extension
Source:
See:
Apply an Extension to the CodeMirror editor.

applyLinter(lint, [config]) #

Apply an extra linter to the CodeMirror editor. This linter respects the user preference for enabling or disabling linting.

Example

// Report Ukrainian letter 'Ñ–' among Latin letters as a warning.
const lint = {
  pattern: /[a-zA-Z]Ñ–|Ñ–(?=[a-zA-Z])/g,
  callback( match ) {
    return {
      from: match.index + match[ 0 ].indexOf( 'Ñ–' ),
      to: match.index + match[ 0 ].indexOf( 'Ñ–' ) + 1,
      severity: 'warning',
      message: 'Ukrainian letter "Ñ–" found among Latin letters.',
      actions: [ {
        name: 'To Latin',
        apply( view, from, to ) {
          view.dispatch( {
            changes: { from, to, insert: 'i' }
          } );
        }
      } ]
    };
  }
};
mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
  cm.applyLinter( lint );
} );

Parameters:

Name Type Attributes Description
lint function | Object

Function that takes a string and returns an array of Diagnostic, or an object with a pattern RegExp and callback function that takes a RegExp match and returns Diagnostic or an array of Diagnostic.

config Object optional

Optional configuration.

Source:
Apply an extra linter to the CodeMirror editor.

deactivate()protected #

Deactivate CodeMirror on the textarea, restoring the original textarea and hiding the editor. This life-cycle method should retain the view.

Source:

Deactivate CodeMirror on the textarea, restoring the original textarea and hiding the editor.

destroy() #

Destroy the CodeMirror instance and revert to the original textarea. This action should be considered irreversible.

Fires:

Source:
Destroy the CodeMirror instance and revert to the original textarea.

dispatch(spec) #

Apply a transaction to the editor. Together with state, this is what makes a CodeMirror instance an Editor.

Parameters:

Name Type Description
spec Object
Source:

Apply a transaction to the editor.

focus([isActive]) #

Focus the CodeMirror editor.

Parameters:

Name Type Attributes Description
isActive boolean optional

Whether the CodeMirror editor is active.

Source:
Focus the CodeMirror editor.

getLineNumberingExtension([firstLineNumber]) → {Extension} #

Line numbering, starting at the given number.

Use this instead of CodeMirror#lineNumberingExtension when the code in the editor is part of a larger file, and the first line is not line 1.

Parameters:

Name Type Attributes Default Description
firstLineNumber number optional
1

Number to show for the first line.

Returns:

Type
Extension
Source:
Line numbering, starting at the given number.

getNewEditorState(extensions) → {EditorState}protected #

Create a new EditorState with the given extensions and the contents of the element that CodeMirror is bound to.

Parameters:

Name Type Description
extensions Extension

Returns:

Type
EditorState
Source:

Create a new EditorState with the given extensions and the contents of the element that CodeMirror is bound to.

getSourceContents() → {string}protected #

Get the contents of the element that CodeMirror is bound to. This is used to populate the initial document, and to re-sync the contents when re-activating.

Returns:

Type
string
Source:
Get the contents of the element that CodeMirror is bound to.

hideEditor()protected #

Hide the editor and give jQuery.textSelection back to the textarea, as deactivate() does on the way out. Integrations that render no editor of their own should override this.

Source:

Hide the editor and give jQuery.textSelection back to the textarea, as deactivate() does on the way out.

initialize([extensions]) #

Setup CodeMirror and add it to the DOM. This will hide the original textarea.

This method should only be called once per instance. Use toggle, activate, and deactivate to enable or disable the same CodeMirror instance programmatically, and restore or hide the original textarea.

Parameters:

Name Type Attributes Default Description
extensions Extension optional
this.defaultExtensions

Extensions to use.

Fires:

Source:
Setup CodeMirror and add it to the DOM.

logEditFeature(action)protected #

Log usage of CodeMirror.

Parameters:

Name Type Description
action string
Source:
See:
Log usage of CodeMirror.

removeFromDOM()protected #

Remove the CodeMirror EditorView from the DOM, unwrapping the element it was attached to, as the inverse of addToDOM(). Integrations that attach CodeMirror to something other than a textarea should override this.

Source:

Remove the CodeMirror EditorView from the DOM, unwrapping the element it was attached to, as the inverse of addToDOM().

removeMwHooks([hook], [fn])protected #

Remove handlers registered with #addMwHook for the given Hook, or remove all handlers if no hook is specified.

Parameters:

Name Type Attributes Description
hook string optional
fn function optional

If specified, only this handler will be removed for the given hook.

Source:

Remove handlers registered with #addMwHook for the given Hook, or remove all handlers if no hook is specified.

restoreSelectionAndScrollPosition(selectionStart, selectionEnd, scrollTop, hadFocus)protected #

Hand the hidden textarea's state over to the editor: disable IME on the textarea so it can't conflict with CodeMirror, then restore the selection, scroll position and focus state that were captured before the textarea was hidden.

This is the activate counterpart to syncSelectionAndScrollPosition(). Integrations that aren't bound to a textarea should override it as a no-op.

Parameters:

Name Type Description
selectionStart number
selectionEnd number
scrollTop number
hadFocus boolean
Source:

Hand the hidden textarea's state over to the editor: disable IME on the textarea so it can't conflict with CodeMirror, then restore the selection, scroll position and focus state that were captured before the textarea was hidden.

setCodeMirrorPreference(prefValue) #

Save CodeMirror enabled preference.

Parameters:

Name Type Description
prefValue boolean

true to enable CodeMirror where possible on page load.

Source:
Save CodeMirror enabled preference.

setupFeatureLogging()protected #

Add hook handlers to log usage of CodeMirror features.

Source:
Add hook handlers to log usage of CodeMirror features.

showEditor()protected #

Reveal the editor and route jQuery.textSelection through it, as activate() does on the way in. Integrations that render no editor of their own should override this.

Source:

Reveal the editor and route jQuery.textSelection through it, as activate() does on the way in.

syncEditorContentsToSource()protected #

Sync the CodeMirror editor contents to the original textarea.

Source:
Sync the CodeMirror editor contents to the original textarea.

syncSelectionAndScrollPosition(from, to, scrollTop)protected #

Sync the selection and scroll position to the original textarea.

Parameters:

Name Type Description
from number
to number
scrollTop number
Source:
Sync the selection and scroll position to the original textarea.

toggle([force]) #

Toggle CodeMirror on or off from the textarea. This will call initialize if CodeMirror is being enabled for the first time.

Parameters:

Name Type Attributes Description
force boolean optional

true to enable CodeMirror, false to disable. Note that the ext.CodeMirror.toggle hook will not be fired if this parameter is set.

Fires:

Source:
Toggle CodeMirror on or off from the textarea.

loadLanguageSupport(mode, [config]) → {Promise.<LanguageSupport>}asyncstatic #

Load the ResourceLoader module for the given mode and build its language support.

Parameters:

Name Type Attributes Description
mode string
config Object optional

Passed to the mode. Only the mediawiki mode uses this.

Returns:

Type
Promise.<LanguageSupport>

Throws:

If the mode is unknown, or its module doesn't provide it.

Type
Error
Source:
Load the ResourceLoader module for the given mode and build its language support.

Type Definitions

Editor #

Anything that can hold an editor configuration: an EditorView, a CodeMirror instance, or a plain object with the two members below. That pair is all CodeMirrorExtensionRegistry and CodeMirrorPreferences need, so integrations without an EditorView can qualify by overriding state and dispatch().

Type:

Properties:

Name Type Description
state EditorState

The current state of the editor.

dispatch function

Applies a transaction to the editor. An EditorState is immutable, so implementations must store the state the transaction produces.

Source:

Anything that can hold an editor configuration: an EditorView, a CodeMirror instance, or a plain object with the two members below.

Events

'ext.CodeMirror.destroy'(textarea) #

Called just after CodeMirror is destroyed and the original textarea is restored.

Parameters:

Name Type Description
textarea HTMLTextAreaElement | ve.ui.Surface

The original textarea.

Source:
Called just after CodeMirror is destroyed and the original textarea is restored.

'ext.CodeMirror.initialize'(textarea) #

Called just before CodeMirror is initialized. This can be used to manipulate the DOM to suit CodeMirror (i.e. if you manipulate WikiEditor's DOM, you may need this).

Parameters:

Name Type Description
textarea HTMLTextAreaElement | ve.ui.Surface

The textarea or VisualEditor surface that CodeMirror is bound to.

Source:
Called just before CodeMirror is initialized.

'ext.CodeMirror.input'(update) #

Called when document changes are made in CodeMirror. The original textarea is not necessarily updated yet.

Parameters:

Name Type Description
update ViewUpdate
Source:
Called when document changes are made in CodeMirror.

'ext.CodeMirror.preferences.apply'(prefName, prefValue) #

Fired when a CodeMirror preference is changed or initially applied in a session. The preference may not have been saved to the database yet.

Parameters:

Name Type Description
prefName string
prefValue PrefValue
Source:
Fired when a CodeMirror preference is changed or initially applied in a session.

'ext.CodeMirror.preferences.display'(dialog) #

Fired when the preferences dialog is opened.

Parameters:

Name Type Description
dialog HTMLDivElement

The preferences dialog backdrop.

Source:
Fired when the preferences dialog is opened.

'ext.CodeMirror.preferences.ready'(preferences) #

Fired just before CodeMirrorPreferences has been instantiated.

Parameters:

Name Type Description
preferences CodeMirrorPreferences
Source:
Fired just before CodeMirrorPreferences has been instantiated.

'ext.CodeMirror.ready'(cm) #

Called just after CodeMirror is initialized.

Parameters:

Name Type Description
cm CodeMirror

The CodeMirror instance.

Source:
Called just after CodeMirror is initialized.

'ext.CodeMirror.toggle'(enabled, cm, textarea) #

Called when CodeMirror is toggled on or off.

Parameters:

Name Type Description
enabled boolean

true if CodeMirror is now enabled, false if disabled.

cm CodeMirror

The CodeMirror instance.

textarea HTMLTextAreaElement | ve.ui.Surface

The original textarea.

Source:
Called when CodeMirror is toggled on or off.