DEV Community

Max S-T
Max S-T

Posted on

1

Auto-Compiling markdown for a live preview

Now, I really like markdown, but there can be some annoyances when it comes to viewing you'r finished product. In a lot of cases it is nice to see you'r result as you type, so we want:

  • Auto compilation on save
  • Refresh our PDF reader

How I thought this would work

Initialy I thought I’d be using the amazing tool entr. entr is great because it monitors a files changes on disk. So the plan was compile with pandoc (as standard for markdown) through a shortcut in [n]vim, be watching for the file change with entr and then send a -HUP signal to my pdf reader (mupdf in this case) with pkill.

How it actually worked

Both fortunately and unfortunately there is no need for entr in this scenario. After a bit of scrolling through :help in nvim I had gathered this info:

  • Bash commands could be ran through the use of !
  • autocmd runs ‘automatically when reading or writing a file’ (from :h autocmd)
  • BufWritePost executes something 'After writing the whole buffer to a file’ (again from :h autocmd)
  • % are the name of the file
  • Using *.md after BufWritePost specifies file type From this we can start to piece together what we need to put in out .vimrc (or init.vim in my case) This is what I came up with:
autocmd BufWritePost *.md !pandoc % -o %:r.pdf --pdf-engine=wkhtmltopdf && pkill -HUP mupdf

Lets decompose that line:

  • autocmd BufWritePost - Run after ! once the entire buffer has been writen to a file
  • *.md - Only do this for markdown files
  • !pandoc % -o %:r.pdf --pdf-engine=wkhtmltopdf - Use pandoc to compile the current file (%) to current filename without extention (%:r.pdf) using the wkhtmltopdf PDF engine
  • pkill -HUP mupdf - Send mupdf a HUP signal (source)

Well that was easy

Yes and no, it took me a while to actually come up with that but its actually a very simple and elegant solution. If it isn't working for you make sure you have wkhtmltopdf (or whatever PDF engine you use) and mupdf installed. Also make sure you’ve put it in the correct file (.vimrc for vim, init.vim for nvim) and reopened any [n]vim instance to make the changes

Thank you all for reading and happy writing,
~ M

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →