Skip to content

markdown-code

Handles fenced code blocks with optional language identifiers.

Details

PropertyValue
Namemarkdown-code
Priority100
TypeBlock
FactorymarkdownCode()

What It Handles

Fenced Code Blocks

Code blocks are delimited by three or more backticks or tildes:

markdown
```
plain code block
```

~~~
also a code block
~~~

Language Identifier

An optional language tag after the opening fence:

markdown
```javascript
const x = 42;
```

```typescript
const x: number = 42;
```

The language is added as a CSS class on the <code> element: <code class="language-javascript">.

Raw Content

Content inside code blocks is treated as raw text. No inline parsing occurs -- bold markers, headings, links, and other markdown syntax are displayed literally.

API

ts
import { markdownCode } from '@generative-dom/plugins';

const plugin = markdownCode();

No configuration options.

Rendering

Code blocks render as:

html
<pre><code class="language-javascript">const x = 42;
</code></pre>

Without a language tag:

html
<pre><code>plain code
</code></pre>

All content is set via textContent, never innerHTML. This means HTML tags in code blocks are displayed as literal text, not interpreted.

Edge Cases

  • Fence inside a fence: A longer fence always wins. If the opening fence is ```, a ```` inside the block does not close it.
  • Unclosed fence: If the stream ends without a closing fence, the content remains in the buffer waiting for more input. On flush(), unclosed fences are rendered as-is.
  • Empty code block: A fence with no content between opening and closing renders an empty <pre><code>.
  • Language tag with spaces: Only the first word after the opening fence is used as the language. ```javascript is fun sets the language to javascript.
  • Indented fences: Opening fences can be preceded by up to three spaces.
  • HTML in code: <script>alert('xss')</script> inside a code block renders as plain text, not executable HTML.

Interaction with highlight

The highlight plugin (priority 95) intercepts code blocks that have a recognized language tag before markdown-code gets a chance to handle them. For unrecognized languages, the match falls through to markdown-code for basic rendering.