There are a lot of Vim plugins that allow you to preview markdown files:

But to name a few.

I was looking for something simple; but most of these plugins had options and setting, commands and auto commands that was just too bloated for my needs.

Most of these tools use a separate tool to render the markdown to the browser; grip is a cli application that renders markdown via the GitHub API, and is simple to install:

$ brew install grip

I would prefer to render offline, but grip does what I need for now.

No plugin required

With grip installed I can simple run it with:

:! grip %

or in a Vim terminal:

:term grip %

Homemade plugin

The above commands are great, but I wanted something more integrated into Vim. Using this Reddit post as inspiration, I adapted the code to work in Vim8:

" .vim/plugin/local.vim
command! MarkdownPreview call local#mdpreview#start()
command! MarkdownStopPreview call local#mdpreview#stop()
" .vim/autoload/local/mdpreview.vim
func! local#mdpreview#start() abort
    call local#mdpreview#stop()
    let s:mdpreview_job_id = job_start(
        \ "/bin/zsh -c \"grip -b ". shellescape(expand('%:p')) . " 0 2>&1 | awk '/Running/ { print \\$4 }'\"",
        \ { 'out_cb': 'OnGripStart', 'pty': 1 })
    func! OnGripStart(_, output)
        echo "grip " . a:output
    endfunc
endfunc

func! local#mdpreview#stop() abort
    if exists('s:mdpreview_job_id')
        call job_stop(s:mdpreview_job_id)
        unlet s:mdpreview_job_id
    endif
endfunc

I also wanted the grip server to stop when I changed vim buffers so I also added this autocmd:

" .vim/plugin/local.vim
au BufLeave * call local#mdpreview#stop()

Simple homemade plugin for markdown preview; all I do now is call :MarkdownPreview and grip will preview my markdown file in my default browser.

comments powered by Disqus