-
Notifications
You must be signed in to change notification settings - Fork 0
/
colr.sh
executable file
·338 lines (309 loc) · 9.28 KB
/
colr.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/bin/bash
# Bash color function to colorize text by name, instead of number.
# Also includes maps from name to escape code for fore, back, and styles.
# -Christopher Welborn 08-27-2015
# Variables are namespaced to not interfere when sourced.
colr_app_name="Colr"
colr_app_version="0.4.0"
colr_app_path="$(readlink -f "${BASH_SOURCE[0]}")"
colr_app_script="${colr_app_path##*/}"
# This flag can be set with colr_enable or colr_disable.
colr_disabled=0
# Functions to format a color number into an actual escape code.
function codeformat {
# Basic fore, back, and styles.
printf "\033[%sm" "$1"
}
function extforeformat {
# 256 fore color
printf "\033[38;5;%sm" "$1"
}
function extbackformat {
# 256 back color
printf "\033[48;5;%sm" "$1"
}
# Maps from color/style name -> escape code.
declare -A fore back style
function build_maps {
# Build the fore/back maps.
# Names and corresponding base code number
local colornum
# shellcheck disable=SC2102
declare -A colornum=(
[black]=0
[red]=1
[green]=2
[yellow]=3
[blue]=4
[magenta]=5
[cyan]=6
[white]=7
)
local cname
for cname in "${!colornum[@]}"; do
fore[$cname]="$(codeformat $((30 + ${colornum[$cname]})))"
fore[light$cname]="$(codeformat $((90 + ${colornum[$cname]})))"
back[$cname]="$(codeformat $((40 + ${colornum[$cname]})))"
back[light$cname]="$(codeformat $((100 + ${colornum[$cname]})))"
done
# shellcheck disable=SC2154
fore[reset]="$(codeformat 39)"
back[reset]="$(codeformat 49)"
# 256 colors.
local cnum
for cnum in {0..255}; do
fore[$cnum]="$(extforeformat "$cnum")"
back[$cnum]="$(extbackformat "$cnum")"
done
# Map of base code -> style name
local stylenum
# shellcheck disable=SC2102
declare -A stylenum=(
[reset]=0
[bright]=1
[dim]=2
[italic]=3
[underline]=4
[flash]=5
[highlight]=7
[normal]=22
)
# Aliases
stylenum[bold]=1
stylenum[b]=1
stylenum[d]=0
stylenum[i]=3
stylenum[u]=4
stylenum[f]=5
stylenum[h]=7
stylenum[n]=22
local sname
for sname in "${!stylenum[@]}"; do
style[$sname]="$(codeformat "${stylenum[$sname]}")"
done
}
build_maps
function colr {
# Colorize a string.
local text="$1"
if ((colr_disabled)); then
# Color has been globally disabled.
echo -en "$text"
return
fi
local forecolr="${2:-reset}"
local backcolr="${3:-reset}"
local stylename="${4:-normal}"
declare -a codes resetcodes
if [[ "$stylename" =~ ^reset ]]; then
resetcodes=("${style[$stylename]}" "${resetcodes[@]}")
else
codes=("${codes[@]}" "${style[$stylename]}")
fi
if [[ "$backcolr" =~ reset ]]; then
resetcodes=("${back[$backcolr]}" "${resetcodes[@]}")
else
codes=("${codes[@]}" "${back[$backcolr]}")
fi
if [[ "$forecolr" =~ reset ]]; then
resetcodes=("${fore[$forecolr]}" "${resetcodes[@]}")
else
codes=("${codes[@]}" "${fore[$forecolr]}")
fi
# Reset codes must come first (style reset can affect colors)
local rc
for rc in "${resetcodes[@]}"; do
echo -en "$rc"
done
local c
for c in "${codes[@]}"; do
echo -en "$c"
done
local closing="\033[m"
echo -n "$text"
echo -en "$closing"
}
function colr_auto_disable {
# Auto disable colors if stdout is not a tty,
# or if the user supplied file descriptors are not ttys.
# Arguments:
# $@ : One or more TTY numbers to check.
# Default: 1
if (($# == 0)); then
# Just check stdout by default.
if [[ ! -t 1 ]] || [[ -p 1 ]]; then
colr_disabled=1
fi
return
fi
# Make sure all user's tty args are ttys.
local ttynum
for ttynum in "$@"; do
if [[ ! -t "$ttynum" ]] || [[ -p "$ttynum" ]]; then
colr_disabled=1
break
fi
done
}
function colr_enable {
# Re-enable colors after colr_disable has been called.
colr_disabled=0
}
function colr_disable {
# Disable colors for the `colr` function.
colr_disabled=1
}
function colr_is_disabled {
# Returns success code if colr_disabled is non-zero.
((colr_disabled)) && return 0
return 1
}
function colr_is_enabled {
# Returns success code if colr_disabled is zero.
((colr_disabled)) && return 1
return 0
}
function echo_err {
# Print to stderr.
printf "%s " "$@" 1>&2
printf "\n" 1>&2
}
function escape_code_repr {
# Print the representation of an escape code,
# without escaping (without setting a color, style, etc.)
# This will replace all escape codes in a string with their
# representation.
# Arguments:
# $@ : The escape codes or strings to show.
(($#)) || {
echo_err "No arguments passed to escape_code_repr."
return 1
}
local escapecode
for escapecode; do
printf "%s" "${escapecode//$'\033'/$'\\033'}"
done
}
function print_usage {
# Show usage reason if first arg is available.
[[ -n "$1" ]] && echo -e "\n$1\n"
local b="${fore[blue]}" B="${style[bright]}" R="${style[reset]}"
local g="${fore[green]}" y="${fore[yellow]}"
local name=$colr_app_name script=$colr_app_script ver=$colr_app_version
echo "${b}${B}\
${name} v. ${ver}${R}
Usage:${b}
$script ${y}-h | -l | -L | -v
${b}$script ${y}TEXT FORE [BACK] [STYLE]
${b}$script ${y}-r TEXT
${R}
Options:$g
BACK ${R}:${g} Name of back color for the text.
FORE ${R}:${g} Name of fore color for the text.
STYLE ${R}:${g} Name of style for the text.
TEXT ${R}:${g} Text to colorize.
-h,--help ${R}:${g} Show this message.
-L,--listcodes ${R}:${g} List all colors and escape codes exported
by this script.
-l,--liststyles ${R}:${g} List all colors exported by this script.
-r,--repr ${R}:${g} Show a representation of escape codes found
in a string.
This may also be used on stdin data.
-v,--version ${R}:${g} Show ${b}${B}${name}${R}${g} version and exit.
${R}"
}
export colr
export fore
export back
export style
if [[ "$0" == "${BASH_SOURCE[0]}" ]]; then
declare -a userargs
do_forced=0
do_list=0
do_listcodes=0
for arg; do
case "$arg" in
"-f"|"--force" )
do_forced=1
;;
"-h"|"--help" )
print_usage ""
exit 0
;;
"-L"|"--listcodes" )
do_listcodes=1
do_list=1
;;
"-l"|"--liststyles" )
do_list=1
;;
"-r"|"--repr" )
do_repr=1
;;
"-v"|"--version" )
echo -e "$colr_app_name v. $colr_app_version\n"
exit 0
;;
-*)
print_usage "Unknown flag argument: $arg"
exit 1
;;
*)
userargs=("${userargs[@]}" "$arg")
esac
done
# Script was executed.
# Automatically disable colors if stdout is not a tty, unless forced.
((do_forced)) || colr_auto_disable 1
maxwidth=7
maxwidthstyle=4
namefmt="%s "
((do_listcodes)) && {
maxwidth=3
maxwidthstyle=3
namefmt="%s: "
}
if ((do_list)); then
printf "Fore/Back"
((do_listcodes)) && printf " (fore code shown, use 48;5; for back colors)"
printf ":\n"
cnt=1
declare -a sortednames=($(printf "%s\n" "${!fore[@]}" | sort -n))
for name in "${sortednames[@]}"; do
# shellcheck disable=SC2059
# I am using a variable format on purpose shellcheck.
printf "$namefmt" "$(colr "$(printf "%12s" "$name")" "$name")"
((do_listcodes)) && colr "$(printf "%-16s" "$(escape_code_repr "${fore[$name]}")")" "$name"
((cnt == maxwidth)) && { printf "\n"; cnt=0; }
let cnt+=1
done
printf "\nStyles:\n"
cnt=1
sortednames=($(printf "%s\n" "${!style[@]}" | sort))
for name in "${sortednames[@]}"; do
# shellcheck disable=SC2059
printf "$namefmt" "$(colr "$(printf "%12s" "$name")" "reset" "reset" "$name")"
((do_listcodes)) && colr "$(printf "%-16s" "$(escape_code_repr "${style[$name]}")")" "reset" "reset" "$name"
((cnt == maxwidthstyle)) && { printf "\n"; cnt=0; }
let cnt+=1
done
printf "\n"
elif ((do_repr)); then
((${#userargs[@]})) || {
# Read lines from stdin.
[[ -t 0 ]] && echo -e "\nReading from stdin until EOF (Ctrl + D)...\n"
nl=$'\n'
while IFS= read -r line; do
# Split on spaces.
userargs+=("${line}${nl}")
done
}
((${#userargs[@]})) || {
echo -e "\nNo text to work with for --repr.\n" 1>&2
exit 1
}
printf "%s\n" "$(escape_code_repr "${userargs[@]}")"
else
colr "${userargs[@]}"
fi
fi