Vim: Markdown Preview

Writing blog posts in markdown is fun! However, it would be more convenient if I could preview the markdown file as I write it in my text editor, vim. There are two ways of approaching this: 1) Preview markdown in vim environment itself. OR 2) Preview markdown in the browser as HTML. In this post, we are going to look at both the ways of previewing. So, let’s get started..

Vim preview

In order to preview the file in vim we will be using the binary mdv, a Python based Markdown previewer. To install this, follow the instructions in the README.md here.

NOTE: Don’t forget to “star” the repository, if you use it/like it


Once installed, this command allows us to preview a markdown file in the terminal itself:

  • File:
# TEST

This is a test file

- Test
  • Preview:
$ mdv test.md

 TEST
  This is a test file
    - Test

Now, we can integrate it with vim. One thing I like to do is always use splits for previews and other results related to a file. So, we can add this function to our vimrc file that opens the output of mdv <current_file> in a new split:

function! TerminalPreviewMarkdown()
	new % | terminal ! mdv %
endfu

map <silent> <leader>m :call TerminalPreviewMarkdown()<CR>

You can see that I have mapped the function to a key ( + `m`). This makes it even easier to preview a markdown file currently opened in `vim`

Test Xref

Vim Markdown Preview


Browser Preview

In order to preview markdown files in browser, we will first convert it to an html file, and then open it in the browser. To do that, we will use the ruby gem github-markdown

Once installed, we can use the command:

$ github-markdown test.md > test.html

This will convert test.md to test.html which is displayable in the browser.

Now, to tie all this to a vim key we can create a function and bind it to another key:

function! BrowserPreviewMarkdown()
  let l:tmpfile = ".some_git_ignored_temp_file_markdown_preview" . ".html"
  execute "!" . "rm " . l:tmpfile
  echo l:tmpfile
  execute "!" . "github-markdown % > " . l:tmpfile
  execute "!" . "xdg-open " . l:tmpfile
endfu

map <silent> <leader>p :call BrowserPreviewMarkdown()<CR>

NOTE: xdg-open works on linux, for mac replace it with just open

This binds the function BrowserPreviewMarkdown to the key, + `p`.

Now, hitting + `p` will open the markdown preview in the default browser.

Test Xref

Browser Markdown Preview