Jump to content

Extension:CodeMirror/ko

From mediawiki.org
This page is a translated version of the page Extension:CodeMirror and the translation is 0% complete.
Not to be confused with CodeEditor .
미디어위키 확장 기능 설명서
CodeMirror
출시 상태: 안정
구현 사용자 인터페이스
설명 Provides syntax highlighting in editors
만든 이
유지 보수자 Community Tech
최신 버전 6.0.0
호환성 정책 스냅샷은 미디어위키와 함께 릴리스됩니다. Master is not backward compatible.
PHP 8.2+
  • $wgCodeMirrorDefaultPreferencesCode
  • $wgCodeMirrorVisualEditorCustomHighlight
  • $wgCodeMirrorConflictingGadgets
  • $wgCodeMirrorEnabledModes
  • $wgCodeMirrorDefaultPreferences
  • $wgCodeMirrorPrimaryPreferences
Licence GNU General Public License 2.0 or later
다운로드
README
도움말 Help:Extension:CodeMirror/ko
CodeMirror 확장 기능 번역 (translatewiki.net에서 가능한 경우)
이슈 미해결 작업 · 버그 보고

The CodeMirror extension provides a standalone editor with syntax highlighting for a number of programming and markup languages, including wikitext, using the CodeMirror library. It can be used with other editors such as WikiEditor , the 2017 위키텍스트 편집기 , Proofread Page , and more. For usage and a list of features, see 도움말:확장:코드미러 .

In 2024–2025, the extension was upgraded to the new major version, CodeMirror 6, and with it many new features were added.

설치

  • 파일을 다운로드하고 CodeMirror 폴더를 extensions/ 디렉토리에 넣어 주세요.
    개발자와 코딩 기여자는 Git을 이용해 확장기능을 다운받는 것이 좋습니다.
    cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/CodeMirror
    
  • 아래의 코드를 LocalSettings.php 코드의 마지막에 추가합니다.
    wfLoadExtension( 'CodeMirror' );
    
  • Configure as required.
  • Yes 완료 – 위키의 ‘Special:Version’에 이동해서, 확장기능이 올바르게 설치된 것을 확인합니다.

Configuration

For customization of colors and CodeMirror's various features, see 도움말:확장:코드미러 .

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 확장기능:코드 편집기 . 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).

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;
$wgCodeMirrorDefaultPreferences
Feature 2017 editor
compatibility
Default value Default value (code)[1]
activeLine N false true
autocomplete N true true
autofocus Yes[2] true true
bidiIsolation[3] N false false
bracketMatching Yes true true
closeBrackets N false true
closeTags[4] N false false
codeFolding N true true
foldAllRefs [5] N false 알 수 없음
highlightRefs [6] Yes true 알 수 없음
lineNumbering Yes true true
lineWrapping Yes[7] true true
lint N false true
openLinks N true true
specialChars N true true
trailingWhitespace N false false
whitespace N false false

Differences from CodeMirror 5

New features

Deprecations and other changes

  • The ResourceLoader modules have changed. See the migration guide.
  • The ext.CodeMirror.switch hook has been deprecated. Use ext.CodeMirror.toggle instead.
  • The .cm-mw-mnemonic CSS class has been renamed to .cm-mw-html-entity.
  • The .cm-mw-doubleUnderscore CSS class has been renamed to .cm-mw-double-underscore.
  • The .cm-mw-template-name-mnemonic class has been removed. Use .cm-mw-template-ground.cm-html-entity instead.
  • The .cm-mw-apostrophes-bold and .cm-mw-apostrophes-italic CSS 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).

Migration guide

미디어위키 버전:
1.45

This guide applies to MediaWiki 1.45 and later. As of MediaWiki 1.46, CodeMirror 5 is no longer supported.

MediaWiki configuration

  • $wgCodeMirrorLineNumberingNamespaces is deprecated.

Configure $wgCodeMirrorDefaultPreferences instead.

ResourceLoader modules

Ensure you're using the correct ResourceLoader 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.

