I've mentioned in the past that I've experimented with a number of different options for styling and syntax highlighting code snippets on this weblog, with varying degrees of success.

For a few months I've been using CSS-based syntax highlighting based on the code generated by Vim's :TOhtml command, and it's been working out pretty well. It means that my RSS feed doesn't have any color, but at least the code itself is correctly formatted.

The part I didn't enjoy too much about :TOhtml, however, was that it would only generate the minimum number of style rules it need to highlight the piece of code it was generating the HTML for. This works fine in many scenarios, but it was annoying for me because it meant I needed to continually update my site code.css file as new rules were generated for new snippets that I didn't have in there before.

So what I really wanted was a way to convert the Vim colorscheme of my choice into a CSS useful for my site. Naturally, I turned to PowerShell and came up with convert-vim2css.ps1:

param( [string] $vimfile )

# some instructions we don't care for
$ignorable = ( 'link', 'clear' )

$nrx = 'hi (?\w+)'
$fgrx = 'guifg=(?#\w+)'
$bgrx = 'guibg=(?#\w+)'
$frx = 'gui=(?\S+)'

(gc $vimfile) | ?{
   ($_ -match $nrx) -and ($ignorable -notcontains $matches.n)
} | %{
   if ( $matches.n -eq 'Normal' ) {
      write '.codebg {'
      write '   border-left: solid 1em #303030;'
      write '   font-size: 1.1em;'
      write '   padding: 0.8em 0.5em;'
   } else {
      write ".$($matches.n) {"
   }
   if ( $_ -match $fgrx ) {
      write "   color: $($matches.n);"
   }
   if ( $_ -match $bgrx ) {
      write "   background: $($matches.n);"
   }
   # element could any combination of these
   if ( $_ -match $frx ) {
      switch ( $matches.n.split(',') ) {
         "italic" { write "   font-style: $_;" }
         "bold" { write "   font-weight: $_;" }
         "underline" { write "   text-decoration: $_;" }
      }
   }
   write '}'
}

# other boilerplate code
write 'code {'
write '   font-family: Consolas, "DejaVu Sans Mono", "Lucida Console", monospace; '
write '}'

It's not very fancy and it only supports GVim schemes, but that's enough for me and does the trick for now.

Technorati tags: ,


Tomas Restrepo

Software developer located in Colombia.