MIAOU-BASH is a collection of settings and helpers for leveraging BASH. Developer-friendly, it may be used as solo package with or without the miaou project.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

122 lines
2.8 KiB

# CONSTANTS
# MARGIN=0
PADDING=0
ANSI_RESET='\e[0m'
BLOCK_CONTINUATION_COL=
BLOCK_CONTINUATION_SYMBOL=
declare -A STYLE_VARIANTS
STYLE_VARIANTS[BOLD]='\e[1m'
STYLE_VARIANTS[ITALIC]='\e[3m'
STYLE_VARIANTS[UNDERLINE]='\e[4m'
STYLE_VARIANTS[STRIKETHROUGH]='\e[9m'
declare -A FG_COLORS
FG_COLORS[BLACK]='\e[30m'
FG_COLORS[RED]='\e[31m'
FG_COLORS[GREEN]='\e[32m'
FG_COLORS[YELLOW]='\e[33m'
FG_COLORS[BLUE]='\e[34m'
FG_COLORS[PURPLE]='\e[35m'
FG_COLORS[CYAN]='\e[36m'
FG_COLORS[WHITE]='\e[37m'
FG_COLORS[GRAY]='\e[90m'
FG_COLORS[MAGENTA]='\e[95m'
declare -A BG_COLORS
BG_COLORS["BLACK"]='\e[40m'
BG_COLORS["RED"]='\e[41m'
BG_COLORS["GREEN"]='\e[42m'
BG_COLORS["YELLOW"]='\e[43m'
BG_COLORS["BLUE"]='\e[44m'
BG_COLORS["PURPLE"]='\e[45m'
BG_COLORS["CYAN"]='\e[46m'
BG_COLORS["WHITE"]='\e[47m'
# BG_COLORS["GRAY"]='\e[90m'
# BG_COLORS["MAGENTA"]='\e[95m'
# FUNCTIONS
function ansi_reset {
PADDING=0
unset PADDING_LEFT PADDING_RIGHT BG FG
}
function ansi_length {
local clean_text
clean_text=$(echo "$1" | sed 's/\x1B\[[0-9;]*m//g')
echo "${#clean_text}"
}
function style_padding {
local left right
local padding_left=${PADDING_LEFT:-$PADDING}
local padding_right=${PADDING_RIGHT:-$PADDING}
left=$(for _ in $(seq 1 "${padding_left}"); do builtin echo -n ' '; done)
style_ansi "$left"
style_ansi "$1"
# builtin echo -n "$1"
right=$(for _ in $(seq 1 "${padding_right}"); do builtin echo -n ' '; done)
style_ansi "$right"
}
function _style_fg {
[[ -n $1 ]] && echo "${FG_COLORS[$1]}" || true
}
function _style_variant {
[[ -n $1 ]] && echo "${STYLE_VARIANTS[$1]}" || true
}
function _style_bg {
if [[ -n "$1" ]]; then
[[ -v BG_COLORS[$1] ]] && echo "${BG_COLORS[$1]}" && return
>&2 echo "unknown BG value: $1" && return 1
# false
fi
}
function style_ansi {
local fg bg variant
fg=$(_style_fg "${FG:-}") && [[ -n $fg ]] && builtin echo -en "$fg"
bg=$(_style_bg "${BG:-}") && [[ -n $bg ]] && builtin echo -en "$bg"
variant=$(_style_variant "${STYLE:-}") && [[ -n $variant ]] && builtin echo -en "$variant"
builtin echo -en "$1"
[[ -n $fg || -n $bg || -n $variant ]] && builtin echo -en "$ANSI_RESET"
true
}
function style_block {
local content length top bottom i
content=$(style_padding "$1")
length=$(ansi_length "$content")
top=$(
builtin echo -n "╔"
for _ in $(seq 1 "${length}"); do builtin echo -n '═'; done
builtin echo "╗"
)
style_ansi "${top}" && builtin echo
style_ansi "║"
style_ansi "${content}"
style_ansi "║" && builtin echo
bottom=$(
builtin echo -n "╚"
for i in $(seq 1 "${length}"); do
if [[ $i == "$BLOCK_CONTINUATION_COL" ]]; then
builtin echo -n "$BLOCK_CONTINUATION_SYMBOL"
else
builtin echo -n '═'
fi
done
builtin echo "╝"
)
style_ansi "${bottom}" && builtin echo
}