fluidBlog

September 11, 2007

Syntax Highlighting for the Web using Vim

Filed under: Blogging, Web Development — trekr @ 12:10 pm

Brian Reindel wrote a review of syntax highlighters for blog code samples. One of the comments on his post caught my attention. Dan wrote that he uses vim and vividchalk for his blog. I love it when I learn about an existing solution using familiar tools. I gave Dan’s method a try and was very pleased with the result. I know there are many WordPress Plugins for syntax highlighting but this is another tool that comes in handy when source is presented on the web as a separate page, for example, dbbackup.sh.

You will need to use a version of vim with GUI support, gvim, on Fedora, to ensure the colors are correct. You can install gvim on Fedora with the following command

$ sudu yum install gvim*

On Fedora, syntax scripts are in the directory /usr/share/vim/vim70/syntax/ and color schemes are in the directory /usr/share/vim/vim70/colors/. You can get other scripts from vim online.

Launch gvim from a terminal or the menu Applications->Programming->Vi Improved.

If you want embedded style in the HTML output then issue the colon command

~
:let html_use_css = 1

If you like the vividchalk color scheme, issue the command

~
:colorscheme vividchalk

To create an HTML version of the file, issue the command

~
:TOhtml

and save the HTML file by issuing the “ZZ” command, and quit the session to leave the original file unchanged with the command

~
:q!

The :TOhtml command produces a complete HTML page. To embed the highlighted syntax within a post, simply change the <body> tag to an appropriate CSS tag for your theme and delete the <html> and <head> sections. Here is a snippet as an example of embedding the highlighted source within a blog post. The HTML was created with the commands

~
:let html_use_css = 0
~
:TOhtml

Without CSS, the generated HTML needs to be enclosed in a tag that can enclose the <font> tag, for example, the <code> tag.


class Zipcode < ActiveRecord::Base
  belongs_to :postoffice
  has_many :locations

  def self.find_by_postoffice_name(postoffice_name)
    postoffice_id = Postoffice.find_by_name(postoffice_name).id
    find(:all, :conditions => [postoffice_id = ?, postoffice_id])
  end

  def self.find_by_postoffice_id(postoffice_id)
      find(:all, :conditions => [postoffice_id = ?, postoffice_id])
  end
end

As an added bonus, the output from vim using css validates to HTML 4.01 Strict.

See the vim documentation for a complete rundown on syntax highlighting in vim.

Hakota Design LLC