Wordpress

Syntax Highlight using Prism in WordPress

Prism is a lightweight, extensible, fast and simple highlighter. It is also used by some famous and popular websites like Mozilla, SitePoint and Drupal. Our website is also using Prism js for syntax highlighting.

Without a syntax highlighter our code look like

File file = new File("/home/ashish/error.txt");
FileReader is = new FileReader(file);
		
BufferedReader br = new BufferedReader(is);
String line;
String result = "";
while ( (line = br.readLine()) != null) {
	result += line + '\n';
}
br.close();
return result.split("\n");

But with prism syntax highlighter

File file = new File("/home/ashish/error.txt");
FileReader is = new FileReader(file);
		
BufferedReader br = new BufferedReader(is);
String line;
String result = "";
while ( (line = br.readLine()) != null) {
	result += line + '\n';
}
br.close();
return result.split("\n");

There are 7 themes available in Prism (Default, Dark, Funky, Okaidia, Twilight, Coy and Solarized Light). It supports a wide variety of languages (mostly all of languages you ever heard of). It also provides a lot of extensions also like line highlight, line numbers, autolinker, show language etc.

So lets start

  1. Go the download page of Prism.
  2. Select your theme. I wiil prefer ‘Coy’ theme.
  3. highlight syntax using prism

  4. Select the languages that you want to highlight in your website.

    Note : Do not select all languages as the size of javascript file (that prism will generate for you to download) will be increased.

  5. Select plugins. Plugins add some extra things to your code like adding displaying line numbers, showing highlighted language in top right corner of that code, preview color when hover on css color code and so on. My favourite plugin is ‘Line Numbers’ plugin.
  6. Goto the bottom of the page and download JS and CSS files.
    prism donwload
  7. Install plugin Prism Syntax Highlighter for WordPress
  8. Goto Plugins > Editor. Select ‘Prism Syntax Highlighter for WordPress’ plugin to edit.
  9. In the right side, under ‘Plugin Files’, open file prism/prism.css and replace its content with the contents of the css file that you downloaded from prism.
  10. Repeat the same process form prism/prism.js file, ie. replace its content with the js file that you downloaded from prism.
  11. That it.

Now if you have to beautify any code append the class. eg.

<pre><code class="language-bash line-numbers">ls
echo 'export PATH=$PATH:/home/username/nodejs/bin' >> /home/username/.bashrc</code></pre>

Output will be

ls
echo 'export PATH=$PATH:/home/username/nodejs/bin' >> /home/username/.bashrc

Leave a Reply

Your email address will not be published. Required fields are marked *