Markdown Preview in Vim
January 12, 2009
The great thing about Shinmun (the lightweight blog engine this blog is running on), is that it allows you to work on the blogposts directly in your favourite text editor, and get them online simply by doing a git push. The posts are simple markdown files, and since I never feel confident that everything will look right if I just push these straight to the blog without previewing, and don’t want to fire up a local webserver just to get a look, I went looking for a way to preview markdown files in Vim. This is what I came up with.
Syntax highlighting for Vim
First I followed these instructions for getting syntax highlighting for Markdown in Vim. The next step was to get Vim to open a simple markdown preview in the browser.
Previewing in the browser
I haven’t really been writing anything in Vim’s own scripting language, and from what I’ve seen of it, it’s ugly enough to make PHP look attractive in comparison. Fortunalety my version of Vim is compiled with ruby support, so I took a look at the API and whipped up this little snippet, which I placed in .Vim/ftplugin/mkd.vim:
- function! PreviewMKD()
- ruby << EOF
- require 'rubygems'
- require 'bluecloth'
- t = ""
- VIM::Buffer.current.count.times {|i| t += "#{VIM::Buffer.current[i + 1]}\n"}
- html_file = VIM::Buffer.current.name.gsub(/.(md|mkd)$/, '.html')
- if html_file == VIM::Buffer.current.name
- print "Error! - This file extension is not supported for Markdown previews"
- end
- File.open(html_file, 'w') do |f|
- f.write(BlueCloth.new(t).to_html)
- end
- system("open #{html_file}")
- EOF
- endfunction
- map <Leader>p :call PreviewMKD()<CR>
This does the trick for me, and let me open a preview in my default browser by pressing ,p. It uses the ‘open’ command from OS X though, so that will need modification for it to work beyond the world of Mac, and it requires the BlueCloth rubygem to be installed.
Posted by Mathias Biilmann. Category: Vim. Tags: vim, ruby, markdown, shinmun.
Similar Posts
- A DRY and RESTful Blog
- Ruby on Rails and the X in front of HTML
- Rdoc Widget
- Why Ruby is more than fast enough
- Sudoku on Rails
- Ruby, Haskell and Euler
- Brand New Biilmann Blog
Posting Comment...
Holger Rapp said 7 months ago:
I dig this. I used it verbatim and it does the job very well. I though I might also share my work with you, because I think i corresponds well: http://www.vim.org/scripts/script.php?script_id=2715
I can do link<tab>Go to google<c-j>www.google.com and get Go to google
Maybe you can use this too.