dotfiles/.config/zsh/functions/cat-highlight

55 lines
1.3 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env zsh
# Highlight cat output with either $CATOPEN, ~/.lessfilter or $LESSOPEN. The
# command needs to have %s in it that will be replaced with input files (one by
# one). Some programs that are known to not work will be ignored in $LESSOPEN
# but not in $CATOPEN.
# Example:
# export CATOPEN="highlight --force --out-format=truecolor --stdout %s"
# alias cat='cat-highlight'
setopt LOCAL_OPTIONS PIPE_FAIL
# Check if we are in a terminal
if [[ ! -t 1 ]]; then
\cat ${@}
return ${?}
fi
# Try to find highlighter
if [[ -v CATOPEN && -n ${CATOPEN} ]]; then
local catopen=${CATOPEN}
elif [[ -x ~/.lessfilter ]]; then
local catopen="~/.lessfilter %s"
elif [[ -v LESSOPEN && -n ${LESSOPEN} ]]; then
local catopen="${LESSOPEN/|/}"
# Programs that won't work with cat
local -a known_bad=("lesspipe")
for baddy in ${known_bad}; do
if [[ ${LESSOPEN} =~ ${baddy} ]]; then
unset catopen
fi
done
fi
if [[ ! -v catopen ]]; then
\cat ${@}
return ${?}
fi
local -a args
local -a files
for arg in ${@}; do
# Filter out file names
if [[ ${arg[1]} != "-" ]]; then
files+=${(q)arg}
else
args+=${arg}
fi
done
for file in ${files}; do
eval "${catopen/\%s/${file}}" 2>& -
[[ ${?} -eq 0 ]] || \cat ${file}
done | \cat ${args}