mkaz.blog

Wordpress

Code Syntax Highlighting in Gutenberg

I've developed a WordPress plugin which extends the core Gutenberg code block adding color syntax highlighting. If you are using Gutenberg to display code and want some color, install and check it out. It is available at github.com/mkaz/code-syntax-block.

I initially started to build as a separate block, but that introduced the issue of converting existing code blocks. While going through Riad's Gutenberg Extensibility Workshop I learned how to simply extend an existing core block, which is a great solution.

If you want to learn how to extend Gutenberg, check out that link, some good working examples to learn from. From creating different types of blocks, blacklisting and whitelisting blocks, and how to extend a core block.

Usage

Download the plugin, install and activate on your site.

In Gutenberg, add a code block as normal and then in the Inspector on the right, select the language for the block. If a language is not selected, no color will be applied.

The plugin uses the Prism library for syntax highlighting and enqueues the necessary scripts and stylesheet needed. Prism automatically adds color syntax to code blocks with the language class name.

Customize

Changing color theme, the default color theme is based off GHColors. You can download a new theme from the link above, or from the Prism themes repo. Download your customized css and replace assets/prism.css in the plugin directory.

The default install uses a limited set of languages from Prism: bash, css, clike, html/markup, git, go, javascript, json, php, python, react jsx, and sql. If your language is not included, you can build and download a new prism.js using this form. Just replace assets/prism.js with the new file. You will also need to edit the langs array in code-syntax.js and rebuild.

The Gutenberg block is built using standard Javascript workflow:

$ npm install
$ npm run build

Contribute

I've opened up a couple of issues in the Github repo which would be good features to address. If you come across any issues, please file a new ticket or request, or feel free to contribute a pull request to enhance.

Published: