Quick Tip: How to Add Syntax Highlighting to Any Project
videos

Quick Tip: How to Add Syntax Highlighting to Any Project

Tutorial Details
    • Topic - Syntax Highlighting
    • Difficulty - Easy
    • Format - Screencast

In this lesson, we’ll use a JavaScript based syntax highlighter to quickly add a syntax highlighting functionality to any web project — even on a simple HTML page!


Step 1 — Download the Source Code

You can download the syntax highlighter source files here.


Step 2 — Drag the src Directory into your Project

I generally rename this folder to highlighter. Don’t delete anything within here, unless you don’t anticipate using some of the language specific JavaScript files.


Step 3 — Import the Necessary Files

Within your HTML file (or whichever page is responsible for displaying your view), import both the prettify.css and prettify.js files.

<!DOCTYPE html>

<html lang="en">
<head>
   <meta charset="utf&mdash;8">
   <title>untitled</title>
   <link rel="stylesheet" href="highlighter/prettify.css" />
</head>
<body>

<script src="highlighter/prettify.js"></script>

</body>
</html>	

Notice how we’ve placed our script at the bottom of the page, just before the closing body tag. This is always a smart move, as it improves performance.

Next, we need something to work with! The syntax highlighter will search for either a pre or code element that has a class of prettyprint. Let’s add that now.

<pre class="prettyprint">
(function() { 
   var jsSyntaxHighlighting = 'rocks';
})();
</pre>

Step 4 — Calling the prettyPrint() Function

The last step is to execute the prettyPrint() function. We can place this bit of code at the bottom of the page as well.

<!DOCTYPE html>

<html lang="en">
<head>
   <meta charset="utf-8">
   <title>untitled</title>
   <link rel="stylesheet" href="highlighter/prettify.css" />
</head>
<body>

<pre class="prettyprint">
(function() { 
   var jsSyntaxHighlighting = 'rocks';
})();
</pre>
<script src="highlighter/prettify.js"></script>
<script>prettyPrint();</script>
</body>
</html>	

If we now view the page in the browser…

final product

Well that was easy! But, as a final bonus step, what if we want to change the highlighter theme? In that case, it all comes down to editing the stylesheet how you see fit. Even better, there are a handful of stylesheets in the theme gallery that you’re free to use. I personally like the Desert theme. To apply it, copy the CSS from the link above, create a new stylesheet in your project, and paste the CSS into it. Next, update the stylesheet include from within the head section of your document.

<head>
   <meta charset="utf&mdash;8">
   <title>untitled</title>
   <link rel="stylesheet" href="highlighter/dessert.css" />
</head>
Desert Theme Applied

