Templates make it possible for users previewing posts in custom formats in UltraBlog.vim. However, there is more you can do with our highly customizable templates. This article discusses how to highlight code snippets in posts by the use of some third-party open-source tools.

Before setting out to work, let me introduce the tools we are about to use:

  • highlight.js: A javascript library which highlights code blocks in web pages automatically.
  • jquery: The famous RIA development javascript library.

Download the upper two libraries and put them under any folder accessible to your webbrowser, in my case, it is /home/lenin/.vim/bundle/ultrablog/vendor/.

Then open UltraBlog.vim and edit the template you are using, put the following lines in the <head>...</head> area:

<link rel="stylesheet" href="/home/lenin/.vim/bundle/ultrablog/vendor/highlight/styles/default.css">
<script src="/home/lenin/.vim/bundle/ultrablog/vendor/highlight/highlight.pack.js"></script>
<script src="/home/lenin/.vim/bundle/ultrablog/vendor/jquery.js"></script>
$('pre').each(function(i, e){
if(typeof e.lang != 'undefined')
e.className = e.lang;
hljs.highlightBlock(e, ' ');

If you are using the default template UltraBlog.vim supplies, change .title to .postTitle in the pre-defined <style>...</style> area, and change the class name of the div element in the <body>...</body> area from title to postTitle, that is because this class name is also used by highlight.js.

An important point, the jquery selector I used in the code snippet above selects every <pre>...</pre> element and copies the value of its attribute lang to class. This is specified for the wordpress plugin wp-syntax I use. If you use another syntax highlighting tool which uses different markup for code blocks, you should modify the code above to make highlight.js find code blocks correctly.

Posted via UltraBlog.vim.