--- id: code-blocks title: Code blocks description: Handling code blocks in Docusaurus Markdown slug: /markdown-features/code-blocks --- import BrowserWindow from '@site/src/components/BrowserWindow'; import CodeBlock from '@theme/CodeBlock'; Code blocks within documentation are super-powered 💪. ## Code title {#code-title} You can add a title to the code block by adding a `title` key after the language (leave a space between them). ````md ```jsx title="/src/components/HelloCodeTitle.js" function HelloCodeTitle(props) { return

Hello, {props.name}

; } ``` ```` ```jsx title="/src/components/HelloCodeTitle.js" function HelloCodeTitle(props) { return

Hello, {props.name}

; } ```
## Syntax highlighting {#syntax-highlighting} Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out [this reference](https://github.com/mdx-js/specification) for the specifications of MDX. ````md ```js console.log('Every repo must come with a mascot.'); ``` ```` Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by [Prism React Renderer](https://github.com/FormidableLabs/prism-react-renderer). ```js console.log('Every repo must come with a mascot.'); ``` ### Theming {#theming} By default, the Prism [syntax highlighting theme](https://github.com/FormidableLabs/prism-react-renderer#theming) we use is [Palenight](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/themes/palenight.js). You can change this to another theme by passing `theme` field in `prism` as `themeConfig` in your docusaurus.config.js. For example, if you prefer to use the `dracula` highlighting theme: ```js title="docusaurus.config.js" module.exports = { themeConfig: { prism: { // highlight-next-line theme: require('prism-react-renderer/themes/dracula'), }, }, }; ``` Because a Prism theme is just a JS object, you can also write your own theme if you are not satisfied with the default. Docusaurus enhances the `github` and `vsDark` themes to provide richer highlight, and you can check our implementations for the [light](https://github.com/facebook/docusaurus/blob/main/website/src/utils/prismLight.mjs) and [dark](https://github.com/facebook/docusaurus/blob/main/website/src/utils/prismDark.mjs) code block themes. ### Supported Languages {#supported-languages} By default, Docusaurus comes with a subset of [commonly used languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js). :::caution Some popular languages like Java, C#, or PHP are not enabled by default. ::: To add syntax highlighting for any of the other [Prism-supported languages](https://prismjs.com/#supported-languages), define it in an array of additional languages. For example, if you want to add highlighting for the PowerShell language: ```js title="docusaurus.config.js" module.exports = { // ... themeConfig: { prism: { // highlight-next-line additionalLanguages: ['powershell'], }, // ... }, }; ``` After adding `additionalLanguages`, restart Docusaurus. If you want to add highlighting for languages not yet supported by Prism, you can swizzle `prism-include-languages`: ```bash npm2yarn npm run swizzle @docusaurus/theme-classic prism-include-languages ``` It will produce `prism-include-languages.js` in your `src/theme` folder. You can add highlighting support for custom languages by editing `prism-include-languages.js`: ```js title="src/theme/prism-include-languages.js" const prismIncludeLanguages = (Prism) => { // ... additionalLanguages.forEach((lang) => { require(`prismjs/components/prism-${lang}`); }); // highlight-next-line require('/path/to/your/prism-language-definition'); // ... }; ``` You can refer to [Prism's official language definitions](https://github.com/PrismJS/prism/tree/master/components) when you are writing your own language definitions. ## Line highlighting {#line-highlighting} ### Highlighting with comments {#highlighting-with-comments} You can use comments with `highlight-next-line`, `highlight-start`, and `highlight-end` to select which lines are highlighted. ````md ```js function HighlightSomeText(highlight) { if (highlight) { // highlight-next-line return 'This text is highlighted!'; } return 'Nothing highlighted'; } function HighlightMoreText(highlight) { // highlight-start if (highlight) { return 'This range is highlighted!'; } // highlight-end return 'Nothing highlighted'; } ``` ```` ````mdx-code-block ```js function HighlightSomeText(highlight) { if (highlight) { // highlight-next-line return 'This text is highlighted!'; } return 'Nothing highlighted'; } function HighlightMoreText(highlight) { // highlight-start if (highlight) { return 'This range is highlighted!'; } // highlight-end return 'Nothing highlighted'; } ``` ```` Supported commenting syntax: | Style | Syntax | | ---------- | ------------------------ | | C-style | `/* ... */` and `// ...` | | JSX-style | `{/* ... */}` | | Bash-style | `# ...` | | HTML-style | `` | We will do our best to infer which set of comment styles to use based on the language, and default to allowing _all_ comment styles. If there's a comment style that is not currently supported, we are open to adding them! Pull requests welcome. To accomplish this, Docusaurus adds the `docusaurus-highlight-code-line` class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your `src/css/custom.css` with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly. ```css title="/src/css/custom.css" .docusaurus-highlight-code-line { background-color: rgb(72, 77, 91); display: block; margin: 0 calc(-1 * var(--ifm-pre-padding)); padding: 0 var(--ifm-pre-padding); } /* If you have a different syntax highlighting theme for dark mode. */ [data-theme='dark'] .docusaurus-highlight-code-line { /* Color which works with dark mode syntax highlighting theme */ background-color: rgb(100, 100, 100); } ``` ### Highlighting with metadata string {#highlighting-with-metadata-string} You can also specify highlighted line ranges within the language meta string (leave a space after the language). To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the `parse-number-range` library and you can find [more syntax](https://www.npmjs.com/package/parse-numeric-range) on their project details. ````md ```jsx {1,4-6,11} import React from 'react'; function MyComponent(props) { if (props.isBar) { return
Bar
; } return
Foo
; } export default MyComponent; ``` ```` ```jsx {1,4-6,11} import React from 'react'; function MyComponent(props) { if (props.isBar) { return
Bar
; } return
Foo
; } export default MyComponent; ```
:::tip prefer comments Prefer highlighting with comments where you can. By inlining highlight in the code, you don't have to manually count the lines if your code block becomes long. If you add/remove lines, you also don't have to offset your line ranges. ````diff - ```jsx {3} + ```jsx {4} function HighlightSomeText(highlight) { if (highlight) { + console.log('Highlighted text found'); return 'This text is highlighted!'; } return 'Nothing highlighted'; } ``` ```` In the future, we may extend the magic comment system and let you define custom directives and their functionalities. The magic comments would only be parsed if a highlight metastring is not present. ::: ## Interactive code editor {#interactive-code-editor} (Powered by [React Live](https://github.com/FormidableLabs/react-live)) You can create an interactive coding editor with the `@docusaurus/theme-live-codeblock` plugin. First, add the plugin to your package. ```bash npm2yarn npm install --save @docusaurus/theme-live-codeblock ``` You will also need to add the plugin to your `docusaurus.config.js`. ```js {3} module.exports = { // ... themes: ['@docusaurus/theme-live-codeblock'], // ... }; ``` To use the plugin, create a code block with `live` attached to the language meta string. ````md ```jsx live function Clock(props) { const [date, setDate] = useState(new Date()); useEffect(() => { var timerID = setInterval(() => tick(), 1000); return function cleanup() { clearInterval(timerID); }; }); function tick() { setDate(new Date()); } return (

It is {date.toLocaleTimeString()}.

); } ``` ```` The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live. ```jsx live function Clock(props) { const [date, setDate] = useState(new Date()); useEffect(() => { var timerID = setInterval(() => tick(), 1000); return function cleanup() { clearInterval(timerID); }; }); function tick() { setDate(new Date()); } return (

It is {date.toLocaleTimeString()}.

); } ```
### Imports {#imports} :::caution react-live and imports It is not possible to import components directly from the react-live code editor, you have to define available imports upfront. ::: By default, all React imports are available. If you need more imports available, swizzle the react-live scope: ```bash npm2yarn npm run swizzle @docusaurus/theme-live-codeblock ReactLiveScope ``` ```jsx title="src/theme/ReactLiveScope/index.js" import React from 'react'; // highlight-start const ButtonExample = (props) => (