Firmware Engineer, Minimalist, Improving Runner

Add Syntax Highlighting To Your Blog With VIM

One of the challenges Chisel presents is the lack of syntax highlighting for code snippets. Luckily, this can be solved with -- surprise, surprise -- VIM!

VIM includes a plugin called TOhtml. Calling this will convert the current file into HTML, complete with coloring if syntax highlighting is enabled. This works on hightlighted text too. To execute, enter normal mode and type:


The HTML output is created in a split VIM window. Here is a sample python script pasted into this post:

import sys

if len(sys.argv) != 2:
hex_num = str('0');
hex_num = str(sys.argv1)

bin_num = bin(int(hex_num, 16))[2:]

print bin_num

counter = 0
for i in bin_num[::-1]:
if i == str(1):
print "Bit " + str(counter)

counter += 1

Here is the same code after ran through TOhtml with syntax highlighting:

import sys

if len(sys.argv) != 2:
   hex_num = str('0');
   hex_num = str(sys.argv[1])

bin_num = bin(int(hex_num, 16))[2:]

print bin_num

counter = 0
for i in bin_num[::-1]:
   if i == str(1):
      print "Bit " + str(counter)

   counter += 1

Note TOhtml creates a HTML file with all tags, which may be overkill for sharing code snippets. My usage simply involves copying the meat between the <body> tags and adding the code in my posts.

The HTML may not be optimal, but it works and provides a quick solution to adding colorized code snippets on your blog.

* Update: Follow the discussion at Hacker News