Code Syntax Highlighting

| No Comments | No TrackBacks
I found an easy way of adding code samples with syntax highlighting to my blog entries, based on a "conversion to html" procedure in Vim. This method is valid for all the languages supported by Vim.

Select the code in the editor and type :TOhtml. This command opens a new buffer containing your code converted to html (including the colors). Now you only have to copy the html code and paste it to your entry.
As an example, here's my solution to Project Euler's #2:

#!/usr/bin/perl -w
use strict;
use feature 'say';
use Memoize;


my $n = 1;
my $fib = fib($n);
my $sum = 0;

while ($fib < 1_000_000) {
    if ($fib % 2 == 0) {
        say $fib;
        $sum += $fib;
    $fib = fib($n);

say "Result: $sum";

sub fib {
    my $n = shift;
    return 1 if $n < 2;
    fib ($n-1) + fib($n-2);

As you can see, the code coloring functionality of a default setup of MacVim doesn't recognize the new Perl 5.10 features (like the say function), but the result is quite readable.

NOTE: For an MT4 blog, the entry format should be None (pure HTML).

There is a similar solution for Emacs/XEmacs users. You can find the details here: htmlize.

No TrackBacks

TrackBack URL:

Leave a comment

About this Entry

This page contains a single entry by Enrique Nell published on January 4, 2009 1:29 AM.

Movable Type was the previous entry in this blog.

UTF-16 Processing Issue in Perl is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.


Powered by Movable Type 4.23-en