From 427baf1491fb05a7a8996da5f392d09af2802925 Mon Sep 17 00:00:00 2001 From: Ethan P Date: Sat, 2 May 2020 16:58:17 -0700 Subject: [PATCH] lib: Add term.sh to more accurately get terminal width --- lib/opt_hook_width.sh | 3 ++- lib/term.sh | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 lib/term.sh diff --git a/lib/opt_hook_width.sh b/lib/opt_hook_width.sh index 94e2229..2eb9390 100644 --- a/lib/opt_hook_width.sh +++ b/lib/opt_hook_width.sh @@ -5,6 +5,7 @@ # Repository: https://github.com/eth-p/bat-extras # Issues: https://github.com/eth-p/bat-extras/issues # ----------------------------------------------------------------------------- +source "${LIB}/term.sh" # Option parser hook: --terminal-width support. # This will accept --terminal-width=number. @@ -23,5 +24,5 @@ hook_width() { } # Default terminal width. - OPT_TERMINAL_WIDTH="$({ stty size 2>/dev/null || echo "22 80"; } | cut -d' ' -f 2)" + OPT_TERMINAL_WIDTH="$(term_width)" } diff --git a/lib/term.sh b/lib/term.sh new file mode 100644 index 0000000..d4ca2ac --- /dev/null +++ b/lib/term.sh @@ -0,0 +1,27 @@ +# ----------------------------------------------------------------------------- +# bat-extras | Copyright (C) 2020 eth-p | MIT License +# +# Repository: https://github.com/eth-p/bat-extras +# Issues: https://github.com/eth-p/bat-extras/issues +# ----------------------------------------------------------------------------- + +# Gets the width of the terminal. +# This will return 80 unless stdin is attached to the terminal. +# +# Returns: +# The terminal width, or 80 if there's no TTY. +# +term_width() { + if ! [[ -t 0 ]]; then + echo "80" + return 0 + fi + + # shellcheck disable=SC2155 + local width="$(stty size 2>/dev/null | cut -d' ' -f2)" + if [[ -z "$width" ]]; then + echo "80" + else + echo "$width" + fi +}