An open API service indexing awesome lists of open source software.

https://github.com/bhsd-harry/codemirror-mediawiki

Modified CodeMirror mode based on wikimedia/mediawiki-extensions-CodeMirror
https://github.com/bhsd-harry/codemirror-mediawiki

codemirror mediawiki mediawiki-gadget wikitext

Last synced: 6 days ago
JSON representation

Modified CodeMirror mode based on wikimedia/mediawiki-extensions-CodeMirror

Awesome Lists containing this project

README

        

[![npm version](https://badge.fury.io/js/@bhsd%2Fcodemirror-mediawiki.svg)](https://www.npmjs.com/package/@bhsd/codemirror-mediawiki)
[![CodeQL](https://github.com/bhsd-harry/codemirror-mediawiki/actions/workflows/codeql.yml/badge.svg)](https://github.com/bhsd-harry/codemirror-mediawiki/actions/workflows/codeql.yml)
[![jsDelivr hits (npm scoped)](https://img.shields.io/jsdelivr/npm/hm/%40bhsd/codemirror-mediawiki)](https://www.npmjs.com/package/@bhsd/codemirror-mediawiki)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/972fd5f6684c4fd8ac2f26e01d349948)](https://app.codacy.com/gh/bhsd-harry/codemirror-mediawiki/dashboard)

Expand

- [Description](#description)
- [Usage](#usage)
- [Constructor](#constructor)
- [Accessors](#accessors)
- [textarea](#textarea)
- [lang](#lang)
- [view](#view)
- [visible](#visible)
- [Methods](#methods)
- [extraKeys](#extrakeys)
- [getLinter](#getlinter)
- [getNodeAt](#getnodeat)
- [initialize](#initialize)
- [lint](#lint)
- [localize](#localize)
- [prefer](#prefer)
- [scrollTo](#scrollto)
- [setContent](#setcontent)
- [setIndent](#setindent)
- [setLanguage](#setlanguage)
- [toggle](#toggle)
- [update](#update)
- [Static methods](#static-methods)
- [getMwConfig](#getmwconfig)
- [replaceSelections](#replaceselections)
- [Extensions](#extensions)
- [allowMultipleSelections](#allowmultipleselections)
- [autocompletion](#autocompletion)
- [bracketMatching](#bracketmatching)
- [closeBrackets](#closebrackets)
- [highlightActiveLine](#highlightactiveline)
- [highlightSpecialChars](#highlightspecialchars)
- [highlightWhitespace](#highlightwhitespace)
- [highlightTrailingWhitespace](#highlighttrailingwhitespace)
- [highlightSelectionMatches](#highlightselectionmatches)
- [codeFolding](#codefolding)
- [scrollPastEnd](#scrollpastend)
- [colorPicker](#colorpicker)
- [escape](#escape)
- [tagMatching](#tagmatching)
- [refHover](#refhover)
- [hover](#hover)
- [openLinks](#openlinks)
- [Known issues](#known-issues)
- [Syntax Highlighting](#syntax-highlighting)

# Description

This repository contains a modified version of the frontend scripts and styles from [MediaWiki extension CodeMirror](https://www.mediawiki.org/wiki/Extension:CodeMirror). The goal is to support a standalone integration between [CodeMirror](https://codemimrror.net) and [Wikitext](https://www.mediawiki.org/wiki/Wikitext), without the need for a [MediaWiki environment](https://doc.wikimedia.org/mediawiki-core/master/js/).

Here is a [demo](https://bhsd-harry.github.io/codemirror-mediawiki). To experiment with the RTL (right-to-left) support, you can append `?rtl=1` to the URL.

Nonetheless, this repository also provides a customized version with additional functionality for use on a MediaWiki site. Browser editing tools such as [Wikiplus-highlight](https://github.com/bhsd-harry/Wikiplus-highlight) and an [InPageEdit plugin](https://github.com/inpageedit/Plugins) are built upon it. Please refer to a separate [README](./mw/README.md) file for the information.

# Usage

You can download the code via CDN, for example:

```js
// static import
import {CodeMirror6} from 'https://cdn.jsdelivr.net/npm/@bhsd/codemirror-mediawiki';
```

or

```js
import {CodeMirror6} from 'https://unpkg.com/@bhsd/codemirror-mediawiki';
```

or

```js
// dynamic import
const {CodeMirror6} = await import('https://cdn.jsdelivr.net/npm/@bhsd/codemirror-mediawiki');
```

or

```js
const {CodeMirror6} = await import('https://unpkg.com/@bhsd/codemirror-mediawiki');
```

# Constructor

Expand

**param**: `HTMLTextAreaElement` the textarea element to be replaced by CodeMirror
**param**: `string` the language mode to be used, default as plain text
**param**: `unknown` the optional language configuration
**param**: `boolean` whether to initialize immediately, default as true

```js
const cm = new CodeMirror6(textarea); // plain text
const cm = new CodeMirror6(textarea, 'mediawiki', mwConfig);
const cm = new CodeMirror6(textarea, 'html', mwConfig); // mixed MediaWiki-HTML
const cm = new CodeMirror6(textarea, 'css');
const cm = new CodeMirror6(textarea, 'javascript');
const cm = new CodeMirror6(textarea, 'json');
const cm = new CodeMirror6(textarea, 'lua');
```

# Accessors

## textarea

Expand

**type**: `HTMLTextAreaElement`
The textarea element replaced by CodeMirror, read-only.

## lang

Expand

*version added: 2.0.14*

**type**: `string`
The current language mode, read-only.

## view

Expand

**type**: [`EditorView | undefined`](https://codemirror.net/6/docs/ref/#view.EditorView)
The CodeMirror EditorView instance, read-only.

## visible

Expand

*version added: 2.1.3*

**type**: `boolean`
Whether the editor is visible, read-only.

# Methods

## extraKeys

Expand

*version added: 2.2.2*

**param**: [`KeyBinding[]`](https://codemirror.net/docs/ref/#view.KeyBinding) the extra key bindings
Add extra key bindings. Need initialization first.

```js
cm.extraKeys([
{key: 'Tab', run: () => console.log('Tab'), preventDefault: true},
]);
```

## getLinter

Expand

*version added: 2.1.3*

**param**: `Record` the optional linter configuration
**returns**: `Promise<(doc: Text) => Diagnostic[] | Promise>`
Get the default linting function, which can be used as the argument of [`lint`](#lint).

```js
const linter = await cm.getLinter(); // default linter configuration
const linterMediawiki = await cm.getLinter({include: true, i18n: 'zh-hans'}); // wikilint configuration
const linterJavaScript = await cm.getLinter({env, parserOptions, rules}); // ESLint configuration
const linterCSS = await cm.getLinter({rules}); // Stylelint configuration
```

## getNodeAt

Expand

*version added: 2.4.2*

**param**: `number` position
**returns**: [`SyntaxNode | undefined`](https://lezer.codemirror.net/docs/ref/#common.SyntaxNode)
Get the syntax node at the given position.

```js
const tree = cm.getNodeAt(0);
```

## initialize

Expand

*version added: 2.11.1*

**param**: `unknown` the optional language configuration
Initialize the editor.

```js
cm.initialize();
```

## lint

Expand

**param**: `(doc: Text) => Diagnostic[] | Promise` the linting function
Set the linting function.

```js
cm.lint(doc => [
/**
* @type {Diagnostic}
* @see https://codemirror.net/docs/ref/#lint.Diagnostic
*/
{
from: 0,
to: doc.toString().length,
message: 'error message',
severity: 'error',
},
]);
```

## localize

Expand

*version added: 2.3.3*

**param**: `Record` localization table
Set the localization table.

```js
cm.localize({
'Find': '查找',
});
```

## prefer

Expand

*version added: 2.0.9*

**param**: `string[] | Record` the preferred [CodeMirror extensions](https://codemirror.net/docs/extensions/)
Set the preferred CodeMirror extensions. Available extensions are introduced [later](#extensions).

```js
cm.prefer([
'allowMultipleSelections',
'autocompletion',
'bracketMatching',
'closeBrackets',
'highlightActiveLine',
'highlightSpecialChars',
'highlightWhitespace',
'highlightTrailingWhitespace',
'highlightSelectionMatches',
'codeFolding',
'scrollPastEnd',

// only available in MediaWiki mode
'escape',
'tagMatching',
'refHover',
]);
cm.prefer({
allowMultipleSelections: false,
autocompletion: false,
bracketMatching: false,
closeBrackets: false,
highlightActiveLine: false,
highlightSpecialChars: false,
highlightWhitespace: false,
highlightTrailingWhitespace: false,
highlightSelectionMatches: false,
codeFolding: false,
scrollPastEnd: false,

// only available in MediaWiki mode
escape: false,
tagMatching: false,
refHover: false,
});
```

## scrollTo

Expand

*version added: 2.6.2*

**param**: [`number | {anchor: number, head: number}`](https://codemirror.net/docs/ref/#state.SelectionRange.anchor) the position or range to scroll to, default as the current cursor position
Scroll to the given position or range. Need initialization first.

```js
cm.scrollTo();
```

## setContent

Expand

*version added: 2.1.8*

**param**: `string` new content
Reset the content of the editor. Need initialization first.

```js
cm.setContent('');
```

## setIndent

Expand

*version added: 2.0.9*

**param**: `string` the indentation string, default as tab
Set the indentation string.

```js
cm.setIndent(' '.repeat(2));
cm.setIndent('\t');
```

## setLanguage

Expand

**param**: `string` the language mode to be used, default as plain text
**param**: `unknown` the optional language configuration
Set the language mode.

```js
cm.setLanguage('mediawiki', mwConfig);
cm.setLanguage('html', mwConfig); // mixed MediaWiki-HTML
cm.setLanguage('css');
cm.setLanguage('javascript');
cm.setLanguage('json');
cm.setLanguage('lua');
```

## toggle

Expand

*version added: 2.1.3*

**param**: `boolean` whether to show the editor, optional
Switch between the CodeMirror editor and the native textarea. Need initialization first.

```js
cm.toggle();
cm.toggle(true); // show CodeMirror
cm.toggle(false); // hide CodeMirror
```

## update

Expand

Refresh linting immediately.

# Static methods

## getMwConfig

Expand

*version added: 2.4.7*

**param**: [`Config`](https://github.com/bhsd-harry/wikiparser-node/wiki/types#config) the [WikiLint](https://www.npmjs.com/package/wikilint) configuration
**returns**: `MwConfig`
Derive the configuration for the MediaWiki mode from WikiLint configuration.

```js
const mwConfig = CodeMirror6.getMwConfig(config);
```

## replaceSelections

Expand

*version added: 2.2.2*

**param**: [`EditorView`](https://codemirror.net/6/docs/ref/#view.EditorView) the CodeMirror EditorView instance
**param**: `(str: string, range: {from: number, to: number}) => string | [string, number, number?]` the replacement function
Replace the selected text with the return value of the replacement function.

```js
CodeMirror6.replaceSelections(cm.view, str => str.toUpperCase());
```

# Extensions

## allowMultipleSelections

*version added: 2.1.11*

Allow multiple selections. This extension also enables rectangular selections by holding down the `Alt` key.

## autocompletion

*version added: 2.5.1*

Provide autocompletion for MediaWiki, CSS and JavaScript modes.

## bracketMatching

*version added: 2.0.9*

Matched or unmatched brackets are highlighted in cyan or dark red when the cursor is next to them.

## closeBrackets

*version added: 2.0.9*

Automatically close brackets (`{`, `[` and `(`) and quotes (`"`, and `'` except for the MediaWiki mode).

## highlightActiveLine

Highlight the line the cursor is on in light cyan.

## highlightSpecialChars

Show invisible characters as red dots.

## highlightWhitespace

*version added: 2.0.12*

Show spaces and tabs as dots and arrows.

## highlightTrailingWhitespace

*version added: 2.0.9*

Highlight trailing whitespace in a red-orange color.

## highlightSelectionMatches

*version added: 2.15.3*

Highlight texts that match the selection in light green.

## codeFolding

*version added: 2.3.0*

Fold sections, templates, parser functions and extension tags in the MediaWiki mode, and code blocks in other modes.

Key bindings:

- `Ctrl` + `Shift` + `[`/`Cmd` + `Alt` + `[`: Fold at the selected text
- `Ctrl` + `Shift` + `]`/`Cmd` + `Alt` + `]`: Unfold at the selected text
- `Ctrl` + `Alt` + `[`: Fold all
- `Ctrl` + `Alt` + `]`: Unfold all

## scrollPastEnd

*version added: 2.15.3*

Allow the editor to be scrolled down past the end of the document.

## colorPicker

*version added: 2.18.0*

Provide color pickers for CSS and MediaWiki modes.

## escape

*version added: 2.2.2*

Key bindings:

- `Ctrl`/`Cmd` + `[`: Escape the selected text with HTML entities
- `Ctrl`/`Cmd` + `]`: Escape the selected text with URL encoding

## tagMatching

*version added: 2.4.1*

Matched or unmatched tags are highlighted in cyan or dark red when the cursor is inside.

## refHover

*version added: 2.17.1*

Show the content of the `` tag defined elsewhere when hovering.

## hover

*version added: 2.21.1*

Show the help information of a magic word when hovering.

## signatureHelp

*version added: 2.21.1*

Show the parser function signature when typing.

## inlayHints

*version added: 2.22.0*

Show inlay hints for anonymous parameters.

## openLinks

*version added: 2.19.6*

CTRL/CMD-click opens a link in a new tab.

# Known issues

## Syntax Highlighting

1. Preformatted text with a leading space may have false positives.
1. [Extension:Translate](https://www.mediawiki.org/wiki/Extension:Translate) is not supported.
1. Template parameter name followed by a newline ([Example](http://bhsd-harry.github.io/codemirror-mediawiki/tests.html#Templates%3A%20Handle%20comments%20in%20parameter%20names%20(T69657))).
1. Wikitext in template parameter names ([Example](http://bhsd-harry.github.io/codemirror-mediawiki/tests.html#Templates%3A%20Other%20wikitext%20in%20parameter%20names%20(T69657))).
1. Double URI encoding in link targets ([Example](http://bhsd-harry.github.io/codemirror-mediawiki/tests.html#Link%20containing%20%25%20as%20a%20double%20hex%20sequence%20interpreted%20to%20hex%20sequence)).
1. Double HTML escaping in link targets ([Example](http://bhsd-harry.github.io/codemirror-mediawiki/tests.html#Link%20containing%20an%20ampersand)).
1. Comments at the start of a line ([Example](https://bhsd-harry.github.io/codemirror-mediawiki/tests.html#1.%20Lists%20with%20start-of-line-transparent%20tokens%20before%20bullets%3A%20Comments)).
1. External link inside double brackets ([Example](http://bhsd-harry.github.io/codemirror-mediawiki/tests.html#Render%20invalid%20page%20names%20as%20plain%20text%20(T53090))).