Friday, August 8, 2008

Source Code Syntax Highlighting for Blogs

Ever wanted to include syntax highlighted source code on your blog? Here's one way to do it (for Blogger):

First of all, you should disable automatic insertion of <br>, since those are shown verbatim if placed within <pre>-blocks. You do this under Settings -> Formating -> Convert Linebreaks (or similar, set it to "no").

Then you should include the highlighting script somehow. Go to Settings -> Layout and add a bottom element of type "HTML/JavaScript ". Then paste this in:

<style type="text/css">
.code {
    background-color:#F0FFEA;
    border:1px dashed #20A000;
    color:#000000;
    padding:6px 6px 6px 6px;
}

.code-line-numbers {
    color:#809080;
    border-right:1px dotted #809080;
    float:left;
    text-align:right;
    width:1.5em;
    padding-right:3px;
    margin-right:12px;
}

.code-code {
    /* This is the box around the actual code 
    (as opposed to .code which is both the 
    code and the line numbers) */
}

.code-keyword {
    font-weight: bold;
    color: #000000;
}

.code-type {
    font-weight: bold;
    color: #106020;
}

.code-variable {
    color: #004050;
}

.code-number {
    color: #F08000;
}

.code-comment {
    color: #208000;
}

.code-string {
    color: #F00000;
}
</style>
<script type="text/javascript" 
src="http://highlighter.ahnfelt.dk/CodeHighlighter.js">
</script>
<script type="text/javascript">
CodeHighlighter.highlightAll();
</script>

The last few lines load and apply the highlighting. Insert true between the parenthesis in the call to highlightAll to enable line numbers. You could also use another highlighter if you tweaked the above a little.

Now hit save. You're done! To include code in your blog comments, you must write it like <pre class="code XXX">CCC</pre> where XXX is the language name (for example java) and CCC is your code. One example is:

<pre class="code java">
public class VisitorDemo {
    static public void main(String[] args) {
        Car car = new Car();
        Visitor printVisitor = new PrintVisitor();
        Visitor doVisitor = new DoVisitor();
        printVisitor.visitCar(car);
        doVisitor.visitCar(car);
    }
}
</pre>

Which will show up as:

public class VisitorDemo {
    static public void main(String[] args) {
        Car car = new Car();
        Visitor printVisitor = new PrintVisitor();
        Visitor doVisitor = new DoVisitor();
        printVisitor.visitCar(car);
        doVisitor.visitCar(car);
    }
}

You may sometimes have to escape < and > with the corresponding codes &lt; and &gt;. The preview won't show the code as highlighted, but it will be when you hit save.

Now it's time to chose the colors and style you want for your code. Go back to editing the <style type="text/css"> code. It's CSS as you probably know, and it decides nearly everything about how your code looks. If you need more languages, you can ask me to add them or modify the source code and compile it yourself.

That's it, you're done!

48 comments:

Unknown said...

Very useful, and I used it (see http://mondorux.blogspot.com).
Would You like to add latex highlighting?
The rule could be:
{
names: ["tex", "latex"],
rules:
common.ignorable,
Flat("keyword", ~/^(\\[a-zA-Z]+)/),
Flat("keyword", ~/^(\{|\})/),
Flat("comment", ~/^([%]*[^\n]*)/),
Flat("", ~/^[^\\{}]+/),
],
}
Sorry, I couldn't use <pre class="code java"> in this comment :).

Ahnfelt said...

Thank you for the contribution! I extended it a bit to highlight some extra characters basically, and I've put it into the highlighter download.

durandal said...

Hi Ahnfelt,

I landed here after poking around on your Sourceforge profile.

Try as I might, I cannot get Blogger's compose tool to leave C++ code alone, no matter if it is wrapped in < pre >, or if I use HTML escape characters.

Do you simply avoid using it?

Paul

durandal said...

PS: Thanks for the PNGwriter bug reports. I left a reply on the forum just now.

Paul

Ahnfelt said...

I use both <pre> and entities (escape characters). It's not very copy-paste friendly I'm afraid.

Anonymous said...

Ja.. det rejser uden tvivl nogle spørgsmål.
Mvh,
Nickie, frokostordning

