I think the google-code syntax highlighter is one of the best available open source highlighters. However I could not find a good enough WordPress plugin that uses it. So here is a small WP plugin that does just that:
This plugin has prettify.js copied (unmodified) directly from google-code source browser. So your code will look exactly like it does on google-code.
Usage
You can use it as follows:
<pre class="prettyprint"> // Put your code here. </pre>
Here is a Scala example with the highlighter in action:
object Main {
def main(args: Array[String]) {
println("Hello world!")
}
}
Making Code HTML Safe
The plugin automatically makes highlighted code html-safe:
<pre class="prettyprint"> Anything that goes here will be quoted to appear on the page as-is. For example: <head></head><body></body> </pre>
To avoid quoting your code, add dontquote as the first class:
<pre class="dontquote prettyprint"> Remember to quote manually. For example: <head></head><body></body> </pre>
Line Numbering
Line numbdering can be enabled as follows:
<pre class="prettyprint linenums"> // Put your code here. </pre>
If you want to start with a line number 42, you can do the following:
<pre class="prettyprint linenums:42"> // Put your code here. </pre>
Highlighting Lines
When line numbering is enabled you can highlight one or several lines of code using the highlight class:
<pre class="prettyprint lang-YOURLANG linenums highlight:2,4"> // line 2 // line 3 // line 4 </pre>
Alternatively you can highlight one or several code segments:
<pre class="prettyprint lang-YOURLANG linenums highlight:1-3,5-6"> // line 2 // line 3 // line 4 // line 5 </pre>
Note: This feature is not available when line numbering is disabled.
Specifying Language
Most of the time the highlighter will do a good job guessing how to highlight the code. However, to achieve the best result, you should specify the language:
<pre class="prettyprint lang-YOURLANG"> // Put your code here. </pre>
Replace YOURLANG with one of the following:
- aea
- agc
- apollo
- bsh
- c
- cc
- cl
- cpp
- cs
- csh
- css-str
- cv
- cxx
- cyc
- default-markup
- el
- fs
- go
- hs
- htm
- html
- java
- js
- json
- lisp
- lua
- m
- ml
- mxml
- perl
- pl
- pm
- proto
- py
- rb
- scala
- scm
- sh
- sql
- vhd
- vhdl
- wiki
- xhtml
- xml
- xsl
- yaml
- yml
Changing Background
To adjust the background for all the code fragments add this to your css:
.prettyprint { background-color: #FAD4FF; }
Changing a single code fragment:
<pre class="prettyprint lang-YOURLANG" style="background-color: #FFE4BB;" > // Put your code here. </pre>
You can add a marker class to your css:
.special { background-color: #C0FFB3 !important; }
then use the marker when highlighting:
<pre class="prettyprint lang-YOURLANG special"> // Put your code here. </pre>
Please Support
If you like Prettify GC Syntax Highlighter plugin, please donate a minute of your time and vote for it. Thank you!
Thanks for this plugin. I have a question though. Is it possible to change the shortcode used? I have 2 sites with many code snippets throughout them which used
and I really don't want to go through each post to change them.Sorry for the second post, I also noticed lines don’t wrap, at least for the posts I tested it on. Long lines continue through the side of the blog post into the sidebar. Is there a wrap code or something I could use?
The plugin needs the right tags to work. You will have to mass-replace your <code> tags, either manually or using the following WP filter. Put this filter in the plugin php before any other filters:
function tags_code_to_pre($text) {
return preg_replace("/<code>(.*?)<\/code>/ise", "'<pre class=\"'.'prettyprint linenums'.'\">'.stripslashes('$1').'</pre>'", $text);
}
add_filter('the_content', 'tags_code_to_pre', 0);
About the word wrap: <pre> tags are designed to keep the text formatting, even when it’s too long. This is good for the code, since you can be sure the lines dont wrap, possibly changing the meaning of the program.
However, instead of lines going through the side of the post, a scrollbar should appear at the bottom. This is fixed in the new version that also brings line number support.
The scroll bar shows up now. I guess I should have been more selective when choosing my syntax highlighter a year ago. The filter would work, but i wasn’t using the native code tags and going through every snippet to change them is too much work to bother with. I will use this on my new site though, it seems very lightweight and displays code nicely.
I voted for it, thanks agian
Glad you like it. And thanks for voting!
Hi, Lex!
After evaluating several syntax highlighters for WordPress, I’ve finally decided that yours is the best one overall considering usability, consistency and quality. However, I miss the ability to highlight some lines with a different background color, to make it easier to reference just those lines in surrounding text.
Would it be possible to add that?
Hi Johann,
Thank you for the positive feedback. I have added a short tutorial on changing background color to this page. I could add a predefined set of colors to use as markers, but I think that plugin users would end up redefining those anyway. If you have anything particular in mind, please let me know.
Lex, while your addition is great, it’s not what I meant. I wanted a way to highlight a couple of lines in a listing, so that I can reference them after the listing. Like this:
pre class=”prettyprint highlight:4,5″
class FooBar
{
int field1; // line 3
int field2; // line 4 different background
int field3; // line 5 different background
}
The above would make the 4th and 5th lines have a different background color so that I can address those two lines in the text below the listing.
Lex, you can see an example of what I mean at Jesse Liberty’s blog post http://jesseliberty.com/2011/05/14/best-practices-for-local-databases/ where he highlights two lines to emphasize a chane in the code listing.
Now I get it. That is a neat feature, thank you for pointing it out, Johann. I will start working on it as soon as I get a chance.
Hi! First off all, thanks for your plugin, I’ve chosen it from numerous highlighters because it’s the cleanest. But the script size (40kb) really hurts, I hope you can find a way to minify it even further.
Anyhow, the reason why I posted here is that your plugin gets broken in IE6. Has anyone found a solution for it? Meanwhile, if ever you wanted to support IE6 without, you can try this simple solution in your WordPress.
<!–
<!–
If in case you have better solutions, please let me know. I’ll appreciate it. Again, great plugin. Thank you very much. ^^,
My bad, I forgot to change the brackets, again, here it is. Sorry for this.
<!–[if !IE 6]><!–>
<?php wp_head(); ?>
<!–<![endif]–>
<!–[if !IE 6]><!–>
<?php wp_footer(); ?>
<!–<![endif]–>
Hi Lex, it’s me again.
Sorry if I keep on coming back. It’s just that I’ve encountered some problems related with your plugin (sometimes, it’s not really the plugin per se, but the browsers) and was able to find a solution which I want to share.
This might help other people who are in the same situation that uses your plugin.
Here’s a short story:
- The previous solution was really bad just to disable your plugin from improperly implementing the <pre> tag’s line breaks in IE6, because I realized, it will remove all other WordPress features that would normally work in IE6.
- Then I came into a situation where I needed to include all the js files into a single js file to improve performance, making the previous solution not useful.
- In your js file, there’s an activation function called prettyPrint(); which is the only thing we need to be concerned of to implement the Google codes (and Onno’s) for syntax highlighting. So, here’s the solution I did to target IE6 from not using the plugin in order to display the line breaks properly, while making sure other browsers is not affected.
document.write(‘<!–[if !IE 6]><!–><script>prettyPrint();</script><!–<![endif]–>’);
And that’s it! Thanks again Lex for your plugin. Have a nice day. ^^,
Yet another IE6 problem. It would be best for everyone if that browser was phased out already. Thanks for the fix, EJelome.
Thanks for this plugin. As someone else said it is one of the cleanest I’ve found; and I’ve been looking for ages.
I’ve married it with another plugin that adds a TinyMCE pre tag button to the WordPress visual editor. I didn’t write the plugin, just so you know, but I think a pre tag button in the visual editor would benefit this plugin a great deal.
I have noticed what seems to be a fault with the dontquote class: it has to be placed ahead of the prettyprint class. Easy to workaround but maybe counter intuitive to many.
I have a question too: why is quoting set as default? I’m having to ‘dontquote’ all pre tags to prevent special characters being converted to HTML entities. It seems a little odd to me, lol.
To add to your answer to Zeak’s question, people wishing to update their old pre tags to add class attributes can use the Search Regex plugin to find and replace all instances of <pre> with <pre class=”…” >
Again, thanks for the plugin. I’ve written about it and given you a backlink.
I’ve noticed an incompatibility between this plugin and W3 Total Cache.
When W3 is activated, the syntax highlighting only shows when I’m logged into my site. I tried moving Prettify’s CSS and other files to my root directory and changing Prettify’s PHP file to reference the new location for its files but it made no difference (I’ve put them back as they should be).
Not sure which W3 setting is causing the problem. For now I’ve disabled W3. I’ll go through W3′s settings after I’ve slept then let you know what I find.
Hi Dion,
Thank you for the post mentioning the plugin. To address your concerns:
Code often contains comparisons, for example "if (a < b)". These will result in invalid HTML due to < and > symbols. Quoting prevents nasty HTML errors, which can lower your rating on search engines among other things. So I believe that enabling quoting is the best default.
It is not possible to detect if the closing </pre> tag is a part of the code or belongs to the enclosing pretty print tag. So the "dontquote" class is a workaround for allowing to post nested <pre> tags and manually adding extra formatting to your code using html tags.
I have tried W3 Total Cache plugin and found that Minify setting is the culprit. More specifically, W3 Cache breaks the highlighter plugin when minifying JavaScript files. You can try manual minification settings or simply disabling minification of the JavaScript.
Hi Lex, now I understand why you’ve used quoting as the default setting; but I’m still keeping the “dontquote” class as my default. If I don’t use it all my code displays on screen with HTML special characters converted to HTML entities when the front end is viewed in a browser.
Thinking about it, I’ve had problems with W3 Total Cache and its minifi settings in the past. Disabling minification of Javascript has solved the issue. Thank you for your help.
Thank you for making such a great plugin. It works great. Only thing I cannot get working is the line numbering. I get what looks like a middot instead of numbers. Is there any way I can explicitly tell the plugin to use decimals?
Thank you.
Glad you like the plugin.
About your problem: line numbering uses ordered lists. You may have a CSS definition that causes ordered list to have middots instead of numbers.
Hi Lex,
a happy new year to you!
Thanks a log for writing this plugin. I experience one problem though. I have added a wordpress shortcode (e.g. [csharp]…[/csharp] that adds the <pre> tags to the section I want to highlight. Highlighting in general works well, but at every line break two <br>s are added to the code. What am I doing wrong here?
Finally a smaller question: Is it possible (by means of modifying some js or css files) to override the default colors of the highlighting and the green bar on the left side?
Greetings,
Markus
Hi again,
just forget my last comment – the issued were just some kind of stupidity when parsing my shortcodes. Obviously the filters applied by your plugin need to be applied *after* the shortcodes have been parsed…
Again: Thanks for the great highlighter!