utilies

A handful of (useful) scripts for unix-like systems
Log | Files | Refs | README | LICENSE

mdview (1715B)


      1 #!/bin/sh
      2 
      3 # DEPENDENCIES
      4 #  * pandoc
      5 #  * zathura
      6 
      7 # CONFIGURATION
      8 out_type="pdf"
      9 
     10 usage() {
     11     echo "mdview -- convert and view markdown files as PDF or HTML."
     12     echo "          With added style."
     13     echo
     14     echo "SYNOPSIS"
     15     echo "\tmdview [-hp] [-o OUTPUT] [-t TYPE] FILE"
     16     echo
     17     echo "\tFILE is a markdown file."
     18     echo
     19     echo "OPTIONS"
     20     echo "\t-h         Show this help page and exits."
     21     echo "\t-o OUTPUT  Name of file to output to. If unset, will open given"
     22     echo "\t           markdown file in either a web browser or pdf reader."
     23     echo "\t-p         Print output "
     24     echo "\t-t TYPE    Can be either \"pdf\" or \"html\""
     25     exit 1
     26 }
     27 
     28 while getopts "ho:pt:" o; do
     29 	case "$o" in
     30         h) usage ;;
     31 		o) out_name=$OPTARG ;;
     32 		p) print=true ;;
     33 		t) out_type=$OPTARG ;;
     34 	esac
     35 done
     36 shift "$((OPTIND-1))"
     37 
     38 [ ! -f "$1" ] && echo "no such file: $1" && exit
     39 
     40 prefix="/tmp/mdview_"
     41 tmp_md="${prefix}${1}.md"
     42 tmp_pdf="${prefix}${1}.${out_type}"
     43 
     44 cp "$1" "$tmp_md"
     45 
     46 echo '
     47 <style>
     48 	html {
     49 		font-family: "PT Serif", serif
     50 	}
     51 
     52 	body {
     53 		max-width: 100%; padding: 0;
     54 	}
     55 
     56 	h3, h4, h5, h6 {
     57 		margin-bottom: -0.75em;
     58 	}
     59 
     60 	h2 {
     61 		border-bottom: 1px solid;
     62 		/*page-break-before: always;*/
     63 	}
     64 
     65 	img {
     66 		display: block;
     67 		margin: auto;
     68 	}
     69 </style>' >> "$tmp_md"
     70 
     71 pandoc -s -t html -o "$tmp_pdf" "$tmp_md" 2>/dev/null
     72 
     73 rm_tmps() {
     74 	rm "$tmp_md"
     75 	rm "$tmp_pdf"
     76 }
     77 
     78 [ "$print" = "true" ] && lpr "$tmp_pdf" && rm_tmps && exit
     79 [ "$out_name" = "-" ] && cat "$tmp_pdf" && rm_tmps && exit
     80 if [ -z "$out_name" ]; then
     81 	[ "$out_type" = "pdf" ] && zathura "$tmp_pdf" && rm_tmps &
     82 	[ "$out_type" = "html" ] && surf "$tmp_pdf" 2>/dev/null && rm_tmps &
     83 fi
     84 [ -n "$out_name" ] && cp "$tmp_pdf" "$out_name"
     85