bat-extras/lib/print.sh

87 lines
2.2 KiB
Bash
Raw Normal View History

2019-06-19 23:15:10 +02:00
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
2021-03-25 01:08:51 +01:00
# bat-extras | Copyright (C) 2021 eth-p | MIT License
2019-06-19 23:15:10 +02:00
#
# Repository: https://github.com/eth-p/bat-extras
# Issues: https://github.com/eth-p/bat-extras/issues
# -----------------------------------------------------------------------------
source "${LIB}/constants.sh"
2019-06-19 23:15:10 +02:00
# Printf, but with optional colors.
# This uses the same syntax and arguments as printf.
#
# Example:
# printc "%{RED}This is red %s.%{CLEAR}\n" "text"
#
printc() {
2020-03-31 23:51:00 +02:00
printf "$(sed "$_PRINTC_PATTERN" <<<"$1")" "${@:2}"
2019-06-19 23:15:10 +02:00
}
# Initializes the color tags for printc.
#
# Arguments:
2019-09-25 23:48:21 +02:00
# true -- Turns on color output.
# false -- Turns off color output.
2019-06-19 23:15:10 +02:00
printc_init() {
case "$1" in
true) _PRINTC_PATTERN="$_PRINTC_PATTERN_ANSI" ;;
2020-03-31 23:51:00 +02:00
false) _PRINTC_PATTERN="$_PRINTC_PATTERN_PLAIN" ;;
2019-06-19 23:15:10 +02:00
"[DEFINE]") {
2020-03-31 23:51:00 +02:00
_PRINTC_PATTERN_ANSI=""
_PRINTC_PATTERN_PLAIN=""
2019-06-19 23:15:10 +02:00
2020-03-31 23:51:00 +02:00
local name
local ansi
while read -r name ansi; do
if [[ -z "${name}" && -z "${ansi}" ]] || [[ "${name:0:1}" = "#" ]]; then
continue
fi
2019-06-19 23:15:10 +02:00
ansi="${ansi/\\/\\\\}"
2019-06-19 23:15:10 +02:00
2020-03-31 23:51:00 +02:00
_PRINTC_PATTERN_PLAIN="${_PRINTC_PATTERN_PLAIN}s/%{${name}}//g;"
_PRINTC_PATTERN_ANSI="${_PRINTC_PATTERN_ANSI}s/%{${name}}/${ansi}/g;"
done
2019-06-19 23:15:10 +02:00
2021-03-25 01:08:51 +01:00
if [[ -t 1 && -z "${NO_COLOR+x}" ]]; then
2020-03-31 23:51:00 +02:00
_PRINTC_PATTERN="$_PRINTC_PATTERN_ANSI"
else
_PRINTC_PATTERN="$_PRINTC_PATTERN_PLAIN"
fi
} ;;
2019-06-19 23:15:10 +02:00
esac
}
2020-03-31 23:51:00 +02:00
# Print a warning message to stderr.
# Arguments:
# 1 -- The printc formatting string.
# ... -- The printc formatting arguments.
print_warning() {
printc "%{YELLOW}[%s warning]%{CLEAR}: $1%{CLEAR}\n" "$PROGRAM" "${@:2}" 1>&2
}
2020-03-31 23:51:00 +02:00
# Print an error message to stderr.
# Arguments:
# 1 -- The printc formatting string.
# ... -- The printc formatting arguments.
print_error() {
printc "%{RED}[%s error]%{CLEAR}: $1%{CLEAR}\n" "$PROGRAM" "${@:2}" 1>&2
}
# -----------------------------------------------------------------------------
# Initialization:
# -----------------------------------------------------------------------------
printc_init "[DEFINE]" <<END
2019-06-19 23:15:10 +02:00
CLEAR \x1B[0m
RED \x1B[31m
GREEN \x1B[32m
YELLOW \x1B[33m
BLUE \x1B[34m
MAGENTA \x1B[35m
CYAN \x1B[36m
2020-10-04 09:40:05 +02:00
DEFAULT \x1B[39m
2019-06-19 23:15:10 +02:00
DIM \x1B[2m
END