Correctly highlighting code using Shiki & PHP

July 11th, 2021

Highlighting code blocks correctly on your website is a more difficult problem to solve than you'd expect. There are many great solutions like Prism or Highlight.js, but they often have difficulty with newer syntax. Inspired by Miguel's blogpost, I set out to create a PHP wrapper around Shiki to do just that.

Shiki uses TextMate grammar to tokenize strings, and colors the tokens with VS Code themes. In short, Shiki generates HTML that looks exactly like your code in VS Code, and that really works great. TextMate grammars are updated frequently, most of the time as soon as a language updates, as people need them to be correct in their editor.

Shiki & PHP

The base of the package is Shiki-php, which in its essence is a wrapper around a node script that calls Shiki, we've also added a custom renderer that allows you to mark lines as highlighted, added, deleted or focused.

In addition to that package, we've built a commonmark highlighter extension which makes it easy to use in your own PHP powered blogs.

If you're using Statamic, I've also built an addon that provides a markdown fieldtype that renders your code with Shiki.

Examples

Below I'll add some examples of what our Shiki integration makes possible. My blog uses Shiki with a custom theme called ayu-light:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
{{ if songs === 1 }}
  <p>There is a song!</p>
{{ elseif songs > 100 }}
  <p>There are lots of songs!</p>
{{ elseif songs }}
  <p>There are songs.
{{ else }}
  <p>There are no songs.</p>
{{ /if }}
use Spatie\ShikiPhp\Shiki;

Shiki::highlight(
    code: '<?php echo "Hello World"; ?>',
    language: 'php',
    theme: 'github',
    theme: 'github-light',
);
use Spatie\ShikiPhp\Shiki;

Shiki::highlight(
    code: '<?php echo "Hello World"; ?>',
    language: 'php',
    theme: 'github',
);
use Spatie\ShikiPhp\Shiki;

Shiki::highlight(
    code: '<?php echo "Hello World"; ?>',
    language: 'php',
    theme: 'github',
);

MENU