Live Previews of Markdown Files
A live preview is when the browser window automatically reloads the rendered HTML every time you change the source markdown file.
Simple setup with Neovim
-
Install python-livereload
-
Add the scripts in the
neovimdirectory to your runtime path. If you use lazy.nvim you can do this by adding this to your setup:{ url='https://codeberg.org/gi1242/md-to-html.git', config = function( plugin ) vim.opt.rtp:append( plugin.dir .. "/neovim" ) end } -
Load
livereload.jsfrom the HTML. You can do this from the YAML header by:--- end_head: <script async src="/run/user/1000/livereload.js?host=127.0.0.1&port=35729"></script> ---Replace
/run/user/1000with the output ofstdpath('run'). -
Run the Vim command
StartLiveReload.
Every time you save the source markdown file, the HTML will be built and the browser window will be reloaded. Either enable autosave or manually press Ctrl S to save. The live reload server is stopped when you close the buffer. Remove the livereload header before uploading, you can automate this by using the method described here
You can also use compiler md-to-html to set makeprg, and use AutoHtml to automatically :make every time the buffer is saved.
Manual Setup using LiveReload
-
Install a live reload server (I used python-livereload), and start it:
livereload -t index.htmlNote: There seem to be some issues with symlinks and watching directories. The script seems to work better with when symlinks in the current directory aren’t resolved, and you watch one HTML file. I couldn’t get it to watch the whole directory
-
Download livereload.js from the livereload-js repository, and put it in the same directory as the file you’re editing.
-
Set up your editor to automatically make the HTML file when you save the Markdown file.
-
Ensure
livereload.jsis loaded from your output HTML<script async src="/path/to/livereload.js?host=127.0.0.1&port=35729"></script>
If things worked the browser should automatically refresh every time you make change.
Setup using LiveJS
I found this less reliable.
-
Include the LiveJS script in your HTML.
<script async src="https://livejs.com/live.js"></script> -
Start a local HTTP server.
$ cd /path/to/file.md $ python3 -m http.server --cgi --bind 127.0.0.1 -
Open
http://localhost:8000/file.htmlin your browser -
Remember to remove it in production. It looks like
LiveJSchecks whether the file has changed every second, which may cause some unnecessary overhead.