2023-10-25 15:22:28 +00:00
|
|
|
#!/usr/bin/env bash
|
|
|
|
#
|
|
|
|
# The purpose of this script is to demonstrate how to preview a file or an
|
|
|
|
# image in the preview window of fzf.
|
2023-10-26 12:36:57 +00:00
|
|
|
#
|
|
|
|
# Dependencies:
|
|
|
|
# - https://github.com/hpjansson/chafa
|
|
|
|
# - https://github.com/sharkdp/bat
|
2023-10-25 15:22:28 +00:00
|
|
|
|
2023-10-29 15:05:20 +00:00
|
|
|
if [[ $# -ne 1 ]]; then
|
|
|
|
>&2 echo "usage: $0 FILENAME"
|
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
|
|
|
file=${1/#\~\//$HOME/}
|
2023-11-01 16:35:36 +00:00
|
|
|
type=$(file --dereference --mime -- "$file")
|
2023-11-01 15:14:11 +00:00
|
|
|
|
2023-10-25 15:22:28 +00:00
|
|
|
if [[ ! $type =~ image/ ]]; then
|
2023-11-01 16:35:36 +00:00
|
|
|
if [[ $type =~ =binary ]]; then
|
|
|
|
file "$1"
|
|
|
|
exit
|
|
|
|
fi
|
|
|
|
|
2023-10-25 15:22:28 +00:00
|
|
|
# Sometimes bat is installed as batcat.
|
|
|
|
if command -v batcat > /dev/null; then
|
|
|
|
batname="batcat"
|
|
|
|
elif command -v bat > /dev/null; then
|
|
|
|
batname="bat"
|
|
|
|
else
|
|
|
|
cat "$1"
|
|
|
|
exit
|
|
|
|
fi
|
|
|
|
|
|
|
|
${batname} --style="${BAT_STYLE:-numbers}" --color=always --pager=never -- "$file"
|
2023-11-01 16:35:36 +00:00
|
|
|
exit
|
|
|
|
fi
|
|
|
|
|
|
|
|
dim=${FZF_PREVIEW_COLUMNS}x${FZF_PREVIEW_LINES}
|
|
|
|
if [[ $dim = x ]]; then
|
|
|
|
dim=$(stty size < /dev/tty | awk '{print $2 "x" $1}')
|
|
|
|
elif ! [[ $KITTY_WINDOW_ID ]] && (( FZF_PREVIEW_TOP + FZF_PREVIEW_LINES == $(stty size < /dev/tty | awk '{print $1}') )); then
|
|
|
|
# Avoid scrolling issue when the Sixel image touches the bottom of the screen
|
|
|
|
# * https://github.com/junegunn/fzf/issues/2544
|
|
|
|
dim=${FZF_PREVIEW_COLUMNS}x$((FZF_PREVIEW_LINES - 1))
|
|
|
|
fi
|
|
|
|
|
|
|
|
if [[ $KITTY_WINDOW_ID ]]; then
|
2023-10-26 13:26:47 +00:00
|
|
|
# 1. 'memory' is the fastest option but if you want the image to be scrollable,
|
|
|
|
# you have to use 'stream'.
|
|
|
|
#
|
|
|
|
# 2. The last line of the output is the ANSI reset code without newline.
|
|
|
|
# This confuses fzf and makes it render scroll offset indicator.
|
|
|
|
# So we remove the last line and append the reset code to its previous line.
|
2023-11-01 15:14:11 +00:00
|
|
|
kitty icat --clear --transfer-mode=memory --stdin=no --place="$dim@0x0" "$file" | sed '$d' | sed $'$s/$/\e[m/'
|
2023-10-26 12:36:57 +00:00
|
|
|
elif command -v chafa > /dev/null; then
|
2023-11-01 15:14:11 +00:00
|
|
|
chafa -f sixel -s "$dim" "$file"
|
2023-11-01 16:35:36 +00:00
|
|
|
# Add a new line character so that fzf can display multiple images in the preview window
|
2023-11-01 15:14:11 +00:00
|
|
|
echo
|
2023-10-25 15:22:28 +00:00
|
|
|
else
|
|
|
|
file "$file"
|
|
|
|
fi
|