Highlighting code in Kramdown or Maruku with Vim
I write posts in Markdown for this blog. Also I use Kramdown (I used Maruku before) for compiling pages into HTML. Maruku has builtin support for syntax highlighting in but unfortuantely it supports only Syntax. Syntax is a great lib with simple yet powerful implementation but it’s very underdeveloped. It has only Ruby, XML and YAML syntax modules by default. With a fair bit of googling it’s possible to find a few more modules but most of them are outdated and not complete. Kramdown doesn’t have any built in support for syntax highlighting at all. There are many other solutions including CodeRay and Ultraviolet gems. For some reason I’m not a fan of those. I’ve come up with a solution to suit my needs. I use gvim to highlight code. First of all, this solution clearly has some disadvantages:
- It needs gvim. Though, it’s possible to use vim with +gui capability with a little modification.
- It can be way slower then ruby implementations because of gvim startup times.
Though, I see some advantages that beat all the sad parts.
- Code looks in my blog exactly as it looks in my editor.
- Probably, I’ll never have a piece of code that can not be highlighted by gvim.
Basically this all done with two parts. First is a Kramdown/Maruku monkey patch to replace builtin syntax highlighting function. Unfortunately neither Maruku, nor Kramdown provides any API or something for this. The second part is a modified buf2html vim script that generates exactly what is needed for the Kramdown/Maruku part. Also highlighted code is cached so it won’t get highlighted on every compilation.
So here’s some examples of code highlighting and the code itself.
lib/vim_syntax_highlighter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230require 'digest'
require 'nokogiri'
require 'extlib'
require 'kramdown'
require 'maruku'
module VimHighlighter
def highlight_code(code, options = {})
options = {:lang => '', :css => true, :syntax => true,
:line_numbers => true, :first_line => 1,
:background => ''}.merge(options)
options[:lang] ||= ''
cache_key = Digest::SHA1.hexdigest(
[ options[:lang], options[:syntax], options[:css],
options[:line_numbers], options[:line_number],
options[:background] ].join('-')) +
'-' + Digest::SHA1.hexdigest(code)
cache_file = File.expand_path(
File.join('tmp', "#{cache_key}.codehl")
)
if File.exists? cache_file
f = File.open(cache_file)
code_html = f.read
f.close
code_html
else
if options[:syntax]
require 'tempfile'
synfile = Tempfile.new('synfile')
synfile.flush
codefile = Tempfile.new('codefile')
codefile << code
codefile.flush
cmd = "gvim -vfnN -i NONE --remote-tab-wait-silent " \
"'+set filetype=#{options[:lang]} | " \
"set nonu | syntax on | " \
"let b2h_use_css=#{options[:css] ? '1' : '0'} | " \
"colorscheme desert | " \
"source #{File.expand_path('lib/buf2html.vim')} | "\
"w! #{synfile.path} | bd! | " \
"bd!' '#{codefile.path}' > /dev/null 2>&1"
`#{cmd}`
unless $? == 0
raise StandardError.new(
"Vim syntax highlighter failed. Exit code: #{$?}"
)
end
synfile.rewind
code_html = synfile.read.strip
else
code_html = "<code>#{code}</code>"
end
doc = Nokogiri::HTML(code_html)
code_el = doc.css('body>*').first
code_el['class'] = options[:lang] unless options[:lang].blank?
pre_el = Nokogiri::XML::Element.new 'pre', doc
unless code_el['style'].blank?
pre_el['style'] = code_el['style']
code_el.remove_attribute 'style'
end
unless options[:css]
style = "position:relative;padding:0.5em"
if pre_el['style']
pre_el['style'] += ";#{style}"
else
pre_el['style'] = style
end
end
if options[:line_numbers]
ln_holder = Nokogiri::XML::Element.new 'span', doc
if options[:css]
ln_holder['class'] = 'LineNr'
pre_el['class'] = 'numbered'
else
ln_holder['style'] = "position:absolute;" +
"width:2em;text-align:right;"
code_el['style'] = 'position:relative;left:3em'
end
ln_holder << Nokogiri::XML::Text.new(
(
options[:first_line]...(options[:first_line] +
code_html.lines.count)
).to_a.join("\n"), doc
)
pre_el << ln_holder
end
pre_el << code_el
unless options[:background].blank?
pre_el['style'] = "background: #{options[:background]};"
end
File.open(cache_file, 'w') do |f|
f.write(pre_el.to_s)
end
pre_el.to_s
end
end
end
if defined? Kramdown
module Kramdown::Converter
class Html
include VimHighlighter
def get_option(el, key, default = nil)
val = if el.options[:attr].nil? || el.options[:attr][key].nil?
if @doc.options["syntax-#{key}".to_sym].nil?
default.to_s
else
@doc.options["syntax-#{key}".to_sym].to_s
end
else
el.options[:attr][key].to_s
end
if val.downcase == 'true' || val.downcase == 'no' ||
(val.to_i != 0 && (default == true || default == false))
return true
end
if val.downcase == 'false' || val.downcase == 'yes' ||
(val.to_i == 0 && (default == true || default == false))
return false
end
if val.to_i.to_s == val || val.is_a?(Numeric)
return val.to_i
end
val
end
def convert_codeblock(el, inner, indent)
lang = get_option el, 'lang', ''
use_syntax = get_option el, 'syntax', true
use_css = !!get_option(el, 'css', true)
line_numbers = get_option(el, 'line-numbers', true)
first_line = get_option(el, 'first-line', 1)
code_html = highlight_code(el.value, :lang => lang, :css => use_css,
:syntax => use_syntax,
:line_numbers => line_numbers,
:first_line => first_line)
"#{' ' * indent}#{code_html}\n"
end
end
end
end
if defined? Maruku
Maruku::Globals[:'syntax'] = true
Maruku::Globals[:'syntax-lang'] = ''
Maruku::Globals[:'syntax-css'] = true
Maruku::Globals[:'syntax-line-numbers'] = true
Maruku::Globals[:'syntax-first-line'] = 1
module MaRuKu
class MDElement
include VimHighlighter
def get_setting(sym, prefix = nil)
if self.attributes.has_key?(sym) then
self.attributes[sym]
elsif self.doc && self.doc.attributes.has_key?(sym) then
self.doc.attributes[sym]
elsif MaRuKu::Globals.has_key?(sym)
MaRuKu::Globals[sym]
elsif !prefix.nil? then
get_setting "#{prefix}-#{sym}".to_sym
else
$stderr.puts "Bug: no default for #{sym.inspect}"
nil
end
end
end
module Out::HTML
def to_html_code
lang = get_setting :lang, :syntax
use_syntax = get_setting(:syntax)
use_css = get_setting :css, :syntax
line_numbers = get_setting :'line-numbers', :syntax
first_line = get_setting :'first-line', :syntax
element =
begin
code_html = highlight_code(self.raw_code, :lang => lang, :css => use_css,
:syntax => use_syntax,
:line_numbers => line_numbers,
:first_line => first_line.to_i)
Document.new(code_html, {:respect_whitespace =>:all}).root
rescue Object => e
maruku_error "Error while using the vim syntax highlighter\n\n" +
"Code: -------------------------------------------------------------------\n" +
self.raw_code +
"\nCode HTML: --------------------------------------------------------------\n" +
(code_html || '') +
"\nLang: -------------------------------------------------------------------\n" +
lang +
"\nObject: ------------------------------------------------------------------\n" +
self.inspect +
"\nException: ---------------------------------------------------------------\n" +
"#{e.class}: #{e.message}" +
"\nBacktrace: ---------------------------------------------------------------\n" +
"\t#{e.backtrace.join("\n\t")}"
tell_user "Using normal PRE because the vim syntax highlighter did not work."
to_html_code_using_pre self.raw_code
end
add_ws element
end
end
end
end
lib/buf2html.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374" buf2html.vim - generate HTML/XHTML+CSS from a Vim buffer
" (using the current syntax highlighting colorscheme)
"
" This script is heavily modified to suit my needs. Namely, use vim as
" code highlighting tool for Maruku.
"
" Based on buf2html 2.0b2
"
" Original script can be found at:
" http://www.vim.org/scripts/script.php?script_id=2384
" ---------------------------------------------------------------------
" Usage: :[<various settings>] | source buf2html.vim
" Options:
" The following global ("g:") variables can be used to configure
" the script's output. 'b2h_use_css' should nearly always be
" defined, for example in .vimrc: let b2h_use_css = 1. Using
" plain HTML could be helpful if only a snippet of the output
" is needed for something.
"
" * b2h_use_css - use CSS instead of HTML tag attributes markup.
" * b2h_use_inlstyle - use CSS but only in style="..." attributes
" inside HTML element tags XXX CURRENTLY UNIMPLEMENTED.
"-----------------------------------------------------------------------
" various and sundry script-scoped variables
let s:sourcefilepathname = substitute(expand("%:p"),'\\','/','g')
" Save the file basename + extension (the 'tail'):
let s:srcfile_bnsuff = expand('%:t')
" Save the filetype:
let s:source_ft = &filetype
" Work out the encoding:
if &fileencoding != ""
let s:quoted_enc = "\"" . &fileencoding . "\""
let s:unquoted_e = &fileencoding
elseif &encoding != ""
let s:quoted_enc = "\"" . &encoding . "\""
let s:unquoted_e = &encoding
endif
" Work out what to name the new buffer when created:
if s:srcfile_bnsuff == ""
let s:synhl_HTMLfile = 'Untitled.html'
elseif s:srcfile_bnsuff[-5:-1] =~ '\.html'
let s:synhl_HTMLfile = substitute(s:srcfile_bnsuff
\ , '\c\.HTML$', '_HTML_', '') .'.html'
else
let s:synhl_HTMLfile = s:srcfile_bnsuff . '.html'
endif
" Work out what a suitable tmp directory might be:
let s:badfnchars = "\t\n'".' "*?[{`$\\%#|!<>'
let s:mytmpdir = ''
let s:dex = ( exists($TMP) ? '$TMP'
\ : exists($TEMP) ? '$TEMP'
\ : exists($TMPDIR) ? '$TMPDIR' : '')
if s:dex && isdirectory(s:dex)
let s:mytmpdir = escape(expand(s:dex), s:badfnchars)
else
let s:mytmpdir = '/tmp'
endi
" Options governing script operations.
let s:useCSS = 0
let s:inlstyle = 0
if exists('g:b2h_use_css') && g:b2h_use_css
let s:useCSS = 1
if exists('g:b2h_use_inlstyle') && g:b2h_use_inlstyle
let s:inlstyle = 1
endif
endif
" When not in gui we can only guess the colors.
if has("gui_running")
let s:whatterm = "gui"
else
let s:whatterm = "cterm"
if &t_Co == 8
let s:cterm_color0 = "#808080"
let s:cterm_color1 = "#ff6060"
let s:cterm_color2 = "#00ff00"
let s:cterm_color3 = "#ffff00"
let s:cterm_color4 = "#8080ff"
let s:cterm_color5 = "#ff40ff"
let s:cterm_color6 = "#00ffff"
let s:cterm_color7 = "#ffffff"
else
let s:cterm_color0 = "#000000"
let s:cterm_color1 = "#c00000"
let s:cterm_color2 = "#008000"
let s:cterm_color3 = "#804000"
let s:cterm_color4 = "#0000c0"
let s:cterm_color5 = "#c000c0"
let s:cterm_color6 = "#008080"
let s:cterm_color7 = "#c0c0c0"
let s:cterm_color8 = "#808080"
let s:cterm_color9 = "#ff6060"
let s:cterm_color10 = "#00ff00"
let s:cterm_color11 = "#ffff00"
let s:cterm_color12 = "#8080ff"
let s:cterm_color13 = "#ff40ff"
let s:cterm_color14 = "#00ffff"
let s:cterm_color15 = "#ffffff"
endif
endif
" Return good color specification: in GUI no transformation is done, in
" terminal return RGB values of known colors and empty string on unknown
if s:whatterm == "gui"
function! s:HtmlColor(color)
return a:color
endfun
else
function! s:HtmlColor(color)
if exists("s:cterm_color" . a:color)
execute "return s:cterm_color" . a:color
else
return ""
endif
endfun
endif
" Added 2008-08-26 ---------------------------------------
function! s:BrightAverage(hexspec)
let triplet = strpart(a:hexspec, 1)
let bfact = 1.10
let R = str2nr(triplet[0:1],16)
let G = str2nr(triplet[2:3],16)
let B = str2nr(triplet[4:5],16)
if R + G + B == 0|let s:abitbrighter = '#403040'|return 0|endif
if R == 0|let Rs = 2|endif
if G == 0|let Gs = 2|endif
if B == 0|let Bs = 2|endif
let rv = printf( '%d', ( R + G + B ) / 3 )
let factrRGB =
\ [ printf('%02x', bfact * (R || Rs))
\ , printf('%02x', bfact * (G || Gs))
\ , printf('%02x', bfact * (B || Bs)) ]
let s:abitbrighter = '#'.factrRGB[0].factrRGB[1].factrRGB[2]
return rv
endfu
" --------------------------------------------------------
if ! s:useCSS
" Return opening HTML tag for given highlight id
function! s:HtmlOpening(id)
let style = s:CSS1(a:id)
if (style != "")
return '<span style="' . style .'">'
else
return ''
end
endfun
" Return closing HTML tag for given highlight id
function s:HtmlClosing(id)
if (s:CSS1(a:id) != "")
return '</span>'
else
return ''
endif
endfun
endif
" Return CSS style describing given highlight id (can be empty)
function! s:CSS1(id)
let a = ""
if synIDattr(a:id, "inverse")
" For inverse, we always must set both colors (and exchange them)
let x = s:HtmlColor(synIDattr(a:id, "bg#", s:whatterm))
let a = a . "color:" . ( x != "" ? x : s:bgc ) . ";"
let x = s:HtmlColor(synIDattr(a:id, "fg#", s:whatterm))
let a = a . "background-color:" . ( x != "" ? x : s:fgc ) . ";"
else
let x = s:HtmlColor(synIDattr(a:id, "fg#", s:whatterm))
if x != "" | let a = a . "color:" . x . ";" | endif
let x = s:HtmlColor(synIDattr(a:id, "bg#", s:whatterm))
if x != "" | let a = a . "background-color:" . x . ";" | endif
endif
if synIDattr(a:id, "bold")
let a = a . "font-weight:bold;"
endif
if synIDattr(a:id, "italic")
let a = a . "font-style:italic;"
endif
if synIDattr(a:id, "underline")
let a = a . "text-decoration:underline;"
endif
return a
endfun
" Set some options to make it work faster.
" Expand tabs in original buffer to get 'tabstop' correctly used.
" Don't report changes for :substitute, there will be many of them.
let s:old_title = &title
let s:old_icon = &icon
let s:old_et = &l:et
let s:old_report = &report
set notitle noicon
setlocal et
set report=1000000
" >>>> NEW BUFFER / WINDOW CREATED HERE -- % NOW MEANS SOMETHING ELSE! <<<<
exec 'new '.s:mytmpdir .'/'. s:synhl_HTMLfile
set modifiable
%d
let s:old_paste = &paste
set paste
" Begin creating the new document.
"--------------------------------
" Now that we have our HEAD on straight... NOTE do NOT do a NEWLINE after
" <code> or will get a silly empty line at top of output HTML.
exe "normal a<code>\e"
" Jump back to previous buffer.
exe "normal \<C-W>p"
" List of all id's
let s:idlist = ","
" Find the background and foreground colors.
let s:fgc = s:HtmlColor(synIDattr(highlightID("Normal"), "fg#", s:whatterm))
let s:bgc = s:HtmlColor(synIDattr(highlightID("Normal"), "bg#", s:whatterm))
if s:fgc == ""
let s:fgc = ( &background == "dark" ? "#ffffff" : "#000000" )
endif
if s:bgc == ""
let s:bgc = ( &background == "dark" ? "#000000" : "#ffffff" )
endif
" Have a way to represent a (invisible) TAB char for makefiles:
let s:TAB_Repr = '<span class="tabchar">|-TAB-\>|</span>'
" Loop over all lines in the original text
let s:end = line("$")
let s:lnum = 1
while s:lnum <= s:end
" Get the current line, with tabs expanded to spaces when needed
" FIXME: What if it changes syntax highlighting?
let s:line = getline(s:lnum)
if stridx(s:line, "\t") >= 0
if s:source_ft != 'make'
exe s:lnum . "retab!"
let s:did_retab = 1
let s:line = getline(s:lnum)
endif
else
let s:did_retab = 0
endif
let s:len = strlen(s:line)
let s:new = ""
" Loop over each character in the line
let s:col = 1
while s:col <= s:len
let s:startcol = s:col " The start column for processing text
let s:id = synID(s:lnum, s:col, 1)
let s:col = s:col + 1
" Speed loop (it's small - that's the trick)
" Go along till we find a change in synID
while s:col <= s:len && s:id == synID(s:lnum, s:col, 1)
let s:col = s:col + 1
endwhi
let s:backedup = s:col
if ' ' == matchstr(getline(s:lnum), '.\{' . -1 + s:backedup . '}\zs.')
while ' ' == matchstr(getline(s:lnum), '.\{' . s:backedup . '}\zs.')
let s:backedup -= 1
endwhile
endif
let nonblank = ( s:backedup < s:col ? s:backedup : s:col )
" Output the text with the same synID, with class set to c{s:id}
let s:id = synIDtrans(s:id)
let s:new = s:new . '<span class="c' . s:id . '">' .
\ substitute(substitute(substitute(substitute(
\ substitute(substitute(strpart(s:line, s:startcol - 1,
\ nonblank - s:startcol), '&', '\&', 'g'), '<',
\ '\<', 'g'), '>', '\>', 'g'), '"',
\ '\"', 'g'), "\x0c", '<hr class="page-break">',
\ 'g'), "\x09", s:TAB_Repr, 'g')
\ . '</span>'
while s:backedup < s:col
let s:new = s:new . ' '
let s:backedup += 1
endwhi
" Add the class to class list if it's not there yet
if stridx(s:idlist, "," . s:id . ",") == -1
let s:idlist = s:idlist . s:id . ","
endif
if s:col > s:len | break | endif
endwhile
if s:did_retab | undo | endif
exe "normal \<C-W>pa" . strtrans(s:new) . "\n\e\<C-W>p"
let s:lnum = s:lnum + 1
+
endwhile
" Finish with the last lines.
exe "normal \<C-W>p\<Up>\<End>a</code>\e"
" Normal/global attributes:
if ! s:useCSS
exec '%s/<code\([^>]*\)>/<code\1 style="background-color:' .
\ s:bgc . ';color:' . s:fgc . '">/'
endif
" Gather attributes for all other classes
let s:idlist = strpart(s:idlist, 1)
while s:idlist != ""
let s:attr = ""
let s:col = stridx(s:idlist, ",")
let s:id = strpart(s:idlist, 0, s:col)
let s:id2name = synIDattr(s:id, "name", 'gui')
let s:idlist = strpart(s:idlist, s:col + 1)
let s:attr = s:CSS1(s:id)
if strlen(s:attr) != 0
if s:useCSS && ! s:inlstyle
exec '%s+<span class="c' . s:id . '">+<span class="' .
\ s:id2name . '">+g'
else
let s:Tag_attr_id_to = s:HtmlOpening(s:id)
let s:Tag_attr_id_tc = s:HtmlClosing(s:id)
exec '%s+<span class="c'. s:id .'">\([^<]*\)</span>+'.
\ s:Tag_attr_id_to .'\1'. s:Tag_attr_id_tc .'+g'
let s:Tag_attr_id_to = ''
let s:Tag_attr_id_tc = ''
endif
else
" clean attribute-less syn id segments
exec '%s+<span class="c' . s:id . '">\([^<]*\)</span>+\1+g'
endif
endwhile
" Cleanup (we've already lost last user's pattern match highlighting)
%s:\s\+$::e
if has("extra_search") | nohlsearch | endif
" Restore old settings
let &report = s:old_report
let &title = s:old_title
let &icon = s:old_icon
let &paste = s:old_paste
exe "normal \<C-W>p"
let &l:et = s:old_et
exe "normal \<C-W>p"
" Save a little bit of memory (Is this worth doing?)
unlet s:old_et s:old_paste s:old_icon s:old_report s:old_title
unlet s:whatterm s:idlist s:lnum s:end s:fgc s:bgc
unlet! s:col s:id s:attr s:len s:line s:new s:did_retab
delfunc s:HtmlColor
delfunc s:CSS1
if ! s:useCSS
delfunc s:HtmlOpening
delfunc s:HtmlClosing
endif
unlet s:useCSS