lib: Add term.sh to more accurately get terminal width

This commit is contained in:
Ethan P 2020-05-02 16:58:17 -07:00
parent bdc2e6ea01
commit 427baf1491
No known key found for this signature in database
GPG Key ID: 6963FD04F6CF35EA
2 changed files with 29 additions and 1 deletions

View File

@ -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)"
}

27
lib/term.sh Normal file
View File

@ -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
}