Sunday, March 13, 2016

bash functions to view markdown documents

If you're writing markdown documents from vim or emacs, here's a couple handy ways to view them as rendered HTML.

Converting to html

An easy program to convert your markdown to html is pandoc. It can be installed on debian/ubuntu systems this way:

sudo apt-get install pandoc

pandoc can be run on your markdown files and will output html to stdout (or a file if you specify the -o option):

pandoc mydoc.md  # prints html to stdout
pandoc -o output.html mydoc.md  # saves html to output.html

So now you can just save your html to a file and open with your browser right? Wrong. It gets much easier..

Using lynx

If you don't already have it, lynx is a command line web browser. You can install it with the following:

sudo apt-get install lynx

lynx can read from stdin when you specify the -stdin flag. So now you can pipe the output from pandoc to it to render your md file:

pandoc mydoc.md | lynx -stdin  # opens mydoc.md in lynx as html

Using your browser

lynx doesn't look quite as appealing as chrome or firefox. In fact it's not too much better than looking at the md file itself. Unfortunately, it's pretty difficult to pipe html into chrome or ff. But that's where bcat comes in. It takes html on stdin and opens it in your default browser! Here's how to install it:

sudo apt-get install ruby-bcat

Now you can just pipe pandoc straight into your browser and have a one-line, no temp-file solution!

pandoc mydoc.md | bcat  # opens mydoc.md in a new browser tab!

Putting it all together

So that's still too much typing, so here's a couple bash functions to make it really easy. Just put one or both in your ~/.bashrc file:

# view markdown file as html in lynx
mdl() {
    if ! which lynx >/dev/null || ! which pandoc >/dev/null; then
        >&2 echo -e "lynx or pandoc not found!\n"
    elif [ "$#" -ne 1 ]; then
        >&2 echo "please specify one markdown file to render"
    else
        pandoc "$1" | lynx -stdin
    fi
}

# view markdown file as html in browser
mdb() {
    if ! which bcat >/dev/null || ! which pandoc >/dev/null; then
        >&2 echo -e "bcat or pandoc not found!\n"
    elif [ "$#" -ne 1 ]; then
        >&2 echo "please specify one markdown file to render"
    else
        pandoc "$1" | bcat
    fi
}

Now you can just do this to see your markdown files rendered as html:

mdl mydoc.md  # view md file in lynx
mdb mydoc.md  # view md file in browser

Further reading:

http://unix.stackexchange.com/a/120519
http://superuser.com/a/844249

No comments :