Old module Old module (MW 1.45) New module (MW 1.46+) Description
ext.CodeMirror ….v6.init ….init CodeMirror integration for WikiEditor on #wpTextbox1 (the normal editing textarea).
N/A ….v6.WikiEditor ….WikiEditor Exports the CodeMirrorWikiEditor class
N/A ….v6.init ….init CodeMirror for #wpTextbox1 and other supported pages.
….lib ….v6.lib ….lib Exports CodeMirror internals.
….addons 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 ….mode.mediawiki The MediaWiki language mode.
N/A ext.CodeMirror.v6 ext.CodeMirror Exports the CodeMirror class.
….visualEditor ….visualEditor.init ….visualEditor.init Integration with the 2017 위키텍스트 편집기 .
….lib.mode.php 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.modes ….modes These languages are supported in CodeMirror 6.
….lib.mode.css
N/A
N/A
N/A

With the release of MediaWiki 1.46, the old modules will be replaced with the new ones, and the .v6 modules will be removed entirely.

Gadgets and user scripts

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.

Integration

MediaWiki Extensions

Using CodeMirror instead of CodeEditor

미디어위키 버전:
1.44

As of MediaWiki 1.44, CodeMirror supports highlighting of the Lua, JavaScript, CSS, JSON, and Vue languages. It can be used as an alternative to 확장기능:코드 편집기 .

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:

As of MediaWiki 1.45+, for this to work, you'll need to adjust $wgCodeMirrorEnabledModes accordingly, along with the *UseCodeEditor and *UseCodeMirror 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['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;

Registering a new tag for MediaWiki

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

미디어위키 버전:
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"
	}
}

PluginModules

CodeMirrorPluginModules is an extension attribute that allows side-loading a module with CodeMirror. This unconditionally loads the module whenever the ext.CodeMirror 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 performance, you can add your own extension to a new or an existing CodeMirror instance.

Using 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,[8] but this isn't recommended and may not work in all editors, such as the 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();
ResourceLoader modules
Module Description
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.
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 Includes the modes javascript, json, css, vue and lua.
ext.CodeMirror.init
(internal)
The main entrypoint for action=edit requests. Not intended for external use.
ext.CodeMirror.visualEditor.init
(internal)
CodeMirror integration with the 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.

Frontend hooks
Hook Description
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).

Parameters

  • (HTMLTextAreaElement) The current "editor", most likely #wpTextbox1.
  • (ve.ui.Surface) The VisualEditor surface CodeMirror is bound to, if applicable.
ext.CodeMirror.ready Called just after CodeMirror is initialized.

Parameters

ext.CodeMirror.toggle Called when CodeMirror is toggled on or off.

Parameters

  • (boolean) Whether CodeMirror is now enabled.
  • (CodeMirror) The CodeMirror instance.
  • (HTMLTextAreaElement) The original textarea.
ext.CodeMirror.destroy Called just after CodeMirror is destroyed and the original textarea is restored.

Parameters

  • (HTMLTextAreaElement) The original textarea.
ext.CodeMirror.input Called when document changes are made in CodeMirror. Note that the textarea may not be updated yet.

Parameters

ext.CodeMirror.preferences.ready Fired just before CodeMirrorPreferences has been instantiated.

Parameters

ext.CodeMirror.preferences.apply Fired when a CodeMirror preference is enabled or initially applied in an editing session.

Parameters

ext.CodeMirror.preferences.display
(internal)
Fired when the preferences panel is constructed, just before it is displayed.

Parameters

  • (HTMLDivElement) The preferences panel container.
ext.CodeMirror.gotoLine
(internal)
Fired when the go-to line panel is opened or closed.
ext.CodeMirror.keymap
(internal)
Fired when the keyboard shortcut help dialog is opened.
ext.CodeMirror.search
(internal)
Fired when the search panel is opened or closed.

Using events

The following events are bubbled to the textarea for developer convenience:

Using these events, you can integrate with CodeMirror using the same code as the original textarea:

myTextarea.addEventListener( 'keyup', ( event ) => {
	console.log( event.key );
} );

Extending 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

  • 2024년 11월 – 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.[10]

See also

Notes

  1. $wgCodeMirrorDefaultPreferencesCode
  2. Focus is always placed on the editor in the 2017 editor.
  3. This feature is not yet stable.
  4. Only has an effect in wikitext.
  5. Only applicable to wikitext.
  6. Only applicable to wikitext.
  7. Line wrapping cannot be disabled in the 2017 editor.
  8. phab:T384556
  9. This event is not fired for wikitext (T401271)
  10. Tech News 2026 – Issue 17, Wikimedia Diff. Published April 20, 2026.