Exporting VIM Syntax Highlight
by Jean-Michel Lacroix on
I've been looking for a tool to replace the GitHub Gists I'm using to highlight code on these pages. Gists are great, but I wanted something that doesn't rely on JavaScript (for SEO, accessibility and performance reasons).
While taking a look at 3rd party libs, I flashed: why not use the output of my favorite editor, VIM? It has powerful syntax highlighting and a lot of syntax files. I can even use color schemes and some of VIM's settings, such as line numbering, to make my life easier (and it reads my vimrc
!).
So instead of using simple tools, I went for the complicated solution. I made two script to help extracting HTML-formatted syntax and its associated CSS styles. Note that these scripts outputs their results on stdout
, so they won't alter your files.
Converting to HTML
highlight.sh
outputs HTML-formatted syntax highlight of a file:
#/bin/bash OUTFILE=$(mktemp -t highlight) INFILE=$1 PARAM="set nonumber" if [ -z "$INFILE" ] then echo "usage: $0 source.file" exit fi vim +"$PARAM" \ +'let html_use_css=1' \ +'TOhtml' \ +'/<pre>/,/<\/pre>/d a' \ +'g/./d' \ +'1pu! a' \ +'$d' \ +"wq! $OUTFILE" \ +'q!' $INFILE &>/dev/null cat $OUTFILE && rm $OUTFILE
Try the script on itself:
$ bash highlight.sh highlight.sh
Extracting CSS
syntax.sh
loads VIM's syntax test and outputs its generated CSS styles:
#!/bin/bash OUTFILE=$(mktemp -t syntax) vim +'so $VIMRUNTIME/syntax/hitest.vim' \ +'let html_use_css=1' \ +'TOhtml' \ +'v/^\./d' \ +"wq! $OUTFILE" \ +'q!' &>/dev/null cat $OUTFILE && rm $OUTFILE
Extract current vim colors as CSS:
$ bash syntax.sh
Further Integration
Currently, it's not the best way to integrate code into my posts. It's not automated and I need to manually insert the HTML. I've made an awk
script to help with this task. I'll post about it when it's integrated into my process.