Last Updated: February 25, 2016
· crusoexia

Preview markdown from Vim



Let's Build it up!

1. Python markdown

Type below command in your terminal to install it

easy_install markdown

2. Markdown.css

We need a stylesheet to beauty our compiled doc, you can find a lot on the internet, or simply download this one for a basic look.
Save it with the name markdown.css at a certain path (Or if you don't want to download it, you can link it from the compiled html later, but you need the internet access when you want to preview the doc).

3. Bash script

Save below bash script into your /usr/bin with name md-prev.sh, pay attention to the variable values.



# Replace markdown.css with the url if you prefer not to save it on local

if [ -d $tmpPath ]; then
    rm $tmpPath/*
    mkdir -p $tmpPath

# Skip this line if you prefer not to save the markdown.css to local
cp "path/to/your/$cssFileName" $tmpPath

echo "<!DOCTYPE html>" > $previewHtml
echo "<html>" >> $previewHtml
echo "<head>" >> $previewHtml
echo "<meta http-equiv='content-type' content='text/html; charset=UTF-8' />" >> $previewHtml
echo "<link href='$css' rel='stylesheet'></link>" >> $previewHtml
echo "</head>" >> $previewHtml
echo "<body>" >> $previewHtml
python -m markdown "$1" -x tables >> $previewHtml
echo "</body></html>" >> $previewHtml

type -P xdg-open &> /dev/null && xdg-open $previewHtml || open $previewHtml

Now you can preview your markdown doc from terminal by type md-prev.sh your-markdown-file.

4. Map a key in Vim

Save below script in your .vimrc

noremap <silent> <F5> :!md-prev.sh "%:p"<CR>

Now, open your vim and write your favourite markdown doc, press F5 to preview it.