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 | 7.4+ |
| Licença | GNU - Licença Pública Geral 2.0 ou superior |
| Transferência | README |
|
|
| 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 Help:Extension:CodeMirror.
In 2024–2025, the extension was upgraded to the new major version, CodeMirror 6, and with it many new features were added.
- For information about the older version, see Extension:CodeMirror/5.
- For help documentation, see Help:Extension:CodeMirror.
- For the JavaScript documentation, see wmdoc:CodeMirror.
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:Version da 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 but still allow users to disable it
$wgDefaultUserOptions[ 'usecodemirror' ] = true;
$wgCodeMirrorV6- Temporary feature flag to control the migration to CodeMirror 6 (T259059).
$wgCodeMirrorEnabledModes- Temporary feature flag to control conflicts with Extensão: CodeEditor.
$wgCodeMirrorConflictingGadgets- An array of gadget names that, if enabled, will prevent CodeMirror from loading. Defaults to wikEd.
$wgCodeMirrorPrimaryPreferences- The preferences to advertse 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. Use
trueorfalseto enable or disable a feature entirely, or provide an array containing namespace IDs (integers) or content models (strings). For example, to limit autocompletion to JavaScript pages and templates only, you could use:
# Limit CodeMirror autocompletion to JavaScript pages and templates
$wgCodeMirrorDefaultPreferences[ 'autocomplete' ] = [ CONTENT_MODEL_JAVASCRIPT, NS_TEMPLATE ];
| Funcionalidade | Compatibilidade editor 2017 |
Valor predefinido |
|---|---|---|
activeLine |
| |
autocomplete |
| |
autofocus |
| |
bidiIsolation |
| |
bracketMatching |
| |
codeFolding |
| |
closeBrackets |
| |
highlightRefs |
| |
lineNumbering |
| |
lineWrapping |
| |
lint |
| |
openLinks |
| |
specialChars |
| |
whitespace |
|
Diferenças de CodeMirror 5
Novas funcionalidades
- No longer requires the use of WikiEditor.
- Support for Scribunto, JavaScript, CSS and JSON, as an alternative to CodeEditor.
- Significant performance improvements.
- Right-to-left support (T170001) with bidi isolation (T358804).
- Code folding (T30684).
- Autocompletion (T95100).
- Linting (T381577).
- Quickly open links with modifier key + click (T303392).
- Improved search panel (T371436).
- CodeMirror preferences (T359498).
- Syntax highlighting on read-only pages (T301615).
- Syntax highlighting at Special:ExpandTemplates.
- Robust JavaScript API for integration with extensions, gadgets, and user scripts.
Depreciações e outras alterações
- The ResourceLoader modules are changing. See the migration guide.
- The
ext.CodeMirror.switchhook has been deprecated. Useext.CodeMirror.toggleinstead. - The
.cm-mw-mnemonicCSS class has been renamed to.cm-mw-html-entity. - The
.cm-mw-template-name-mnemonicclass has been removed. Use.cm-mw-template-ground.cm-html-entityinstead. - The
.cm-mw-apostrophes-boldand.cm-mw-apostrophes-italicCSS classes have been removed. Use .cm-mw-apostrophes instead. - Line-level styling for
<nowiki>,<pre>, or any tag without an associated TagMode has been removed (T351686). - Mixed languages within wikitext are not yet supported (T357480).
- The browser's native search functionality (using Ctrl+F) has been replaced with search functionality built into CodeMirror. This is necessary to maintain performance (T303664).
Guia de Migração
| Versão MediaWiki: | ≥ 1.44 |
This guide applies to MediaWiki 1.45 and later. All integrations should aim to be migrated by the release of MediaWiki 1.46 (release timeline).
Configuração do MediWiki
$wgCodeMirrorLineNumberingNamespacesestá obsoleto. Em vez deste, configure$wgCodeMirrorDefaultPreferences.
Módulos ResourceLoader
Ensure you're using the new .v6 modules.
Because CodeMirror 6 no longer relies on WikiEditor, there are some naming and behaviourial changes from the CodeMirror 5 counterparts:
Some module names are shown without the ext.CodeMirror prefix for brevity; replace the '…' when using.
| Módulo antigo | Novo módulo (MW 1.44) | New module (MW 1.45) | Novo módulo (MW 1.46+) | Descrição |
|---|---|---|---|---|
ext.CodeMirror
|
….v6.WikiEditor.init
|
….v6.init
|
….init
|
CodeMirror integration for WikiEditor on #wpTextbox1 (the normal editing textarea).
|
| N/A | ….v6.WikiEditor
|
….v6.WikiEditor
|
….WikiEditor
|
Exports the CodeMirrorWikiEditor class |
| N/A | ….v6.init
|
….v6.init
|
….init
|
CodeMirror for #wpTextbox1 and other supported pages.
|
….lib
|
….v6.init
|
….v6.init
|
….lib
|
Exports CodeMirror internals. |
….addons
|
N/A | N/A | N/A | This packaged the bracket matching feature in CodeMirror 5. Bracket matching is default behaviour in CodeMirror 6. |
….mode.mediawiki
|
….v6.mode.mediawiki
|
….v6.mode.mediawiki
|
….mode.mediawiki
|
The MediaWiki language mode. |
| N/A | ext.CodeMirror.v6
|
ext.CodeMirror.v6
|
ext.CodeMirror
|
Exports the CodeMirror class. |
….visualEditor
|
….visualEditor.init
|
….visualEditor.init
|
….init
|
Integration with the Editor de Texto Wiki 2017. |
….lib.mode.php
|
N/A | N/A | CodeMirror 6 will eventually provide some or all of these modes, but they will not be available as separate modules. | |
….lib.mode.clike
|
||||
….lib.mode.htmlmixed
|
||||
….lib.mode.xml
|
||||
….lib.mode.javascript
|
….v6.mode.javascript
|
….v6.modes
|
….modes
|
These languages are supported in CodeMirror 6. |
….lib.mode.css
|
….v6.mode.css
| |||
| N/A | ….v6.mode.lua
| |||
| N/A | ….v6.mode.json
| |||
| N/A | ….v6.mode.vue
|
With the release of MediaWiki 1.46, the old modules will be replaced with the new ones, and for some time the .v6 modules will be aliased before being removed entirely.
Comandos (scripts) do utilizador e gadgets
The CodeMirror global has been removed entirely.
For example, CodeMirror.fromTextArea( myTextarea ) will no longer work.
Instead, first load the desired ResourceLoader modules, instantiate a CodeMirror object, and call the initialize() method.
If your script relies on the ext.CodeMirror.switch hook to change the way it interacts with the editor, you'll need to use ext.CodeMirror.toggle instead, or alternatively listen to an event.
See the JavaScript integration section for more information.
CSS
The .CodeMirror element no longer exists. Use .cm-editor instead for the entire CodeMirror DOM, or .cm-content for the inner content (doesn't include the search panel, for example).
See deprecations and other changes to other CSS classes.
Integração
Extensões do MediaWiki
Using CodeMirror instead of CodeEditor
| Versão MediaWiki: | ≥ 1.44 |
As of MediaWiki 1.44, CodeMirror supports highlighting of the Lua, JavaScript, CSS, and JSON languages. It can be used as an alternative to Extensão: CodeEditor.
However, 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):
- Extensão: AbuseFilter – relies on CodeEditor for syntax highlighting of AbuseFilter syntax (T399673).
- Extensão: WikiLambda – the
ext.wikilambda.appmodule relies on CodeEditor (T400015).
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.
PHP hook
| Versão MediaWiki: | ≥ 1.44 |
Since MediaWiki 1.44, the preferred means to integrate with CodeMirror in PHP is implementing 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;
}
}
Register the hook in extension.json:
"Hooks": {
"CodeMirrorGetMode": "codemirror"
},
"HookHandlers": {
"codemirror": {
"class": "MediaWiki\\Extension\\MyExtension\\CodeMirrorHooks"
}
}
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.v6 module is loaded.
extension.json:
{
"attributes": {
"CodeMirror": {
"PluginModules": [
"ext.MyExtension.CodeMirror"
]
}
}
}
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 preformance, 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,[3] 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.v6 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.v6.mode.mediawiki, and for JavaScript, JSON, CSS, Vue and Lua, you'd use ext.CodeMirror.v6.modes:
const require = await mw.loader.using( [ 'ext.CodeMirror.v6', 'ext.CodeMirror.v6.mode.mediawiki' ] );
const CodeMirror = require( 'ext.CodeMirror.v6' );
const { mediawiki } = require( 'ext.CodeMirror.v6.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.v6.WikiEditor',
'ext.CodeMirror.v6.mode.mediawiki'
] );
const textarea = document.getElementById( 'wpTextbox1' );
mw.addWikiEditor( $( textarea ) );
const CodeMirrorWikiEditor = require( 'ext.CodeMirror.v6.WikiEditor' );
const { mediawiki } = require( 'ext.CodeMirror.v6.mode.mediawiki' );
const cmWe = new CodeMirrorWikiEditor( textarea, mediawikiLang() );
cmWe.mode = 'mediawiki';
cmWe.initialize();
Creating a new JavaScript instance:
const require = await mw.loader.using( [ 'ext.CodeMirror.v6', 'ext.CodeMirror.v6.modes' ] );
const CodeMirror = require( 'ext.CodeMirror.v6' );
const { javascript } = require( 'ext.CodeMirror.v6.modes' );
const cm = new CodeMirror( myTextarea, javascript() );
cm.initialize();
| Módulo | Descrição |
|---|---|
ext.CodeMirror.v6.lib
|
The core CodeMirror library. You shouldn't need to require this directly unless you need access to the upstream CodeMirror API. |
ext.CodeMirror.v6
|
The basic CodeMirror integration for MediaWiki editors. This module exports the CodeMirror class. |
ext.CodeMirror.v6.WikiEditor
|
CodeMirror integration for WikiEditor. This module exports the CodeMirrorWikiEditor class. |
ext.CodeMirror.v6.mode.mediawiki
|
Exports the mediawiki mode for highlighting MediaWiki wikitext.
|
ext.CodeMirror.v6.modes
|
Includes the modes javascript, json, css, vue and lua.
|
ext.CodeMirror.v6.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.
Parâmetros
|
ext.CodeMirror.preferences.change
|
Fired when a CodeMirror preference is enabled or disabled by the user.
Parâmetros
|
ext.CodeMirror.preferences.display(interno) |
Fired when the preferences panel is constructed, just before it is displayed.
Parâmetros
|
ext.CodeMirror.keymap(interno) |
Fired when the keyboard shortcut help dialog is opened. |
ext.CodeMirror.search(interno) |
Fired when the search panel is opened. |
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.v6.lib module to get access to the upstream CodeMirror API.
With this you can provide your own Extension when instantiating a CodeMirror or CodeMirrorWikiEditor instance.
For example, to provide your own Extension that reacts to changes made in CodeMirror:
await require = mw.loader.using( [ 'ext.CodeMirror.v6', 'ext.CodeMirror.v6.mode.mediawiki' ] );
const CodeMirror = require( 'ext.CodeMirror.v6' );
const { mediawiki } = require( 'ext.CodeMirror.v6.mode.mediawiki' );
// ext.CodeMirror.v6.lib is a dependency of ext.CodeMirror.v6, so it's already loaded at this point.
const { EditorView } = require( 'ext.CodeMirror.v6.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 existng CodeMirror instance:
// Ensure CodeMirror is initialized first
mw.hook( 'ext.CodeMirror.ready' ).add( ( cm ) => {
const { EditorView } = require( 'ext.CodeMirror.v6.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() );
} );
Consultar também
- User:Remember the dot/Syntax highlighter
- Extension:VisualEditor
- Extensão: WikiEditor
- Extensão: CodeEditor
- c:Category:MediaWiki extension CodeMirror
Notas
- ↑ Focus is always placed on the editor in the 2017 editor.
- ↑ Line wrapping cannot be disabled in the 2017 editor.
- ↑ phab:T384556
| 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: This is not an authoritative list. Some wiki farms/hosts and/or packages may contain this extension even if they are not listed here. Always check with your wiki farms/hosts or bundle to confirm. |
- Stable extensions/pt
- User interface extensions/pt
- GPL licensed extensions/pt
- Extensions in Wikimedia version control/pt
- EditPage::showEditForm:initial extensions/pt
- EditPage::showReadOnlyForm:initial extensions/pt
- GetBetaFeaturePreferences extensions/pt
- GetPreferences extensions/pt
- PreferencesFormPreSave extensions/pt
- SpecialPageBeforeExecute extensions/pt
- UploadForm:initial extensions/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 wiki.gg/pt
- Extensions included in WikiForge/pt
- Syntax highlighting extensions/pt
