Easily converting from Markdown to PDF with Pandoc

Converting from Markdown to Pandoc is pretty easy, and documented as one of their own demos:

pandoc MANUAL.txt --pdf-engine=xelatex -o example13.pdf

Although it isn't a complicated command, it'd be nice to shorten it and to add command completion. With the following bash snippet, thats exactly what you get:

function md2pdf {
    local source="$1"
    local out="$2"
    
    if [[ -z "${source}" ]] || [[ -z "${out}" ]]; then
        echo "usage: $0 <input.md> <output.md>"
        return 1
    fi
    
    if [[ ! -f "$source" ]]; then
        echo "$source doesn't exist!"
        return 1
    fi
    
    pandoc "${source}" -V geometry:margin=1in --pdf-engine=xelatex --template eisvogel --listings -o "${out}"
}

function _md2pdf {
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    if [[ $COMP_CWORD == "1" ]]; then
        COMPREPLY=( $(compgen -W "$(command ls --color=never *.md)" -- ${cur}) )
    elif [[ $COMP_CWORD == "2" ]]; then
        COMPREPLY=( $(compgen -W "$(echo ${prev} | sed 's/.md/.pdf/')" -- ${cur}) )
    else
        COMPREPLY=( )
    fi
}

complete -F _md2pdf md2pdf

Note: The template mentioned above is https://github.com/Wandmalfarbe/pandoc-latex-template.

Copy the above into your ~/.bashrc and md2pdf will autocomplete the .md filename and will autocomplete the output name if needed.

md2pdf report.md report.pdf