Extensão: CodeMirror
- Não confundir com CodeEditor.
Estado de lançamento: estável |
|
|---|---|
| Implementação | Interface do utilizador |
| Descrição | Fornece destaque da sintaxe nos editores |
| Autor(es) | |
| Responsável(eis) | Community Tech |
| Última versão | 6.0.0 |
| Política de compatibilidade | Lançamentos de capturas de ecrã em conjunto com o MediaWiki. Original não é compatível com as versões anteriores. |
| PHP | 8.2+ |
|
|
| Licence | GNU - Licença Pública Geral 2.0 ou superior |
| Transferência | README |
| Ajuda | Help:Extension:CodeMirror/pt |
| Traduza a extensão CodeMirror se esta estiver disponível em translatewiki.net | |
| Problemas | Tarefas em aberto · Reportar um erro |
A extensão CodeMirror fornece um editor independente que fornece destaque de sintaxe highlighting em várias linguagens de programação e de marcação, incluindo texto wiki, utilizando a biblioteca CodeMirror. Este pode ser utilizado com outros editores, tais como WikiEditor, the Editor de Texto Wiki 2017, Proofread Page, e muito mmais. Para a utilização e uma lista de funcionalidades, consulte Ajuda:Extensão: CodeMirror.
Em 2024–2025, a extensão foi atualizada para a nova versão principal, CodeMirror 6, e com ela foram adicionadas muitas novas funcionalidades.
- Para a documentação de ajuda, consulte Ajuda:Extensão: CodeMirror.
- Para a documentação de JavaScript, consulte wmdoc:CodeMirror.
- Para informação sobre a versão anterior, consulte Extension:CodeMirror/5.
Instalação
- Exporte e coloque o ficheiro, ou ficheiros, num diretório chamado
CodeMirror, na sua pastaextensions/.
Developers and code contributors should install the extension from Git instead, using:cd extensions/ git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/CodeMirror
- Acrescente o seguinte código ao fundo do ficheiro $LocalSettings:
wfLoadExtension( 'CodeMirror' );
- Configure as required.
Pronto – Na página especial Special:Versionda sua wiki verifique se a extensão foi instalada.
Configuração
To enable CodeMirror for all users by default, add the following to your LocalSettings.php:
# Enables use of CodeMirror by default in wikitext, but still allow users to disable it
$wgDefaultUserOptions[ 'usecodemirror' ] = true;
If CodeMirror is being used instead of CodeEditor for code editing, a second user option, usecodemirror-code has effect, which by default is set to true.
$wgCodeMirrorEnabledModes- Temporary feature flag to control conflicts with Extensão: CodeEditor. See the Using CodeMirror instead of CodeEditor section below for more information.
$wgCodeMirrorConflictingGadgets- An array of gadget names that, if enabled, will prevent CodeMirror from loading. Defaults to wikEd.
$wgCodeMirrorPrimaryPreferences- The preferences to advertise in the in-editor preferences panel. These should have a clear visual effect or be commonly used to warrant easier access to toggling the feature. Preferences not listed here will still be available in the full preferences dialog.
$wgCodeMirrorDefaultPreferences- Control which features are enabled by default for all users. See below for more information.
$wgCodeMirrorDefaultPreferencesCode- Same as $wgCodeMirrorDefaultPreferences but applies to "code"; That is, any CodeMirror mode other than "mediawiki" (wikitext).
$wgCodeMirrorVisualEditorCustomHighlight- Experimental: highlight wikitext in the 2017 wikitext editor by painting syntax colors onto VisualEditor's own text via the CSS Custom Highlight API, instead of overlaying a CodeMirror EditorView.
Default preferences
The default preferences are set on either wikitext ($wgCodeMirrorDefaultPreferences) or all other "modes" such as JavaScript, CSS and JSON ($wgCodeMirrorDefaultPreferencesCode). For each feature, use true or false to enable or disable it entirely, or provide an array containing namespace IDs (integers) indicating where the feature should be enabled by default.
Note this configuration setting only applies to the default value. Users can override the defaults in their own CodeMirror preferences.
When changing a preference, it will apply only to either wikitext (the mediawiki mode) or non-wikitext (all other modes).
For example:
# Limit highlighting of whitespace to non-wikitext
$wgCodeMirrorDefaultPreferences[ 'whitespace' ] = false;
$wgCodeMirrorDefaultPreferencesCode[ 'whitespace' ] = true;
# Limit autocompletion to templates and code
$wgCodeMirrorDefaultPreferences[ 'autocomplete' ] = [ NS_TEMPLATE ];
$wgCodeMirrorDefaultPreferencesCode[ 'autocomplete' ] = true;
| Funcionalidade | Compatibilidade editor 2017 |
Valor predefinido | Default value (code)[1] |
|---|---|---|---|
activeLine |
|
| |
autocomplete |
|
| |
autofocus |
|
| |
bidiIsolation[4] |
|
N/A | |
bracketMatching |
|
| |
closeBrackets |
|
| |
closeTags[5] |
|
N/A | |
codeFolding |
|
| |
foldAllRefs[6] |
|
N/A | |
highlightRefs[7] |
|
N/A | |
lineNumbering |
|
| |
lineWrapping |
|
| |
lint |
|
| |
openLinks |
|
N/A | |
specialChars |
|
| |
theme |
default |
default
| |
trailingWhitespace |
|
| |
whitespace |
|
|
Integração
Extensões do MediaWiki
Using CodeMirror instead of CodeEditor
As of MediaWiki 1.47, all integrations except VisualEditor's "Code block" dialog will use CodeMirror unless configured otherwise.
| Versão MediaWiki: | ≥ 1.44 |
As of MediaWiki 1.44, CodeMirror can be used as an alternative to Extensão: CodeEditor.
Note however that not all extensions that integrate with CodeEditor have been updated to support CodeMirror. If you are using any of these extensions, you may want to keep CodeEditor installed on your wiki:
- Extension:VisualEditor – uses CodeEditor modules to power syntax highlighting for other extensions integrating with VisualEditor (T400014):
| Versões do MediaWiki: | 1.45 – 1.46 |
For MediaWiki 1.45 and 1.46, to use CodeMirror instead of CodeEditor, you'll need to adjust $wgCodeMirrorEnabledModes accordingly, along with the *UseCodeEditor and *UseCodeMirror settings for any applicable extensions you also have installed:
// Desired modes that should use CodeMirror (mediawiki, i.e. wikitext, is enabled by default)
$wgCodeMirrorEnabledModes['javascript'] = true;
$wgCodeMirrorEnabledModes['json'] = true;
$wgCodeMirrorEnabledModes['jsonc'] = true;
$wgCodeMirrorEnabledModes['css'] = true;
$wgCodeMirrorEnabledModes['lua'] = true;
$wgCodeMirrorEnabledModes['vue'] = true;
// If you're also using CodeEditor, disable the same modes there:
$wgCodeEditorEnabledModes['javascript'] = false;
$wgCodeEditorEnabledModes['json'] = false;
$wgCodeEditorEnabledModes['css'] = false;
$wgCodeEditorEnabledModes['lua'] = false;
$wgCodeEditorEnabledModes['vue'] = false;
// AbuseFilter (note that there is no corresponding "mode" that needs to be set above)
$wgAbuseFilterUseCodeEditor = false;
$wgAbuseFilterUseCodeMirror = true;
// Gadgets (for editing Gadget definition JSON pages)
$wgGadgetsDefinitionsUseCodeEditor = false;
$wgGadgetsDefinitionsUseCodeMirror = true;
// JsonConfig
$wgJsonConfigUseCodeEditor = false;
$wgJsonConfigUseCodeMirror = true;
// Scribunto (for editing Module pages that use the "lua" mode)
$wgScribuntoUseCodeEditor = false;
$wgScribuntoUseCodeMirror = true;
// TemplateStyles
$wgTemplateStylesUseCodeEditor = false;
$wgTemplateStylesUseCodeMirror = true;
// UploadWizard (for editing Campaign JSON pages)
$wgUploadWizardUseCodeEditor = false;
$wgUploadWizardUseCodeMirror = true;
Hook de PHP
| Versão MediaWiki: | ≥ 1.44 |
To add a new mode that should be recognized by CodeMirror, you should use the CodeMirrorGetModeHook interface:
class CodeMirrorHooks implements CodeMirrorGetModeHook {
public function onCodeMirrorGetMode(Title $title, ?string &$mode, string $model ): bool {
// Logic to determine if CodeMirror should be used
if ( $title->hasContentModel( 'JsonLikeContentModel' ) ) {
$mode = 'json';
return false;
}
return true;
}
}
Registar o hook em extension.json:
"Hooks": {
"CodeMirrorGetMode": "codemirror"
},
"HookHandlers": {
"codemirror": {
"class": "MediaWiki\\Extension\\MyExtension\\CodeMirrorHooks"
}
}
Extension attributes
There are several extension attributes that can be used to integrate with CodeMirror:
Registar uma nova etiqueta para o MediWiki
If you simply want CodeMirror to recognize a tag that is added by an extension, you can do so using the CodeMirrorTagModes extension attribute.
For example, to register the tag <foo> as something containing wikitext, you would add the following to extension.json:
{
"attributes": {
"CodeMirror": {
"TagModes": [
"foo": "mediawiki"
]
}
}
}
CodeMirror will then highlight the content inside <foo>…</foo> as wikitext.
Registering a tag so that CodeMirror treats the contents as something other than wikitext is currently not supported (T357480).
If a tag is not registered, CodeMirror will highlight the contents as non-wikitext in the same way it highlights the contents of a <nowiki>…</nowiki> tag.
Módulos de Plug-in
CodeMirrorPluginModules é um atributo de extensão que permite o carregamento de um módulo com CodeMirror.
This unconditionally loads the module whenever the ext.CodeMirror module is loaded.
{
"attributes": {
"CodeMirror": {
"PluginModules": [
"ext.MyExtension.CodeMirror"
]
}
}
}
ParserFunctionNsIds
If an extension registers a parser function that takes a page title, you can let CodeMirror know about it so that the "Open links with modifier key + click" feature works accordingly.
For example, Extensão:Scribunto registers the ID for the "Module" namespace with the {{#invoke:}} parser function as follows:
{
"attributes": {
"CodeMirror": {
"ParserFunctionNsIds": {
"invoke": 828
}
}
}
}
JavaScript
The CodeMirror editor is not an actual textarea, but a contenteditable. Usually developers need to ensure their code works with both given that CodeMirror can be toggled off.
For detecting changes to the document, using an event or a hook is likely the simplest. For reading and making changes, jQuery.textSelection may be convenient.
For more complex integrations or those who need better performance, you can add your own extension to a new or an existing CodeMirror instance.
Utilizar jQuery.textSelection
If you simply want to fetch or make changes to the document text, jQuery.textSelection is the easiest and most reliable means to do so. Usage of jQuery.textSelection on the textarea is bubbled up to CodeMirror, so you don't need to have any knowledge of whether CodeMirror is enabled:
const $textarea = $( '#wpTextbox1' )
const content = $textarea.textSelection( 'getContents' );
// Append "Foobar" to the content.
$textarea.textSelection( 'setContents', content + '\nFoobar' );
jQuery's .val() on #wpTextbox1 can be used,[9] but this isn't recommended and may not work in all editors, such as the Editor de Texto Wiki 2017.
Using ResourceLoader
The CodeMirror extension provides a number of ResourceLoader modules for use by user scripts, gadgets, and extensions.
To make use of CodeMirror, you'll need at minimum the ext.CodeMirror module, along with the desired "mode".
Modes can be unpacked from the ResourceLoader modules, using an exported method with the same name as the mode.
For MediaWiki wikitext, you'd use ext.CodeMirror.mode.mediawiki, and for JavaScript, JSON, CSS, Vue and Lua, you'd use ext.CodeMirror.modes:
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();
If you also want WikiEditor:
const require = await mw.loader.using( [
'ext.wikiEditor',
'ext.CodeMirror.WikiEditor',
'ext.CodeMirror.mode.mediawiki'
] );
const textarea = document.getElementById( 'wpTextbox1' );
mw.addWikiEditor( $( textarea ) );
const CodeMirrorWikiEditor = require( 'ext.CodeMirror.WikiEditor' );
const { mediawiki } = require( 'ext.CodeMirror.mode.mediawiki' );
const cmWe = new CodeMirrorWikiEditor( textarea, mediawiki() );
cmWe.mode = 'mediawiki';
cmWe.initialize();
Creating a new JavaScript instance:
const require = await mw.loader.using( [ 'ext.CodeMirror', 'ext.CodeMirror.modes' ] );
const CodeMirror = require( 'ext.CodeMirror' );
const { javascript } = require( 'ext.CodeMirror.modes' );
const cm = new CodeMirror( myTextarea, javascript() );
cm.initialize();
| Módulo | Descrição |
|---|---|
ext.CodeMirror.lib
|
The core CodeMirror library. You shouldn't need to require this directly unless you need access to the upstream CodeMirror API. |
ext.CodeMirror
|
The basic CodeMirror integration for MediaWiki editors. This module exports the CodeMirror class among other dependent classes and utilities. |
ext.CodeMirror.WikiEditor
|
CodeMirror integration for WikiEditor. This module exports the CodeMirrorWikiEditor class. |
ext.CodeMirror.mode.mediawiki
|
Exports the mediawiki mode for highlighting MediaWiki wikitext.
|
ext.CodeMirror.modes
|
Exports language modes that have a corresponding content model in MediaWiki. |
ext.CodeMirror.modes.extended
|
Exports numerous modes that don't have corresponding MediaWiki content models. See the auto-generated docs for the full list. |
ext.CodeMirror.VueComponent
|
Exports a Vue component for use as a standalone CodeMirror editor. |
ext.CodeMirror.init(interno) |
The main entrypoint for action=edit requests. Not intended for external use. |
ext.CodeMirror.visualEditor.init(interno) |
CodeMirror integration with the Editor de Texto Wiki 2017, and only for wikitext. |
Using hooks
You can also integrate with CodeMirror by using frontend hooks. These allow you to run code just before or after CodeMirror has loaded, or react to changes to the document.
| Hook | Descrição |
|---|---|
ext.CodeMirror.initialize
|
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).
Parâmetros
|
ext.CodeMirror.ready
|
Called just after CodeMirror is initialized.
Parâmetros
|
ext.CodeMirror.toggle
|
Called when CodeMirror is toggled on or off.
Parâmetros
|
ext.CodeMirror.destroy
|
Called just after CodeMirror is destroyed and the original textarea is restored.
Parâmetros
|
ext.CodeMirror.input
|
Called when document changes are made in CodeMirror. Note that the textarea may not be updated yet.
Parâmetros
|
ext.CodeMirror.preferences.ready
|
Fired just before CodeMirrorPreferences has been instantiated.
Parâmetros
|
ext.CodeMirror.preferences.apply
|
Fired when a CodeMirror preference is enabled or initially applied in an editing session.
Parâmetros
|
ext.CodeMirror.preferences.display(interno) |
Fired when the preferences panel is constructed, just before it is displayed.
Parâmetros
|
ext.CodeMirror.gotoLine(internal) |
Fired when the go-to line panel is opened or closed. |
ext.CodeMirror.keymap(interno) |
Fired when the keyboard shortcut help dialog is opened. |
ext.CodeMirror.search(interno) |
Fired when the search panel is opened or closed. |
Utilizar eventos
Using these events, you can integrate with CodeMirror using the same code as the original textarea:
myTextarea.addEventListener( 'keyup', ( event ) => {
console.log( event.key );
} );
Estendendo CodeMirror
You can import the ext.CodeMirror.lib module to get access to the upstream CodeMirror API.
With this you can provide your own Extension when instantiating a CodeMirror or CodeMirrorWikiEditor object.
For example, to provide your own Extension that reacts to changes made in CodeMirror:
const require = await mw.loader.using( [ 'ext.CodeMirror', 'ext.CodeMirror.mode.mediawiki' ] );
const CodeMirror = require( 'ext.CodeMirror' );
const { mediawiki } = require( 'ext.CodeMirror.mode.mediawiki' );
// ext.CodeMirror.lib is a dependency of ext.CodeMirror, so it's already loaded at this point
const { EditorView } = require( 'ext.CodeMirror.lib' );
const myExtension = EditorView.updateListener.of( ( /** @type {ViewUpdate} */ update ) => {
if ( update.docChanged ) {
// do something
console.log( update.changes );
}
} );
const cm = new CodeMirror( myTextarea, mediawiki() );
cm.initialize( [ cm.defaultExtensions, myExtension ] );
Or if you need to interact with an existing CodeMirror instance:
// Ensure CodeMirror is initialized first
mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
const { EditorView } = require( 'ext.CodeMirror.lib' );
const myExtension = EditorView.updateListener.of( ( /** @type {ViewUpdate} */ update ) => {
if ( update.docChanged ) {
// do something
console.log( update.changes );
}
} );
cm.applyExtension( myExtension );
} );
Another means of listening to changes is using the ext.CodeMirror.input hook:
mw.hook( 'ext.CodeMirror.input' ).add( ( update ) => {
// Print the ChangeSet to the console
console.log( update.changes.toJSON() );
} );
Release history
- novembro de 2024 – The CodeMirror 6 version of the extension was introduced as a beta feature.
- – After two years of development and testing, "Improved Syntax Highlighting" (CodeMirror 6) was officially promoted out of beta. This update brought advanced features like code folding, autocompletion, and linting to all users of the standard syntax highlighter, while significantly improving wikitext readability.[11]
Consultar também
- User:Remember the dot/Syntax highlighter
- Extension:VisualEditor
- Extensão: WikiEditor
- Extensão: CodeEditor
- EditorAPIs: A library that presents a common interface for wikitext editing. Support for the legacy editor, VE, 2017 source editor and CodeMirror 5/6.
- c:Category:MediaWiki extension CodeMirror
Notas
- ↑
$wgCodeMirrorDefaultPreferencesCode - ↑ Implemented separately in the 2017 editor and cannot be disabled.
- ↑ Focus is always placed on the editor in the 2017 editor.
- ↑ This feature is not yet stable.
- ↑ Only has an effect in wikitext.
- ↑ Only applicable to wikitext.
- ↑ Only applicable to wikitext.
- ↑ Line wrapping cannot be disabled in the 2017 editor.
- ↑ phab:T384556
- ↑ This event is not fired for wikitext (T401271)
- ↑ Tech News 2026 – Issue 17, Wikimedia Diff. Published April 20, 2026.
| Este extensão está a ser utilizado em um ou mais projetos da Wikimedia. Isso provavelmente significa que a extensão é estável e funciona bem o suficiente para ser usada por esses sites de alto tráfego. Procure o nome desta extensão nos arquivos de configuração CommonSettings.php e InitialiseSettings.php da Wikimedia para ver onde está instalado. Uma lista completa das extensões instaladas em um determinado wiki pode ser vista na página Special:Version do wiki. |
| This extension is included in the following wiki farms/hosts and/or packages: |
- Stable extensions/pt
- User interface extensions/pt
- EditPage::showEditForm:initial extensions/pt
- EditPage::showReadOnlyForm:initial extensions/pt
- GetPreferences extensions/pt
- SpecialPageAfterExecute extensions/pt
- UploadForm:initial extensions/pt
- GPL licensed extensions/pt
- Extensions in Wikimedia version control/pt
- All extensions/pt
- Extensions used on Wikimedia/pt
- Extensions included in Canasta/pt
- Extensions included in Fandom/pt
- Extensions included in Miraheze/pt
- Extensions included in MyWikis/pt
- Extensions included in ProWiki/pt
- Extensions included in Telepedia/pt
- Extensions included in Weird Gloop/pt
- Extensions included in wiki.gg/pt
- Syntax highlighting extensions/pt
