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

  1. Install python-livereload

  2. Add the scripts in the neovim directory 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
    }
    
  3. Load livereload.js from 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/1000 with the output of stdpath('run').

  4. 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

  1. Install a live reload server (I used python-livereload), and start it:

    livereload -t index.html
    

    Note: 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

  2. Download livereload.js from the livereload-js repository, and put it in the same directory as the file you’re editing.

  3. Set up your editor to automatically make the HTML file when you save the Markdown file.

  4. Ensure livereload.js is 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.

  1. Include the LiveJS script in your HTML.

    <script async src="https://livejs.com/live.js"></script>
    
  2. Start a local HTTP server.

    $ cd /path/to/file.md
    $ python3 -m http.server --cgi --bind 127.0.0.1
    
  3. Open http://localhost:8000/file.html in your browser

  4. Remember to remove it in production. It looks like LiveJS checks whether the file has changed every second, which may cause some unnecessary overhead.