Monday, July 21, 2008

Syntax Highlighting Code in Webpages

This post is deprecated. Please read my new entry on: "Upgrading to SyntaxHighlighter 3.0"

If you're a code blogger or someone who frequently posts code snippets online, then you'll know how difficult it can be to get your code highlighted and displayed nicely on your webpage. I have tried a number of different ways, such as saving code to HTML in SciTe or using Java2HTML to produce HTML files from Java and then copying the HTML output into my webpage. These processes are time-consuming and the HTML produced is ugly so I have always been on the lookout for something that will make code posting easier.

A few months ago, I stumbled across SyntaxHighlighter and it's just what I've been looking for! All you have to do is link your webpage to some CSS and JavaScript and surround your code with a tag saying which language the code is in. It's really that simple!

This is how you can use SyntaxHighlighter to highlight your code:

1. Download SyntaxHighlighter
This is an optional step. You don't necessarily have to download it because you can just link to the free hosted version. But if you have your own server you can download the latest version of SyntaxHighlighter here and upload it.

2. Link to CSS and Javascript
Open your webpage's HTML file and add links to the SyntaxHighlighter's CSS and JavaScript files. For optimal results, place these lines at the very end of your page, just before the closing body tag.

<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css"></link>
<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css"></link>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shLegacy.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js"></script>
<script type="text/javascript">
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>
It is not necessary to add the js files for all the languages - just for the ones you will be using.

3. Add Code
Now add the code you wish to highlight in your webpage, surrounded by the <pre> tag. Set the class attribute to one of the language aliases you wish to use, such as java, xml, sql, ruby etc.For example: brush:java

<pre title="Test SyntaxHighlighter" class="brush: java;">
public void printHello(){
    System.out.println("Hello World");
}
</pre>
4. View Page
View the webpage in your browser and you should see your syntax highlighted code snippet as:
public void printHello(){
    System.out.println("Hello World");
}

Configuration Options
Here are a couple of handy options. (Full list of here):

  • If you don't want to display the line numbers column, use the gutter option e.g. gutter:false.
  • If you don't want to display the top toolbar, use the toolbar:false option.
If you use an alternative to SyntaxHighlighter, share it with us in the Comments section!

Links:
SyntaxHighlighter Homepage

