Preview Markdown files locally
Render some Markdown file to HTML and show it in your browser.
This is useful when you want to check a Markdown file before pushing it onto GitHub/GitLab/etc or if you want to simply print a nice looking Markdown file. Just print it from your browser.
The look is broadly similar to that on GitHub but stripped down to the bare minimum. It can also be changed easily. Just have a look at the source, Luke. It's really quite simple.
This script does use CommonMarker to render the Markdown files to HTML. Install it with:
$ [sudo] gem install commonmarker
According to github.com/github/markup, this is the very same component GitHub is using.
viewmd.rb, save it somewhere within your
PATH and make it
$ mv Downloads/viewmd.rb /usr/local/bin/viewmd $ chmod a+x /usr/local/bin/viewmd
When there's a
README.md in the current folder:
If you want to view another file:
$ viewmd path/to/another/file.md
Your default web browser should open immediately and display the rendered Markdown.
Because this script mimicks a web server, it won't terminate instantly but continue to serve a new render of the Markdown file each time you refresh the page in your browser.
To stop the script, just hit CTRL+C.
You may want to put the script in the background while you edit the Markdown file in your favorite editor:
$ viewmd & $ vim README.md
Now make some changes and reload the page in your browser.
Motivation & Alternatives
There are a couple of tools out there than can do the same. Somehow, they just didn't quite cut the mustard for me.
I wanted a simple tool I can use to pretty print a Markdown file. Or generate a PDF. Your browser most certainly can do so.
At the time of writing, grip renders
the Markdown file on a GitHub server. This service has a quota that quickly
dries up. Also,
grip has this annoying bar above the document you just
can't get rid of.
Alternatively one can use
browser (on macOS, both available
brew) like this:
$ pandoc -f markdown_github < README.md | browser
But this won't update when you reload the page.
Another handy option for macOS is QLMarkdown that shows a preview of a Markdown file by simply pressing space if it's selected in Finder.
Also, there are plug-ins for Emacs and Vim that can do the same and more.
Webserver seems overkill, especially since you still need to refresh the browser (could be more interesting with hot reload). And you really don't need to use Ruby here: CommonMark's official C implementation is called
cmarkin every distribution, including brew, so that you could hack a way smaller inotify-based shell script for the heavy lifting.
Of course, every Emacs user does this inside Emacs (https://www.youtube.com/watch?v=Pd0JwOqh-gI), but Vim users obviously can do that too: https://nickjanetakis.com/blog/writing-and-previewing-markdown-in-real-time-with-vim-8.