diff --git a/profile.d/disp.sh b/profile.d/disp.sh index 8f92da9..66cc69c 100644 --- a/profile.d/disp.sh +++ b/profile.d/disp.sh @@ -128,52 +128,107 @@ export -f set_colors # D : debug (cyan) disp() { + _disp_print_wrapped() + { + local prefix="$1" + local prefix_len="$2" + local target_fd="$3" + shift 3 + local message="$*" + + local cols="${COLUMNS:-}" + if [[ -z "$cols" || ! "$cols" =~ ^[0-9]+$ || "$cols" -lt 20 ]]; then + cols=$(tput cols 2>/dev/null) + fi + [[ -z "$cols" || ! "$cols" =~ ^[0-9]+$ || "$cols" -lt 20 ]] && cols=80 + + local indent_len=0 + [[ "$prefix_len" =~ ^[0-9]+$ && "$prefix_len" -gt 0 ]] && indent_len=$((prefix_len + 1)) + + local width=$((cols - indent_len)) + (( width < 10 )) && width=10 + + local wrapped + wrapped=$(printf "%s" "$message" | fold -s -w "$width") + + local first_line=1 + local line + while IFS= read -r line || [[ -n "$line" ]]; do + if (( first_line )); then + if [[ -n "$prefix" ]]; then + if [[ "$target_fd" -eq 2 ]]; then + printf "%b\n" "${prefix} ${line}${RESETCOL}" >&2 + else + printf "%b\n" "${prefix} ${line}${RESETCOL}" + fi + else + if [[ "$target_fd" -eq 2 ]]; then + printf "%b\n" "${line}${RESETCOL}" >&2 + else + printf "%b\n" "${line}${RESETCOL}" + fi + fi + first_line=0 + else + if [[ "$target_fd" -eq 2 ]]; then + printf "%*s%b\n" "$indent_len" "" "${line}${RESETCOL}" >&2 + else + printf "%*s%b\n" "$indent_len" "" "${line}${RESETCOL}" + fi + fi + done <<< "$wrapped" + } + # Handle NO_COLOR: disable colors if set local color_enabled=1 [[ -n $NO_COLOR ]] && color_enabled=0 case ${1^^} in "I") + local heads_plain="[ info ]" if [[ $color_enabled -eq 1 ]]; then local heads="[ ${IGreen}info${DEFAULTFG} ]" else - local heads="[ info ]" + local heads="$heads_plain" fi shift [[ -z $QUIET || $QUIET -ne 1 ]] && \ - printf "%b\n" "${heads} $*${RESETCOL}" + _disp_print_wrapped "$heads" "${#heads_plain}" 1 "$*" ;; "W") + local heads_plain="[ Warning ]" if [[ $color_enabled -eq 1 ]]; then local heads="[ ${IYellow}Warning${DEFAULTFG} ]" else - local heads="[ Warning ]" + local heads="$heads_plain" fi shift - printf "%b\n" "${heads} $*${RESETCOL}" >&2 + _disp_print_wrapped "$heads" "${#heads_plain}" 2 "$*" ;; "E") + local heads_plain="[ ERROR ]" if [[ $color_enabled -eq 1 ]]; then local heads="[ ${IRed}ERROR${DEFAULTFG} ]" else - local heads="[ ERROR ]" + local heads="$heads_plain" fi shift - printf "%b\n" "${heads} $*${RESETCOL}" >&2 + _disp_print_wrapped "$heads" "${#heads_plain}" 2 "$*" ;; "D") + local heads_plain="[ debug ]" if [[ $color_enabled -eq 1 ]]; then local heads="[ ${ICyan}debug${DEFAULTFG} ]" else - local heads="[ debug ]" + local heads="$heads_plain" fi shift [[ -n $DEBUG && $DEBUG -gt 1 ]] && \ - printf "%b\n" "${heads} $*${RESETCOL}" + _disp_print_wrapped "$heads" "${#heads_plain}" 1 "$*" ;; * ) [[ -z $QUIET || $QUIET -ne 1 ]] && \ - printf "%b\n" "$*" + _disp_print_wrapped "" 0 1 "$*" ;; esac }