dotfiles/.config/zsh/functions/cat-highlight
tastytea 23ad6625ba
cat-highlight: Fix error check
It caused cat-highlight to always return with an error status.
2022-04-25 00:16:38 +02:00

55 lines
1.3 KiB
Bash
Executable File

#!/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}