In many posts I show examples of source code. Previously, these examples were only included in simple <pre>
blocks. I’ve been looking for a better solution for a long time that should meet the following requirements:
- Use of
<pre>
is still possible so that I don’t have to laboriously rebuild existing articles. - Line numbers and syntax highlighting for all required languages and formats.
- Easy way to copy the texts with one click.
The solution is EnlighterJS. There is also an official WordPress plugin for this, which can be used both in the classic editor with TinyMCE and in Gutenberg. This is a JavaScript that automatically converts existing <pre>
elements with the appropriate attributes into an extended view in the browser. If JavaScript is not active, the block remains usable as a pure text section.
The integration into existing content is relatively easy: the existing <pre>
blocks only have to be given additional attributes so that they are recognized by EnlighterJS:
<pre class="EnlighterJSRAW" data-enlighter-language="generic"> ... </pre>
With the attribute data-enlighter-language
you define the programming language or format used for syntax highlighting or "generic"
for a generic format or "raw"
for text without any hightlighting.
In TinyMCE there is an additional button with which you can easily create such blocks. However, you can also simply add the information to the source text at any time.
In existing content, you can expand the blocks with the additional attributes – for this I updated the content directly in the database, which took about a little more than an hour. The advantage of this approach is that it doesn’t change the metadata of the posts, only the <pre>
sections are updated. Important for such actions: create a current backup of the database before each change. If you use a cache like Redis, you have to empty the cache afterwards so that the changed database contents are also used.
Adjustments for display
Despite the plugin works well, I still wanted to adjust a few points in the display:
- The corners of the code block are rounded – this is considered “modern” but I find it irritating.
- If the code block contains less than about 4 lines of text, there is not enough space for the action buttons.
- There is only one fixed font and not the font stack I defined for
<code>
or<pre>
elements.
Since this can not be adjusted in the backend settings my solution is an additional rule in my website’s stylesheet:
.enlighter-t-enlighter { border-radius: 0 !important; min-height: 3.5em !important; } .enlighter-default { font-family: Consolas, "Lucida Console", monospace !important; font-size: 0.875em !important; }
The minimum height of 3.5em
ensures that the action buttons remain operable even in short sections, like here:
An example.