59 comments:

  1. Great job on this tutorial.

    However I would like to know whether is it possible to post VBA codes on blogger template ??

    Please help....

    ReplyDelete
  2. For VB, use:

    name="code" class="vb"


    The list of supported languages is here:
    http://code.google.com/p/syntaxhighlighter/wiki/Languages

    ReplyDelete
  3. Thanks for that info...

    I will reply back once done.

    AsSalaamAlaikum,
    Ilyas Kazi

    ReplyDelete
  4. Jazak Allah!

    I hv implemented here: http://automax-vba.blogspot.com

    Ilyas Kazi

    ReplyDelete
  5. thanx for sharing

    I just want to know how to remove the code line number when copying the snippet? Seems like the numbering still be added when copying even "nogutter" configuration is set.

    ReplyDelete
  6. I've already test it in my site
    Nice info

    ReplyDelete
  7. Hi Fahd,

    Thanks a lot for putting this together.

    I have made the Syntax Highlighter source code files available here:
    http://howard.ross.work.googlepages.com/syntaxhighlighting

    ReplyDelete
  8. Thanks for the write-up. Saved me the effort! You might want to make your example text reflect all the same paths. Your path in the last line of the clipboard points to js/ which is not consistent with the others, or how you use it on your page.

    I also found I had to change the default setting of blogger to not insert BR for linebreaks in the editor. Under Settings->Formating->Convert Line Breaks set to NO

    Do you have problems with the Blogger editor complaining about some of the code posted as well? For instance trying to post the example which had the link for the stylesheet triggers the Editor's code checking. Do you see the same?

    ReplyDelete
  9. Steve,

    I remember having similar problems, so switched to "Blogger in draft" which has improved raw HTML support. You can set it to ignore newlines instead of converting them to br tags.

    More info on blogger in draft here: http://bloggerindraft.blogspot.com/

    ReplyDelete
  10. I have fixed the paths.
    Good spot!

    ReplyDelete
  11. Fahd,

    As Azo asked, do u know how to eliminate row numbers while copying? Even though we set as 'nogutter' the problem still exist.

    When all selected and copied it shows row numbers. When some lines selected it shows hash (#).

    Could you fix it?

    ReplyDelete
  12. Anonymous10:02 AM

    thanks very much. this really helped me to get it working as i am not such an experienced user. now it works just perfect.

    ReplyDelete
  13. Thanks Fahd. It did me a great favor.

    BTW, would you mind my translation of this post to Chinese and post on my blog so that your post will then help more people?

    ReplyDelete
  14. Hi chzhcn,

    I'm glad you found it helpful. Feel free to post a chinese version of this on your blog.

    ReplyDelete
  15. I want to add it in my jsp files. But i am facing path problems as all pages are in different folders. Can you help me in this?

    ReplyDelete
  16. Your blog was great help.

    if you experience issues with "br" in output take a look at this: http://code.google.com/p/syntaxhighlighter/wiki/BloggerMode

    ReplyDelete
  17. hi
    Thanks for ur write ups

    And thanks to Jim Shingler also for leading me to solve the
    error

    ReplyDelete
  18. Thanks for writing this up. It's much better than the original doc on the main google site.

    ReplyDelete
  19. What is your settings for 'Convert line breaks' set to? In my case, if I set it to 'Yes', it's inserting <br /> into codes defined under <pre> tag.

    ReplyDelete
  20. Hi,

    A while a go I implemented this syntax highlighter as well on my own blog. In internet explorer 7 the loading speed is ok I think, but when loading one of my pages with syntax highlights in firefox, the page loads really slow. It causes the browser to freeze for a while

    However your blog loads really fast in a firefox browser.

    Would it be possible for you to have a look at one of my pages and tell me what I'm doing wrong? :-)

    (for instance: http://www.testingminded.com/2009/04/automatic-pagerank-checking-script.html)

    Many thanks!

    ReplyDelete
  21. Nevermind, I found the solution. The autoit brush has a size of 52 kb in comparison with others which only have a size of 4 kb. I commented out the UDF's regexp in the autoit brush.

    ReplyDelete
  22. Anonymous5:38 PM

    I keep getting a 'dp is undefined' error on the client. shCore is being included ok so what gives?

    ReplyDelete
  23. Anonymous7:30 AM

    Thank you SOOOOOOO much!! I didn't feel like digging around in the code to figure out how to use the damn thing.

    ReplyDelete
  24. Can you please give me a java code example to show how to use it properly to post code on blogspot.com.

    ReplyDelete
  25. Very helpful, but can you provide more insight as to how to use it for Blogger? You mentioned that we need to use Google Pages but can you elaborate more on that? Thank you very much!

    ReplyDelete
  26. This post is deprecated. Please read my new entry on: "Upgrading to SyntaxHighlighter 2.0"

    http://fahdshariff.blogspot.com/2009/09/upgrading-to-syntaxhighlighter-20.html

    ReplyDelete
  27. I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

    ReplyDelete
  28. hi, the latest version of SyntaxHighlighter is very good I like it.

    ReplyDelete
  29. This type of lace wig looks very realistic and is made from sophisticated lace material having the original look. Not just full lace wigs,lace front wigs,full lace wigs gives a natural character but lace wigs and lace front wigs also render a fashionable look to the face. The lace wigs in this wig usually appears as if it is growing out of the scalp and equally distributed. Some manufacturers now are trying to make their lace front human hair wigs inexpensive so that ladies who really need it can afford to buy it.

    ReplyDelete
  30. Anonymous3:25 PM

    Hi I am Hitesh Panchal,

    I have downloaded "SyntaxHighlighter_1.5.1" and create sample applcation in Dot NET. It works fine in InterNet Explorer but it not works with FireFox. (NO any Error Prompt)

    so any one know how can i do this ?

    Regards,
    Hitesh Panchal

    ReplyDelete
  31. Anonymous3:59 PM

    Your blog is really helps for my search and i really like it.. Thanks a lot..:)
    Term Papers Writing Services

    ReplyDelete
  32. Thank you. Couldn't get SyntaxHighlighter to work until I found you. Awesome! Thanks.

    ReplyDelete
  33. Thanks a billion..Fahd Shariff vai because i can not use syntaxhighlighting but by reading your post I have done it and i used here:
    http://knowledgediarybd.com/c-programming-2/difference-between-c-and-c/

    ReplyDelete
  34. Stunning publish! I in the beginning observed your site weekly or so in the past, and I want to subscribe to the RSS feed.
    website design

    ReplyDelete

  35. Thanks for sharing valuable Information, I really very impressive on your blog. I hope you continue on blogging job. Python course in Noida is where you can learn how to set up campaigns, generate and analyze personalized reports.

    Python Training In Noida
    Python Coaching In Noida
    Python Classes In Noida
    Best Python Training Institute In Noida

    ReplyDelete
  36. I am thankful to you that you Are sharing such valuable inforation, having read your Blog I am so impressed I hope you will be continue on blogging job. here data science training in greter noida is essential for professionals and students looking for a career as a data scientist.
    Data Science Training In Greater Noida
    Data Science Training In Greater Noida
    Data Science Training In Greater Noida
    Data Science Training In Greater Noida

    ReplyDelete
  37. Thanks for sharing such a great information with us. Your Post is very unique and all information is reliable for new readers.
    Keep it up in future, thanks for sharing such a useful post.
    CCC computer course is a special course that is designed to provide a basic level IT literacy program to an ordinary man.
    This course helps people learn basic things about computers, This course teaches how to use the Internet, how to send emails, how to make a business letter and access the small database.
    This course definitely helps housewives; business communities to keep their small accounts updated with any computer and can enjoy the facilities of information technology.
    To complete this course one can join CCC coaching in greater Noida.

    ccc coaching in greater noida
    ccc training in greater noida

    ReplyDelete
  38. I am exceptionally happy to see this post. It is fascinating and enlightening. Such a pleasant post, I am grateful and I like this post. Likewise I might want to share one thing which is an establishment for learning Digital Marketing, which is the most requesting now daily. For that, you can join at this connection
    Digital Marketing Training in Noida
    Digital Marketing coaching in Noida
    Digital Marketing institute in Noida
    Digital Marketing classes in Noida


    ReplyDelete
  39. I Am thankful to you that you Are sharing such valuable inforation, I Am very glad

    to read your blog I am so impressed I hope you will be continue on blogging job.

    Java increases productivity by enabling the inheritance of methods and properties

    from the well-organized Java Class Library. Participants will explore multi-threads

    and how they can improve the performance of applications.

    Java

    Training in Greater Noida

    Java Training Institute in Greater Noida
    Java

    Course in Greater Noida

    Java

    classes in Greater Noida

    ReplyDelete
  40. I am outstandingly glad to see this post. It is interesting and edifying. Such a lovely post, I am appreciative and I like this post. Moreover, I should need to share one thing which is a foundation for learning python, which is the most mentioning now every day. For that, you can join at this association

    Pythan Training in Greater Noida
    Pythan coaching in Greater Noida
    Pythan institute in Greater Noida
    Pythan classes in Greater Noida


    ReplyDelete
  41. I Am thankful to you that you Are sharing such valuable inforation, I Am very Impressed to read your blog I am so impressed I hope you will be continue on blogging job. Java increases productivity by enabling the inheritance of methods and properties from the well-organized Java Class Library. Participants will explore multi-threads and how they can improve the performance of applications.

    Java Training in Greater Noida
    Java Training Institute in Greater Noida
    Java Course in Greater Noida
    Java classes in Greater Noida

    ReplyDelete
  42. I would say to you thanks that you are shareing such a valuable information with

    us, I Am very glad to read your blog I am so impressed I hope you will be continue

    on blogging job. here you can learn in SEO new techniques or tricks, to acquire new

    approaches or just another point of view, is to do a SEO Positioning course.

    SEO

    Training In Greater Noida

    SEO

    Training Institute In Greater Noida

    SEO

    Classes In Greater Noida

    SEO

    Course In Greater Noida

    ReplyDelete
  43. Haveing seen your blog i am very happy thanks for shareing such valuable

    information keep continue this blogging job, here you can learn C language C is the

    precursor and inspirer for almost all the most popular high-level languages

    available today.

    C Language Training In Greater Noida
    C Language Training Institute In Greater Noida
    C Language Course In Greater Noida
    C Language Tranning In Greater Noida

    ReplyDelete
  44. Decent Post much obliged for sharing it's exceptionally valuable. This article gives me so much data.

    Data Science Training in Noida
    Data Science coaching in Noida
    Data Science institute in Noida
    Data Science classes in Noida


    ReplyDelete
  45. Thangs for shareing this Blog I am very happy to see this such a valuable

    information, you are doing good job keep continue on Blogging job here you can do

    C++ Training in Greater Noida at Mirorsoft Technologies It can be used for low-

    level programming, such as writing scripts for drivers and kernels, and also

    supports high-level programming language functions, such as writing scripts for

    software applications, etc.
    C++ Language Training In Greater Noida
    C++ Language Training Institute In Greater Noida
    C++ Language Course In Greater Noida
    C++ Language Classes In Greater Noida

    ReplyDelete
  46. The article is very interesting and very understood to be read, may be useful for the people. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it. I have to bookmark to check out new stuff on your post. Thanks for sharing the information keep updating, looking forward for more posts..
    Transformer Manufacturers In Pune | Transformer Manufacturers In Mumbai | Transformer Manufacturers In India

    ReplyDelete
  47. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!

    3d animation Company
    Best Chatbot Development Company
    Mobile app development in Coimbatore

    ReplyDelete
  48. This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site.

    Leather boots never go out of trend because of their class and superb finish. If you are also a fan of this fabric and looking forward to Buy Men Leather Boots Online, Sartojiva is here for you. Drop us your enquiry or dial our number now.

    ReplyDelete

  49. Thanks for sharing valuable Information, I really very impressive on your blog. I hope you continue on blogging job. TalktoAstro is a leading astrology prediction platform. Here you can talk to India’s best astrologers, tarot reader, Vastu experts or numerologists over call or order report with just Rs 100. Our mission is to provide exceptional services at a minimum cost. Get predictions related to love, marriage, career or finance from the comfort of your home with full privacy from Talktoastro experts.



    astrologer online

    free talk to astrologer

    astrologist online

    best online astrology consultation

    online astrologist

    talk to astrologer free

    ReplyDelete
  50. Wow, Fantastic Blog, it’s so helpful to me, and your blog is very good
    PCD Pharma Franchise Company

    ReplyDelete
  51. Great blog it’s useful for me, I am enjoy to read this, keep share like this type of helpful information.

    Indo American Health is providing Medical Tourism in India at very cheap rates that you can’t even have imagined. The rates are so budget friendly that there is no better place to get high-quality treatment without spending a fortune. Visit our website for further information.

    ReplyDelete