Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Using VIM as a syntax highlighting engine from Ruby (See related posts)

You can use VIM as a syntax highlighting engine for code fragments in your blogs etc. The below code snippet works sort of, but it is slow for me. Not sure at the moment whether it is VIM or something else. Perhapps others can try it out and suggest speed or other improvments.

       def  vimsyn(text, filetype)
           synfile = Tempfile.new('synfile')
           synfile.close
           codefile = Tempfile.new('codefile')
           codefile << text
           codefile.close

           # filetype="matlab"

           expr = %Q%/usr/local/bin/vim -f -n -X -e -s -c \
               "set filetype=#{filetpe}" \
               -c "syntax on" \
               -c "set background=dark" \
               -c "let html_use_css=1" \
               -c "run syntax/2html.vim" \
               -c "wq! #{synfile.path}" -c "q" \ 
               #{codefile.path}%

           `#{expr}`
           html = IO.readlines(synfile.path).join
           body = html.match(/<body.*<\/body>/m)[0]
           css  = html.match(/<style.*<\/style>/m)[0]
           css.gsub!(/pre/,'pre.code')
           css.gsub!(/^body.*$/,'')
           body.gsub!(/^<body/,'<div')
           body.gsub!(/<\/body>/,'<div>')                                        
           body.gsub!(/<pre>/,'<pre class=code>')

           return css+body
       end

Comments on this post

takayama posts on Oct 25, 2006 at 23:49
this snippet helps me a lot! thanks for your posting.

on my OSX 10.4.8, this script fails to execute tempfile like below:

irb(main):008:0> vimsyn(open('vimsyn.rb').readlines, 'ruby')
sh: line 2: /tmp/codefile.5090.1: Permission denied
=> "<style type=\"text/css\">\npre.code { color: #ffffff; background-color: #000000; }\n\n<!--\n-->\n</style><div>\n<pre class=code>\n\n</pre>\n<div>"


use "system()" instead of "`#{expr}`" works on my environment.

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts