Skip to content

PostHTML plugin for code syntax highlighting with Prism.

License

Notifications You must be signed in to change notification settings

posthtml/posthtml-prism

Repository files navigation

Prism Syntax Highlighting

Compile-time syntax highlighting for code blocks with Prism

Version Build License Downloads

Introduction

Before:

<pre><code class="language-javascript">
  const foo = 'bar'
  console.log(foo)
</code></pre>

After:

<pre><code class="language-javascript">
  <span class="token keyword">const</span> foo <span class="token operator">=</span> <span class="token string">'bar'</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span>
</code></pre>

Install

$ npm i posthtml posthtml-prism

Usage

const fs = require('fs')
const posthtml = require('posthtml')
const highlight = require('posthtml-prism')

const source = fs.readFileSync('./before.html')

posthtml([
    highlight({ inline: true  })
  ])
  .process(source)
  .then(result => fs.writeFileSync('./after.html', result.html))

Options

inline

Type: boolean
Default: false

By default, only <code> tags wrapped in <pre> tags are highlighted.

Pass in inline: true to highlight all code tags.

Styling

You will also need to include a Prism theme stylesheet in your HTML.

See PrismJS/prism-themes for all available themes.

Languages

By default, Prism loads the following languages: markup, css, clike, and javascript.

You can specify the language to be used for highlighting your code, by adding a language-* or lang-* class to the <code> tag:

<pre>
  <code class="language-php">
    $app->post('framework/{id}', function($framework) {        
      $this->dispatch(new Energy($framework));
    });
  </code>
</pre>

Skip highlighting on a node

You can skip highlighting on a node in two ways:

  1. add a prism-ignore attribute on the node:
<pre>
  <code prism-ignore>...</code>
</pre>
  1. or, add a prism-ignore class:
<pre>
  <code class="prism-ignore">...</code>
</pre>

In both cases, the prism-ignore attribute/class will be removed and highlighting will be skipped.