WordPress : How to highlight syntax code without using any plugins

WordPress highlighting syntax code without plugins

There are many WordPress plugins for highlighting programming code. Until now, I have used Crayon Syntax Highlighter on this blog and was satisfied with it, but at the time of the writing, the plugin was last updated more than 2 years ago, so I started looking for the non-plugin alternative. In the end, I chose to use Google code-prettify library. This article will show you how to implement this library into the WordPress and how to make it more versatile by using few CSS tricks.

At the moment, the WordPress plugin page for Crayon Syntax Highlighter is showing the following message:

This plugin hasn’t been tested with the latest 3 major releases of WordPress. It may no longer be maintained or supported and may have compatibility issues when used with more recent versions of WordPress.

It's never a good idea to have plugins that are no longer supported and the code-prettify library from Google is a good alternative. The library will do pretty good job on C based languages, JavaScript, HTML, while for other special case languages like F#, Scala, they are supported using extensions. Check the Prettify GitHub page for more information.

First, let's compare it with Crayon Syntax Highlighter, so you could have a better idea if the Prettify is a way to go.

Pro's
  • More lightweight.
  • Overall page size will be reduced.
  • Simpler to use as all you need is to insert a class name into a <pre> tag.
  • It is a project from GitHub, so it should be always up-to-date as oppose as the WordPress plugins, where often they rely on a single developer to maintain it.
  • The library is used by very popular websites like StackOverflow.
Con's
  • Less accurate Syntax detection.
  • As it is not a plugin, you need to do HTML encoding yourself.
  • No native line highlighting support.

First, we will configure the WordPress to support the library. Next, we will need to encode our syntax code to be HTML friendly and finally, we will enable it to highlight the code.

Note: All the work regarding the embedding code snippets that we want to show in our posts will be done in "Text editor" of WordPress and not on "Visual editor" when editing the post.

Step 1 - Setting code-prettify for WordPress

The library itself can be found on GitHub, but to set up the code-prettify to work with WordPress, we just need to add following line into header.php template file inside the <head> tag before <?php wp_head(); ?>.

<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
Note: The more correct way would be to add the script using the WordPress Enqueue functionality. For more information on how to accomplish that check this article.

Step 2 - HTML Encode the syntax code you want to show in your post

Next, we need to HTML encode our syntax code inside the post, as certain characters have special meaning in HTML and the browser will interpret them as a part of the HTML. The easiest way to achieve this is to find some online HTML encoder, like this one (shown below):

Encoding HTML for Prettify in WordPress

Click to Enlarge

Simply copy your syntax code inside the windows and click the 'Encode' button. You can leave the checkbox about converting all non-alphanumeric characters unchecked. Copy the encoded version from "Encode Result" window and paste it into the post editor in the WordPress.

Step 3 - Enabling the Google Prettify on the syntax code

After we copied the encoded syntax code, we need to do two things:

  1. Wrap it with <pre> tag.
  2. To make the highlighter work on the <pre> tag, we need to add a class="prettyprint" to it.

For example, if we want to show the following snippet of code:

function MyFunction( $result, $url ) 
{
...
}

Then in our post editor, the code would look like this:

<pre class="prettyprint">
function MyFunction( $result, $url ) 
{
...
}
</pre>

And this is it. For each new syntax code you want to add, simply repeat the steps 2 and 3.

In all the remaining sections of this article, we will focus on different ways to customize the prettify functionality.

Changing the default theme / skin

Google Prettify has four themes to choose from. You can check them out here.

To load a theme, we need to append a query string ?skin=SKINNAME to the run_prettify.js file we added in step 1. For example, to use "Desert" theme, we would put desert (all lower case) as a value like this:

 <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert"></script>

Using 3rd party themes

There are also 3rd party themes available like this Color themes for Google Code Prettify project. The steps to use a theme from this project are:

  1. Choose the color theme you want and copy the minimized version (.min.css) to your local computer.
  2. Copy that .min.css file into your WordPress theme folder.
  3. Reference that file inside the header.php file after the line <script src=".../run_prettify.js"></script> we added in step 1.

For example, if we copied github-v2.min.css inside our theme folder, we need to add the following line after the run_prettify.js file we added in step 1.

<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() . "/github-v2.min.css" ?>" type="text/css" />	