Seriously — can it get any simpler than that?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://coderbay.com Coderbay

    Good stuff. Thanks a lot.

  • http://codecanyon.net/user/RikdeVos/portfolio/?ref=RikdeVos Rik de Vos

    Cool! Is there any way to edit the code (using html5 contenteditable) after the code has been colored?

    I tried something like this with 2 divs laying on top of each other. The top div had transparent text and was contenteditable. Each time a key was pressed, the contents of the top div were copied to the bottom div and the function to color the text was executed. As a result, you had a text editor with syntax highlighting. The (only) problem was that it’s really really slow. So is there another way to do this? Is there a way to create a text editor with syntax highlighting using javascript?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      I’d use something like codemirror.net for that.

  • http://www.5jc.net huarong

    You can download the syntax highlighter source files here.

    The href to ‘here’ is wrong.

  • http://mimrankhan.com M.Imran Khan

    wow, easy as cake. Thanks.

  • http://thetechtime.com rax

    Download link in first step is wrong..
    it is : http://goo.gl/VfEE

    article is great ! :)

  • V

    the download link didn’t work for me…

  • V
  • http://evanrelf.com Evan Relf

    Mmmmm… dessert.css…

    • http://edwinhollen.com edwinhollen

      Hehe, ’twas the first thing I noticed as well. :D

      Quite frankly, this should, from now on, be a running gag in Nettuts+ tutorials.

  • Kyle Smith

    Awesome quick tip.

    This is handy for just about any developer, and Google makes it so easy to add custom “themes”…

    Jeffrey, just a little pet peeve: in the video you say “Desert” but you type “dessert”. Not a big deal whatsoever, and your tutorials are 1000x better then anything I could make; just wanted you to be aware in-case you ask your friends if they like the dessert.

    Also, do you know of anyone who is hosting prettify on a CDN? Thanks.

  • mukarram

    @Jeff ” Seriously — can it get any
    simpler than that? ”
    Nope! Its now much simplified!

  • irengba

    Good one.. What about a copy to clipboard option? That will be useful with this.

  • http://www.github.com/dotink/inkwell Matthew J. Sahagian

    I always find myself starting of with JS based syntax highlighting and moving very rapidly to PHP solutions like GeSHi… even though syntax being highlighted could be considered a “progressive enhancement” — I always feel like if I can highlight it for everyone, I should… you know, just in case that half a person out there browsing the web without JS happens to visit my page.

  • Zsolt Ébel

    Great article!

  • Fabien

    In responce to Irengba. I am not sure if it’s possible to implement the exact same thing in this syntax highlighter, or if it’s a super duper solution. Anyway. I made some syntax highlighter for fun once too. To make copy to clipboard pretty easy I made shift + click on the code appear a textarea, which would automatically be selected.

    You could see it in action here http://www.tessmore.nl/highlight

    But I dunno, it doesn’t support other languages than javascript nor is the copy to clipboard totally optimized. Anyway I found it working pretty well and a decent alternative to using an invisible Flash app on your website. Maybe some day browsers will be allowed to do copy to clipboard more effectively. But who knows.

    Also to rik de vos: Highlighting is probably done when the document is loaded and ready. So (if your familiar with javascript) you could take out the part that creates certain highlights, put it in a function and call it when you change something in the content editable part. This ofcourse wouldn’t be too efficient yet, but it is a nice start and the script shouldn’t take more then a ms to run anyway.

  • http://www.encoder2002.com Daniel Sitnik

    Another excelent quick tip Jeff!!

    By the way, the links to “Theme gallery” and “Desert” are also broken. :(

  • http://www.regalsweb.com John

    I think the auto-detection is cool. I know other highlighters where you have to specify the language, and I hate that. It seems to play well with using two languages in it as well.

  • http://acedesigns.co.za Anele

    I have seen and know how to use http://alexgorbatchev.com/SyntaxHighlighter/

    Preety neat tutorial….non the less

  • http://www.umbraprojekt.pl mingos

    I used to use this plugin in the past, but now I’ve settled for GeSHi. It’s written in PHP, so it only works on a server, and its learning curve is much steeper, but it allows for really extreme customisation. And it works with JavaScript turned off ;).

  • http://www.jeffadams.co.uk Jeff Adams

    Yay! Welcome back Jeff – I really missed these Quick Tips but this one is particularly good because I was looking for this exact thing last weekend!!

    I have a couple of tutorials on my blog (2 actually got published on ThemeForest.net) – I don’t like the default styling on the theme I’m using so I wanted something like this – I played with highlighter.js but to be honest it was too clunky for my liking.

    I’ll be sure to check this out – particularly love the line numbers thing.

    One thing though – you spent Desert wrong, you’ve used “dessert” :-P

  • http://danlamanna.com Dan LaManna

    That is a great really quick tip, on a somewhat unrelated note, since when is the type attribute not required for script tags? :)

  • http://8gramgorilla.com 8 Gram Gorilla

    Wow, that looks very awesome. Is there a WordPress plugin version? I’d like to find something that could highlight code in posts.

  • Gaurav Porwal

    Nothing is happening when i am using this code on firefox.. just showing black background but not changing color or text..

    • Gaurav Porwal

      Sorry i am using linux machine so there was some problem in file permission..

      Code is working very fine…… Thanks

  • http://www.isshtechnosoft.com/ flyer

    done a good job, Thanks!

  • Torzonhot

    can any body provide me the link for theme gallery

  • Dexter

    NIce One Jeffrey, Gonna use it on my blog… Thanks!

  • Morphius

    Hi Jeff,
    I use google-code-prettify on my site. It works fine, but I find the js folder to messy.

    Do you know how to recode the prettify.js so it will take the language files from a other folder

    like this:

    -js(folder)
    prettify.js
    custom.js
    -language(folder)
    lang-css.js
    lang-sql.js

    I hope U will be able to help me out!

    Keep up the good work!!!

    Grtz from the Netherlands

  • http://www.e-cart.dk Torben Gross

    Really cool tool

  • Badia

    can this be added to a textarea ?

  • http://rtyrggythy.ru ПКАвшнрепвпшлневлрл ронпа ллггн апе енднгп гндл пдгнекащлгн пдшгнп гнлд нна глн длгонп зжгш еп гнднгп гна лгнр дгн глн алгон гнп гнаглд пд
  • bhagwat

    i am trying to highlight text that is written in a textarea but this prettyfy thing does not work..could anyone help me out.

  • Sagar

    thnx a lot guys!

  • luis alberto

    my first comment in this page and I Just have to say awesome. this is what I’ve been searching

  • http://www.facebook.com/osc4life Jim Clarke

    Thank you for tutorial, I know I’m a little late to the conversation but has anyone else had problems with html table elements rendering? It appears to ignore the or but counts the line. I’ve tried other languages without issue. Thanks for any tips
    PS.
    I’m using table elements in a tutorial on coding email.