mirror of
https://github.com/eth-p/bat-extras.git
synced 2024-12-12 17:20:40 +01:00
76 lines
1.7 KiB
Bash
76 lines
1.7 KiB
Bash
#!/usr/bin/env bash
|
|
# -----------------------------------------------------------------------------
|
|
# bat-extras | Copyright (C) 2019 eth-p | MIT License
|
|
#
|
|
# Repository: https://github.com/eth-p/bat-extras
|
|
# Issues: https://github.com/eth-p/bat-extras/issues
|
|
# -----------------------------------------------------------------------------
|
|
|
|
# Defaults.
|
|
_SCRIPT_PAGER_NAME=
|
|
SCRIPT_PAGER_CMD=("$PAGER")
|
|
SCRIPT_PAGER_ARGS=()
|
|
|
|
# Add arguments for the less pager.
|
|
if [[ "$(basename "${SCRIPT_PAGER_CMD[0]}")" = "less" ]]; then
|
|
SCRIPT_PAGER_ARGS=(-R)
|
|
fi
|
|
|
|
# Prefer the bat pager.
|
|
if [[ -n "${BAT_PAGER+x}" ]]; then
|
|
SCRIPT_PAGER_CMD=($BAT_PAGER)
|
|
SCRIPT_PAGER_ARGS=()
|
|
fi
|
|
|
|
# Prefer no pager if not a tty.
|
|
if ! [[ -t 1 ]]; then
|
|
SCRIPT_PAGER_CMD=()
|
|
SCRIPT_PAGER_ARGS=()
|
|
fi
|
|
|
|
# -----------------------------------------------------------------------------
|
|
|
|
# Gets the pager name.
|
|
pager_name() {
|
|
if [[ -z "${SCRIPT_PAGER_CMD[0]}" ]]; then return; fi
|
|
if [[ -z "$_SCRIPT_PAGER_NAME" ]]; then
|
|
local output="$("${SCRIPT_PAGER_CMD[0]}" --version 2>&1)"
|
|
|
|
if head -n 1 <<< "$output" | grep '^less \d' &>/dev/null; then
|
|
_SCRIPT_PAGER_NAME="less"
|
|
fi
|
|
fi
|
|
|
|
echo "$_SCRIPT_PAGER_NAME"
|
|
}
|
|
|
|
# Executes a command or function, and pipes its output to the pager (if exists).
|
|
#
|
|
# Returns: The exit code of the command.
|
|
# Example:
|
|
# pager_exec echo hi
|
|
pager_exec() {
|
|
if [[ -n "$1" ]]; then
|
|
if [[ -n "$SCRIPT_PAGER_CMD" ]]; then
|
|
"$@" | "${SCRIPT_PAGER_CMD[@]}" "${SCRIPT_PAGER_ARGS[@]}"
|
|
return $?
|
|
else
|
|
"$@"
|
|
return $?
|
|
fi
|
|
fi
|
|
}
|
|
|
|
# Displays the output of a command or function inside the pager (if exists).
|
|
#
|
|
# Example:
|
|
# bat | pager_display
|
|
pager_display() {
|
|
if [[ -n "$SCRIPT_PAGER_CMD" ]]; then
|
|
"${SCRIPT_PAGER_CMD[@]}" "${SCRIPT_PAGER_ARGS[@]}"
|
|
else
|
|
cat
|
|
fi
|
|
}
|
|
|