yoob games said...

Yoob.net update new-best free games online from internet. Play free action games, free addicting games, puzzle games, sports games, girls games and adventure games online. ..and more. Visit and play funny games at Yoob.net.

8 ball pool said...

I just want to say thanks for your wonderful post, it is contain a lot of knowledge and information that i needed right now. You really help me out my friend, thanks!
halloween| animal jam| happy wheels| cool math games| 8 ball pool| sudoku| yoob| friv| tetris| friv4school| monster high

Unknown said...

I just want to say : why you do not click to play
puzzle games | mario games | brain games | tetris | happy wheels | agario | super mario

happy wheels games said...

I just want to say : why you do not click to play
puzzle games | mario games | brain games | tetris | happy wheels | agario | super mario | abcya

Anonymous said...

Yoobgames update new-best free games online from internet. Play free action games, free addicting games, puzzle games, sports games, girls games and adventure games online. ..and more. Visit and play funny games at yoob games

Mario Games said...

Busy life circumstances than the current world history.
Mario Friv Doraemon Games Kizi Yoob
Thanks so much!

Unknown said...

I want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog!
Science Kombat | Science Kombat Game | slither io | wings io | wingsio | Tank trouble | Tank trouble 2 | Tank trouble 3 | Tank trouble 4

Unknown said...

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work.

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
Sign in to Gmail to access to all Gooogle services. Log in to your account or sign up to create a new account
gmail sign in

gmail log in

what's gmail?

slitherio

Tank trouble

happy wheels

Strike Force Heroes

tank trouble 2

In this game, you start at the cavern men's age, then evolve! There is a total of 5 ages, each with its units and turrets. Take control of 16 different units and 15 different turrets to defend your base and destroy your enemy.
age of war

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work.
happy wheels

strike force heroes

earn to die

Fireboy and Watergirl arrived again to the temple in the forest. 2 players together can help them to find their way out.
fire boy and water girl

Unknown said...

This content is written very well. Your use of formatting when making your points makes your observations very clear and easy to understand. Thank you.
- usps tracking
- iphone 7 release date
- excel

Five Nights At Freddy's said...

Thanks for giving me the useful information. I think I need it!
Happy Wheels , FNAF World , Five Nights At Freddy's

Friv 1000 said...

Oh. This post very happy. Thanks so much and I like this.
Please visit adress Yoob , Friv , Doraemon , Kizi

Unknown said...

You need to have time to take care of the kids active. Please visit our website and play exciting flash games.Thanks you for sharing!
Twizl | friv2018 | y5games | friv games | ozov games

Yoob said...

Y8 | Juegos de Twizl | Twizl Juegos | Twizl
Twizl.juegos - Jugar juegos gratis de acción, juegos adictivos, juegos de rompecabezas, juegos de deportes, juegos de chicas y juegos de aventura en línea. ..y más. Muy juegos divertidos en Twizl.juegos.

Unknown said...

The blog or and best that is extremely useful to keep I can share the ideas. Age Of War 2
Big Farm | Slitherio | Tank Trouble
Of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
Happy Wheels | Goodgeme Empire | Slither.io


Unknown said...

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Discover our website bounty of free online games now!
Our website has the biggest collection of free online games. Totally new games are added every day!

age of war 2| gold Miner 2| unfair Mario 2 | cubefield 2 |tanki Online 2

Unknown said...

This is one of the cult game now, a lot of people enjoy playing them . Also you can refer to the game :
gold mine strike | pokemon go 2
The game controls are shown just under . Movement mechanisms primarily include acceleration and tilting controls.
stickman games | stick war 2 | animal jam 2

HayleePh said...

Thanks for the job post. For more of such kind of jobs, you can refer to the link below.
friv100 | zoxy 3 | Friv 10 |agar.io |

Newbie said...

Troll Face Quest Video Games. Play. Troll Face Quest Video Games · Y10 City Heroes. the best free online Twizl games, juegos Twizl, jogos Twizlfrom the top game developers all over the world. Zoxy is the best entertainment site with free games.

Newbie said...

Best of friv 4 Games game series are waiting for you! Kizi 100 Games is a great place to play free online juegos kizi game, sport, girl, including puzzle, boy and more juegos de kizi 100 game! Enjoy and play Kizi!