To make any further CSS changes to it, we can simply override them in our WordPress Theme stylesheet file. In the following example, we set the comments to be a green color:

pre.prettyprint .com {
    color: #080;
}
Note: Again, the correct way for adding styles is to use WordPress Enqueue functionality, but we can always fix that later.

Turning on line numbers

When we have a large block of syntax code with lots of lines, we can make it more readable by turning on line numbering. With Google Prettify, this is simply done by adding a linenums class to the <pre> tag, like so:

<pre class="prettyprint linenums">

This will only show line number for every 5th line, so we need to add the following CSS rule in styles.css to show the line numbers for every line:

li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 {
  list-style-type: decimal;
}

To change the background of the left side bar, where the line numbers reside, we add this:

pre.prettyprint.linenums {
    background: #dfefff;
}

This will also change most of the background where syntax code is shown. We will fix this in the next section.

And to change the color of numbers itself, we add:

ol.linenums {
    color: #5499de;
}

If not all digits are shown for the line numbers, we can fix that with padding:

pre.prettyprint.linenums ol {
    padding-left: 10px;
}

Coloring of the lines

To set the background where the syntax code is displayed, we use this:

li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 {
    background: #f7f7f7;
}

And to set the alternative rows to different colors, we do:

li.L1, li.L3, li.L5, li.L7, li.L9 {
    background: #eee;
}
Note: The coloring of alternative rows only works if the <pre> is using line numbering.

Highlighting the specific lines

One cool feature of the Syntax Highlighter plugin is the ability to highlight the individual lines to a highlighting color. As the prettify doesn't seem to have that feature, we need to make use of<span> elements and CSS to achieve the same effect.

Step 1 - Adding CSS rule

pre.prettyprint span.highlight {
  background: #fffee2;
  border-width: 1px;
  border-color: #e9e579;
}

We need to add one more CSS rule. To highlight the whole line, we need to make it display:block;, so we add this:

pre.prettyprint.linenums span.highlight {
	display:block;
}

Step 2 - Specify which lines to highlight

Now that we added CSS, we just need to wrap the code we want to highlight with <span> tag that will have .highlight class as shown below:

<span class="highlight">some code</span>
Note: We can highlight multiple lines with the single <span class="highlight"> tag, we just need to move the ending </span> where we want the highlighting to end.

How the highlighted line on syntax code with line numbering works is shown below:

some code
some code
some code
some code

When not using line numbering, only the syntax code will get highlighted and not the whole line:

some code
some code
some code
some code

Using inline code

Sometimes, we want to have syntax code to be inline. We can easily achieve this by using <code> tag instead of <pre>, like so:

<code class="prettyprint">...</code>

And to style it, we use this:

code.prettyprint {
...
}

Other issues and workarounds

When using the customization tricks, we will sometimes notice that things don't always work as we intended.

Problem with background colors when coloring lines

One issue I have noticed is in cases where the long syntax code creates a horizontal scrollbar. In those cases, only the original unscrolled section will have background colors as intended. My fix was to prevent scrolling all together by using white-space property for the <pre> tag:

pre.prettyprint {
  white-space: pre-wrap;
}

This will prevent scrolling and will instead wrap the long lines and it will work for both coloring every second row and for highlighted lines.

Forcing a comment color on whole syntax code

One drawback of Prettify compared to Crayon Syntax Highlighter is that you cannot specify which language you are using, so sometimes it misses the coloring of the syntax. A good example of this is when you want to show a commented code in php.ini, like this:

;always_populate_raw_post_data = –1

The above code will not be recognized as a comment, so to fix it, we can create a class that will force all the syntax to be in specific color:

pre.prettyprint.allcomment span {
	color:#080;
}

Then, we just add allcomment class inside <pre> tag like so:

<pre class="prettyprint allcomment">

Now, all the lines will be colored as a comment:

;always_populate_raw_post_data = –1

Conclusion

If we need to highlight the syntax code in our posts, there are many options to choose from. When using WordPress, the Crayon Syntax Highlighter plugin was and still is a very popular for this task. But it has been 2 years since the last update, so if you are looking for an alternative syntax code highlighter, the Google prettify library might be a good choice. In this article, we first examined how to set up the library for the WordPress, then we demonstrated how to use it and finally, we showed a few ways to customize it using CSS styles.

Share this page

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top