Terminal Commands – How to Open PDF from Terminal Using Command Completion

macportsterminal

I'm used to the linux way of opening a PDF from the terminal. That is, via e.g. evince sample.pdf. Command completion makes this fairly fast. In particular when there are many files with the same name but different endings (like after pdflatex compilations). From macports I have the bash-completion, but it is ineffective for the open command in the sense that I have to cycle through all files until I get the PDF one. Is there another way of opening a PDF that allows to employ the bash-completion? Or a way to make open ignore certain file types?

Best Answer

open is a generic file-opener-thing so a generic completion for open must match anything open can open. One workaround is to invent a new command name, alias it to open, and then specify that the new command should complete PDF files.

bash-4.4$ alias viewpdf=open
bash-4.4$ complete -f -X '!*.@(pdf|PDF)' viewpdf

You could then use viewpdf to tab-complete-open PDF files. However this is rather incomplete as it only matches filenames unqualified with any directory path. With more complexity:

alias viewpdf=open
function _viewpdf()
{
   local word=${COMP_WORDS[COMP_CWORD]}
   COMPREPLY=($(compgen -f -X "!*.@(pdf|PDF)" -- "${word}"))
}
complete -d -X '.[^./]*' -F _viewpdf viewpdf

Which should be saved into a bash rc file.

If you instead use the Z-Shell zsh the completion might look like

REVERT=$options[COMPLETE_ALIASES]
setopt COMPLETE_ALIASES
alias viewpdf=open
compdef '_files -g "*.(pdf|PDF)"' viewpdf
options[COMPLETE_ALIASES]=$REVERT
unset REVERT