Skip to content

Instantly share code, notes, and snippets.

@tcely
Created February 5, 2015 02:38
Show Gist options
  • Save tcely/06c9d80cf0560505f8d1 to your computer and use it in GitHub Desktop.
Save tcely/06c9d80cf0560505f8d1 to your computer and use it in GitHub Desktop.
A bash function for displaying wrapped messages in ANSI terminal colors.
#!/bin/bash
#
# Requires:
# awk
# fmt
# tput
#
colorMsg() {
[ $# -gt 1 ] || return 0
tput -S <<< "$(printf '%s\n' 'sgr 0' ${1##*[0-7]} "setaf ${1%%[^0-7]*}")"
shift
if [ $# -gt 0 ]; then
local awkindenter='{
if (" " == substr($0, 0, 3)) {
print ind substr($0, 4)
} else if (NR > 1) {
if(pghb) {print ""}
print ind $0
} else {
print
}
}'
local indent="$(awk <<<"$1" '{
p="";
fwl=length($1);
while (fwl-- >= 0) {p=p " ";};
print p;
exit;
}')"
local width="$(( $(tput cols) * 90 / 100 ))"
(
echo "$1"
shift
[ $# -gt 0 ] && printf '%s\n' "$@"
) | fmt -t --width="${width:-75}" | awk -v pghb="${COLORMSG_PARAGRAPHS:-0}" -v ind="$indent" "$awkindenter"
fi
tput sgr 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment