View man pages in Preview

It’s not a new concept, but here is my take on it:

 1function man {
 2    # We can get the actual path to the man command here, so we can override
 3    # it with our function name.
 4    MAN=`which man`
 5    # Change these two if you are not on OS X.
 6    CACHE_DIR="${HOME}/Library/Caches/manpages"
 7    OPEN="open"
 8    
 9    # If we don't have any arguments, use the nice man error message
10    if [ ! $1 ]; then
11        $MAN
12        return
13    fi
14    
15    # If we have an argument that clashes with what we are wanting to be
16    # able to do, pass the whole command through.
17    for ARG in $*; do
18        case $ARG in 
19            -[dfkKwtWP])
20                $MAN $*
21                return;;
22        esac
23    done
24    
25    # Make sure our cache directory exists.
26    mkdir -p $CACHE_DIR
27    # Get the man page(s) that match our query.
28    MAN_FILES=`$MAN -w $*`
29    for MAN_FILE in $MAN_FILES; do
30        # Get the name of the man file, and the section.
31        MAN_PAGE=`basename "$MAN_FILE" | cut -d \. -f 1-2 | sed 's/\./(/' | sed 's/$/)/'`
32        # Our PDF will be in this location
33        PDF_FILE="${CACHE_DIR}/${MAN_PAGE}"
34        
35        # If we actually have a man file that matches
36        if [ -n "$MAN_FILE" ]; then
37            # See if the man file is newer than our cached PDF, and if it is,
38            # then generate a new PDF. This works even if $PDF_FILE does not
39            # exist.
40            if [ $MAN_FILE -nt $PDF_FILE ]; then
41                $MAN -t $* | pstopdf -i -o "$PDF_FILE"
42            fi
43            # Then display the file.
44            $OPEN "$PDF_FILE"
45        fi
46    done
47}