Skip to content

Instantly share code, notes, and snippets.

@mshafae
Created April 7, 2021 20:31
Show Gist options
  • Save mshafae/9c68ad8ad7e96178b1db8bb149cf5037 to your computer and use it in GitHub Desktop.
Save mshafae/9c68ad8ad7e96178b1db8bb149cf5037 to your computer and use it in GitHub Desktop.
Preview Markdown files via GitHub's Markdown Renderer.
#!/bin/bash
#
# Copyright 2021 Michael Shafae
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
mdsee () {
# BASH shell function that will use perl, realpath, jq, and curl
# to generate a preview of a Markdown file using GitHub's
# renderer.
# Inspired by the discussion at
# https://stackoverflow.com/a/54013496
#HTMLFILE="$(mktemp -u).html"
UNAME=`uname`
if [ ${UNAME}"x" = "Darwinx" ]; then
# If it's a mac, open the file in Safari.
# Change it to whatever browser you prefer.
OPEN="open -a Safari.app"
else
# If it's not a mac, then it's Gnome for me
# Otherwie, change it to whatever else you want.
OPEN="gio open"
fi
RP=`realpath $1`
BASE=`dirname $RP`
MARKDOWN="/tmp/mdsee-in.md"
perl -splwe 's/(\!\[.+\]\()([a-zA-Z0-9_\-\.\/]+)(\))/$1$basedir\/$2)/' -- -basedir=$BASE $1 > $MARKDOWN
HTMLFILE="/tmp/mdsee-out.html"
cat "$MARKDOWN" | \
jq --slurp --raw-input '{"text": "\(.)", "mode": "markdown"}' | \
curl -s --data @- https://api.github.com/markdown > "$HTMLFILE"
${OPEN} "$HTMLFILE"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment