editor

Docs › Blocks

Code blocks

Code blocks that keep line breaks and indentation, with a language.

For source code, config files and terminal commands, where characters and spaces must stay exactly as typed. Shown in a gray box with a monospace font.

Try it

Code for this demo

createEditor('#editor', {
  toolbar: 'heading | bold code | codeBlock | undo redo',
});

How to use

  • The codeBlock button or Ctrl+Shift+C turns the paragraph at the caret (or the selected paragraphs) into a code block, one line per paragraph.
  • Inside a code block the button turns each line back into a paragraph. Backspace at the very start does too.
  • Enter adds a line. Enter on an empty last line leaves the block.
  • Tab inserts two spaces.
  • On an empty line, type / and pick "Code block".
  • The selection bubble toolbar does not show inside code blocks.

Choosing a language

With the caret in a code block, a bar shows below it. The language you pick goes on <code> as class="language-…". The editor does not color the code; a highlighter on the reading page (Prism, highlight.js and the like) uses that class. The bar’s close button turns the block back into paragraphs.

ValueLanguage
(none)Plain text
html css js ts jsonHTML, CSS, JavaScript, TypeScript, JSON
bash python java kotlin php sqlShell, Python, Java, Kotlin, PHP, SQL
c cpp csharp go rust swift rubyC, C++, C#, Go, Rust, Swift, Ruby
xml yaml markdownXML, YAML, Markdown

Code inside a sentence

For a word or a short command, use the code button (Ctrl+E). With markdownShortcuts on, typing `code` in backticks works too. Markdown ``` fences come in through Markdown paste.

Saved HTML

<pre><code class="language-js">const editor = createEditor('#editor', {
  toolbar: 'board',
});</code></pre>
editor.exec('codeBlock');         // add / remove
editor.exec('codeBlock', 'php');  // add with a language
editor.exec('code');              // inline code

Presets

codeBlock is under ⋯ in the board and full presets. code (inline) is only in full.

Options

NameTypeDefaultDescription
codeBlocktoolbar item-Add or remove a code block (Ctrl+Shift+C)
codetoolbar item-Inline code (Ctrl+E)
markdownShortcutsbooleantrueIncludes the `code` typing shortcut