cara menggugurkan kandungan said...

for beginners like me need a lot of reading and searching for information on various blogs. and articles that you share a very nice and inspires me

Friv 10 games said...

I liked it so much and very interesting, too! Thanks for sharing the experience.
Wonderful post, really great tips and advice.
friv 3
friv 4
kizi 2
friv.org

Unknown said...

This is a very good article material and it is very useful for us all. thank you . cara menggugurkan kandungan

Drag Racer V3 said...

I really like your post scorehero.net

Potty Racers 2 said...

articles that you share a very nice and inspires me stick-rpg2.com

Unknown said...

I like your post. It really useful with me. Thanks for sharing these useful information!
happywheels3game.com

alicetaylor said...

Thanks for sharing the information. It is very useful for my future. keep sharing

http://lennyfacetext.com

Unknown said...

I was very impressed by this post, this site has always been pleasant news. Thank you very much for such an interesting post. Keep working, great job! In my free time, I like play game: facebooklite.com.br. What about you?

Unknown said...

I realize that nothing is fair but I'm still trying. I just want to do my best and what is possible
povaup

Unknown said...

I like to get up early to go out and breathe fresh air. I feel that it is good for health and a good habit
19216811ll.com

Unknown said...

Play with millions of players around the world and try to become the longest of the day! Kizi game 2018 | Shellshock Live is the best entertainment site with free games.

Linda said...

You’ve written nice post, I am gonna bookmark this page, thanks for info. I actually appreciate your own position and I will be sure to come back here.
www.baixar-whatsapp.com.br

Unknown said...

It seems I'm on the right track, I hope I can do well. The result was something I did and was doing to implement it. www.clickjogosclick.com

ngocanhng said...

Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. Nice! thank you so much! Thank you for sharing.
b612az.com

Unknown said...

I have read your article, the information you give is very interesting.
pocatravel

alicetaylor said...

This article is really fantastic and thanks for sharing the valuable post.

supersmashflash2s.com

Bongol said...

By taking the time to read a lot of information like this to add my insight . cara menggugurkan hamil

Misty said...

I really enjoyed your blog Thanks for sharing such an informative post.
clipping path
clipping path service
background removal
car editing

Mike said...

You want to take some social security Benefits then you must find a Social Security Office Near Me. While looking for a Disability Benefits you must find a Disability Attorney Near Me.
While you must know about Social Security Office then you must open Social Security MY Account.
You must checkout Social Security Benefits and Social Security Disability

CB said...

By reading the article material very very well and this is very useful.
cara menggugurkan kandungan
penyebab sering keguguran
cara mengatasi telat haid
tanda tanda kehamilan 1 bulan
kalkulator masa subur akurat dan berhasil
masa subur wanita sebelum haid

selapak said...

Ada sebagian orang mempercayai bahan tradisional seperti kunyit asam , manjakani , jahe , asam jawa dan sebagainya untuk cara menggugurkan kandungan 100 berhasil dengan bahan alami
, apakah semua itu hanya sebuah mitos atau memang fakta ? Terlepas dari fakta atau mitos yang perlu anda ketahui tindakan cara menggugurkan hamil merupakan suatu tindakan yang penuh resiko tinggi dan berbahaya . Apalagi untuk cara menggugurkan kandungan 3 bulan yang mana usia kandungan sudah mulai kuat . Maka dari itulah , sebaiknya konsultasi saja ke dokter spesialis kandungan . siklus menstruasi yang terjadi pada tubuh wanita berulang setiap 28-30 hari sekali . Apakah wanita juga mengalami mimpi basah ? . Sebagai lelaki tidak boleh egois dalam melakukan hubungan intim , perempuan juga ingin mengalami klimak dalam melakukan hubungan intim . Lantas , bagaimana cara membuat wanita cepat keluar agar dapat membahagiakan pasangan .

Clipping Path Service said...

Wonderful Tutorial, thanks for putting this together! This is obviously one great post. Thanks for the valuable information.

Farhan.Jee said...

Other clipping path services include skin edit services which is a fast and affordable service, clipping path services