Skip to main content

CodeBlockExtension

Summary

The CodeBlock extension adds fenced code blocks to your editor. A code block contains a formatted snippets of source code.

info

This extension differs from the CodeExtension, which provides code marks on inline text.

info

Also check a more powerful code block implementation at CodeMirrorExtension.

Features

Formatting

Code blocks can be formatted for many different languages. For example, JavaScript code will be formatted differently from markdown or JSON code.

For a list of supported languages, please consult refractor, which we use under the hood.

Keyboard support

Users can create a new code block by typing ```  (3 ticks and a space). Users can define the language of the code block by typing ```html .

Usage

Installation

This extension is installed for you when you install the main remirror package.

You can use the imports in the following way:

import { CodeBlockExtension } from 'remirror/extensions';

Examples

Source code
import css from 'refractor/lang/css';
import javascript from 'refractor/lang/javascript';
import json from 'refractor/lang/json';
import markdown from 'refractor/lang/markdown';
import typescript from 'refractor/lang/typescript';
import { CodeBlockExtension } from 'remirror/extensions';
import { Remirror, ThemeProvider, useRemirror } from '@remirror/react';

const extensions = () => [
new CodeBlockExtension({
supportedLanguages: [css, javascript, json, markdown, typescript],
}),
];

const content = `
<pre><code data-code-block-language="typescript">function sayHello {
console.log('Hello world, TypeScript!')
}</code></pre>
<pre><code data-code-block-language="markdown">Hello _world_, **Markdown**</code></pre>
<pre><code data-code-block-language="css">.hello-world-css {
color: red;
}</code></pre>
<pre><code data-code-block-language="json">{
"hello-world": "JSON"
}</code></pre>
`;

const Basic = (): JSX.Element => {
const { manager, state } = useRemirror({ extensions, content, stringHandler: 'html' });

return (
<ThemeProvider>
<Remirror manager={manager} initialContent={state} autoRender />
</ThemeProvider>
);
};

export default Basic;

API