Syntax Highlighting
Author: Kev Quirk |
Hook:
on_render_markdown
Adds syntax highlighting to fenced code blocks in your posts using the highlight.php library.
Setup
- Install highlight.php via Composer, or download it manually into your Pure Blog install (e.g.
lib/Highlight/) - Add the hook to your
config/hooks.php - Create/update your
/config/update-ignorefile with the following:
# Third-party libraries not in the Pure Blog release
lib/Highlight
lib/HighlightUtilities
require_once __DIR__ . '/../lib/Highlight/Autoloader.php';
spl_autoload_register('\Highlight\Autoloader::load');
function on_render_markdown(string $html): string
{
return preg_replace_callback(
'/<pre><code class="language-([a-zA-Z0-9_+\-]+)">(.*?)<\/code><\/pre>/s',
function (array $m): string {
$lang = $m[1];
$code = html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5, 'UTF-8');
try {
$highlighter = new \Highlight\Highlighter();
$result = $highlighter->highlight($lang, $code);
return '<pre><code class="hljs language-'
. htmlspecialchars($result->language, ENT_QUOTES, 'UTF-8') . '">'
. $result->value
. '</code></pre>';
} catch (\Exception $e) {
return $m[0];
}
},
$html
) ?? $html;
}
You'll also need to include a highlight.js CSS theme in your layout. Browse available themes at highlightjs.org.