3 # Description: Terminal based file previewer
5 # Note: This plugin needs a "NNN_FIFO" to work. See man.
8 # - Supports 6 independent methods to preview with:
10 # - kitty with allow_remote_control and listen_on set in kitty.conf, or
11 # - wezterm (https://wezfurlong.org/wezterm), or
12 # - QuickLook on WSL (https://github.com/QL-Win/QuickLook), or
13 # - Windows Terminal (https://github.com/Microsoft/Terminal | https://aka.ms/terminal) with WSL, or
14 # - $NNN_TERMINAL set to a terminal (it's xterm by default).
15 # - less or $NNN_PAGER
16 # - tree or exa/eza or (GNU) ls
22 # - optional: bsdtar or atool for additional archive preview
23 # - optional: bat for code syntax highlighting
24 # - optional: ueberzug, kitty terminal, wezterm terminal, img2sixel, viu, catimg or chafa for images
25 # - optional: convert(ImageMagick) for playing gif preview (mandatory for kitty image previews)
26 # - optional: mpv for gif and video
27 # Also requires a terminal supporting the sixel (https://www.arewesixelyet.com/)
28 # or kitty (https://sw.kovidgoyal.net/kitty/graphics-protocol) video_output backends.
29 # Requires tmux compiled with `./configure --enable-sixel` if used.
30 # - optional: ffmpegthumbnailer for video thumbnails (https://github.com/dirkvdb/ffmpegthumbnailer)
31 # - optional: ffmpeg for audio thumbnails
32 # - optional: libreoffce for opendocument/officedocument preview
33 # - optional: pdftoppm(poppler) for pdf thumbnails
34 # - optional: gnome-epub-thumbnailer for epub thumbnails (https://gitlab.gnome.org/GNOME/gnome-epub-thumbnailer)
35 # - optional: fontpreview for font preview (https://github.com/sdushantha/fontpreview)
36 # - optional: djvulibre for djvu
37 # - optional: glow or lowdown for markdown
38 # - optional: w3m or lynx or elinks for html
39 # - optional: set/export NNN_ICONLOOKUP as 1 to enable file icons in front of directory previews with .iconlookup
40 # Icons and colors are configurable in .iconlookup
41 # - optional: scope.sh file viewer from ranger.
42 # 1. drop scope.sh executable in $PATH
43 # 2. set/export $NNN_SCOPE as 1
44 # - optional: pistol file viewer (https://github.com/doronbehar/pistol).
46 # 2. set/export $NNN_PISTOL as 1
49 # You need to set a NNN_FIFO path and a key for the plugin with NNN_PLUG,
56 # $ NNN_FIFO=/tmp/nnn.fifo nnn
58 # Then launch the `preview-tui` plugin in `nnn`.
60 # If you provide the same NNN_FIFO to all nnn instances, there will be a
61 # single common preview window. If you provide different FIFO path (e.g.
62 # with -a), they will be independent.
64 # The previews will be shown in a tmux split. If that isn't possible, it
65 # will try to use a kitty terminal split. And as a final fallback, a
66 # different terminal window will be used ($NNN_TERMINAL).
68 # Kitty users need something similar to the following in their kitty.conf:
69 # - `allow_remote_control yes`
70 # - `listen_on unix:$TMPDIR/kitty`
71 # - `enabled_layouts splits` (optional)
72 # With ImageMagick installed, this terminal can use the icat kitten to display images.
73 # Refer to kitty documentation for further details.
75 # Wezterm should work out of the box. If `NNN_PREVIEWIMGPROG` is not specified it will use
76 # built in iTerm2 image protocol.
78 # Note that GNU ls is used for its `--group-directories-first` flag.
79 # On MacOS this may be installed with `brew install coreutils`, or the flag can be removed.
80 # iTerm2 users are recommended to use viu to view images without getting pixelated.
82 # Windows Terminal users can set "Profile termination behavior" under "Profile > Advanced" settings
83 # to automatically close pane on quit when exit code is 0.
85 # When specifying a different terminal, additional arguments are supported. In particular, you can
86 # append a specific title to the terminal and set it to "nofocus" in your WM config.
87 # E.g for alacritty and i3, you can set $NNN_TERMINAL to 'alacritty --title preview-tui' and add
88 # 'no_focus [title="preview-tui"]' to your i3 config file.
90 # Shell: Bash (for environment manipulation through arrays)
91 # Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal, @WanderLanz
93 # Configurable environment variables:
94 NNN_SPLIT=${NNN_SPLIT:-} # permanent split direction
95 NNN_TERMINAL=${NNN_TERMINAL:-} # external terminal to be used
96 NNN_SPLITSIZE=${NNN_SPLITSIZE:-50} # previewer split size percentage
97 TMPDIR=${TMPDIR:-/tmp} # location of temporary files
99 "NNN_SCOPE=${NNN_SCOPE:-0}" # use scope
100 "NNN_PISTOL=${NNN_PISTOL:-0}" # use pistol
101 "NNN_ICONLOOKUP=${NNN_ICONLOOKUP:-0}" # use .iconlookup
102 "NNN_PAGER=${NNN_PAGER:-less -P?n -R -C}" # pager options
103 "NNN_BATTHEME=${NNN_BATTHEME:-ansi}" # bat theme
104 "NNN_BATSTYLE=${NNN_BATSTYLE:-numbers}" # bat style
105 "NNN_PREVIEWWIDTH=${NNN_PREVIEWWIDTH:-1920}" # width of generated preview images
106 "NNN_PREVIEWHEIGHT=${NNN_PREVIEWHEIGHT:-1080}" # height of generated preview images
107 "NNN_PREVIEWDIR=${NNN_PREVIEWDIR:-$TMPDIR/nnn/previews}" # location of generated preview images
108 "NNN_PREVIEWIMGPROG=${NNN_PREVIEWIMGPROG:-}" # program used to preview images
109 "NNN_PREVIEWVIDEO=${NNN_PREVIEWVIDEO:-}" # mpv backend used to preview video
111 # Non-configurable environment variables
112 NNN_PARENT=${NNN_FIFO#*.}
113 [ "$NNN_PARENT" -eq "$NNN_PARENT" ] 2>/dev/null || NNN_PARENT="" # Make empty if non-numeric
118 "FIFOPID=$TMPDIR/nnn-preview-tui-fifopid.$NNN_PARENT"
119 "FIFOPATH=$TMPDIR/nnn-preview-tui-fifo.$NNN_PARENT"
120 "PREVIEWPID=$TMPDIR/nnn-preview-tui-previewpid.$NNN_PARENT"
121 "CURSEL=$TMPDIR/nnn-preview-tui-selection.$NNN_PARENT"
122 "FIFO_UEBERZUG=$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NNN_PARENT"
123 "POSOFFSET=$TMPDIR/nnn-preview-tui-posoffset"
127 exists() { type "$1" >/dev/null 2>&1 ;}
128 pkill() { command pkill "$@" >/dev/null 2>&1 ;}
129 prompt() { clear; printf "%b" "$@"; cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg" ;}
132 PID="$(cat "$1" 2>/dev/null)" || return 1
133 kill "$PID" >/dev/null 2>&1
135 wait "$PID" 2>/dev/null
142 if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
144 exists mpv && tmux display -p '#{client_termfeatures}' | grep -q 'sixel' && ENVVARS+=("NNN_PREVIEWVIDEO=sixel")
145 elif [ -n "$KITTY_LISTEN_ON" ]; then
147 exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=kitty")
148 elif [ -n "$WEZTERM_PANE" ]; then
150 exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=kitty")
151 elif [ -z "$NNN_TERMINAL" ] && [ "$TERM_PROGRAM" = "iTerm.app" ]; then
153 exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=sixel")
154 elif [ -n "$WT_SESSION" ]; then
157 NNN_TERMINAL="${NNN_TERMINAL:-xterm}"
160 if [ -z "$NNN_SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
162 elif [ "$NNN_SPLIT" != 'h' ]; then
166 ENVVARS+=("NNN_TERMINAL=$NNN_TERMINAL" "NNN_SPLIT=$NNN_SPLIT" "QLPATH=$2" "PREVIEW_MODE=1")
167 case "$NNN_TERMINAL" in
168 iterm|winterm) # has to run in separate shell command: escape
169 ENVVARS=("${ENVVARS[@]/#/\\\"}")
170 ENVVARS=("${ENVVARS[@]/%/\\\"}")
171 command="$SHELL -c 'env ${ENVVARS[*]} \\\"$0\\\" \\\"$1\\\"'" ;;
174 case "$NNN_TERMINAL" in
175 tmux) # tmux splits are inverted
176 ENVVARS=("${ENVVARS[@]/#/-e}")
177 if [ "$NNN_SPLIT" = "v" ]; then split="h"; else split="v"; fi
178 tmux split-window -l"$NNN_SPLITSIZE"% "${ENVVARS[@]}" -d"$split" -p"$NNN_SPLITSIZE" "$0" "$1" ;;
179 kitty) # Setting the layout for the new window. It will be restored after the script ends.
180 ENVVARS=("${ENVVARS[@]/#/--env=}")
181 kitty @ goto-layout splits
182 # Trying to use kitty's integrated window management as the split window.
183 kitty @ launch --no-response --title "preview-tui" --keep-focus \
184 --cwd "$PWD" "${ENVVARS[@]}" --location "${NNN_SPLIT}split" "$0" "$1" ;;
186 export "${ENVVARS[@]}"
187 if [ "$NNN_SPLIT" = "v" ]; then split="--horizontal"; else split="--bottom"; fi
188 wezterm cli split-pane --cwd "$PWD" $split --percent "$NNN_SPLITSIZE" "$0" "$1" >/dev/null
189 wezterm cli activate-pane-direction Prev ;;
191 if [ "$NNN_SPLIT" = "h" ]; then split="horizontally"; else split="vertically"; fi
193 tell application "iTerm"
194 tell current session of current window
195 split $split with default profile command "$command"
201 if [ "$NNN_SPLIT" = "h" ]; then split="H"; else split="V"; fi
202 wt -w 0 sp -$split -s"0.$NNN_SPLITSIZE" "$command" \; -w 0 mf previous 2>/dev/null ;;
203 *) if [ -n "$2" ]; then
204 env "${ENVVARS[@]}" QUICKLOOK=1 "$0" "$1" &
206 # shellcheck disable=SC2086 # (allow arguments)
207 env "${ENVVARS[@]}" $NNN_TERMINAL -e "$0" "$1" &
213 export "${ENVVARS[@]}"
214 if exists QuickLook.exe; then
215 QLPATH="QuickLook.exe"
216 elif exists Bridge.exe; then
219 if pidkill "$FIFOPID"; then
220 [ -p "$NNN_PPIPE" ] && printf "0" > "$NNN_PPIPE"
221 pidkill "$PREVIEWPID"
222 pkill -f "tail --follow $FIFO_UEBERZUG"
223 if [ -n "$QLPATH" ] && stat "$1"; then
224 f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
227 [ -p "$NNN_PPIPE" ] && printf "1" > "$NNN_PPIPE"
228 start_preview "$1" "$QLPATH"
236 # We use a FIFO to access $NNN_PAGER PID in jobs control
237 mkfifo "$FIFOPATH" || return
239 $NNN_PAGER < "$FIFOPATH" &
240 printf "%s" "$!" > "$PREVIEWPID"
244 if [ "$cmd" = "pager" ]; then
246 bat --terminal-width="$cols" --decorations=always --color=always \
247 --paging=never --style="$NNN_BATSTYLE" --theme="$NNN_BATTHEME" "$@" &
259 # Binary file: show file info inside the pager
261 printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
262 if exists mediainfo; then
271 image/jpeg) image_preview "$cols" "$lines" "$1" ;;
272 image/gif) generate_preview "$cols" "$lines" "$1" "gif" ;;
273 image/vnd.djvu) generate_preview "$cols" "$lines" "$1" "djvu" ;;
274 image/*) generate_preview "$cols" "$lines" "$1" "image" ;;
275 video/*) generate_preview "$cols" "$lines" "$1" "video" ;;
276 audio/*) generate_preview "$cols" "$lines" "$1" "audio" ;;
277 application/font*|application/*opentype|font/*) generate_preview "$cols" "$lines" "$1" "font" ;;
278 */*office*|*/*document*|*/*msword|*/*ms-excel) generate_preview "$cols" "$lines" "$1" "office" ;;
279 application/zip) fifo_pager unzip -l "$1" ;;
282 fifo_pager man -Pcat -l "$1"
284 fifo_pager pager "$1"
286 *) handle_ext "$1" "$3" "$4" ;;
292 epub) generate_preview "$cols" "$lines" "$1" "epub" ;;
293 pdf) generate_preview "$cols" "$lines" "$1" "pdf" ;;
294 gz|bz2) fifo_pager tar -tvf "$1" ;;
295 md) if exists glow; then
296 fifo_pager glow -s dark "$1"
297 elif exists lowdown; then
298 fifo_pager lowdown -Tterm "$1"
300 fifo_pager pager "$1"
305 elif exists lynx; then
307 elif exists elinks; then
308 fifo_pager elinks "$1"
310 fifo_pager pager "$1"
312 7z|a|ace|alz|arc|arj|bz|cab|cpio|deb|jar|lha|lz|lzh|lzma|lzo\
313 |rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z)
314 if exists atool; then
315 fifo_pager atool -l "$1"
316 elif exists bsdtar; then
317 fifo_pager bsdtar -tvf "$1"
319 *) if [ "$3" = "bin" ]; then
320 fifo_pager print_bin_info "$1"
322 fifo_pager pager "$1"
329 # Trying to use pistol if it's available.
330 if [ "$NNN_PISTOL" -ne 0 ] && exists pistol; then
331 fifo_pager pistol "$1"
335 # Trying to use scope.sh if it's available.
336 if [ "$NNN_SCOPE" -ne 0 ] && exists scope.sh; then
337 fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" "True"
341 # Use QuickLook if it's available.
342 if [ -n "$QUICKLOOK" ]; then
343 stat "$1" && f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
347 # Detecting the exact type of the file: the encoding, mime type, and extension in lowercase.
348 encoding="$(file -bL --mime-encoding -- "$1")"
349 mimetype="$(file -bL --mime-type -- "$1")"
351 [ -n "$ext" ] && ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
355 # Otherwise, falling back to the defaults.
358 if [ "$NNN_ICONLOOKUP" -ne 0 ] && [ -f "$(dirname "$0")"/.iconlookup ]; then
359 [ "$NNN_SPLIT" = v ] && BSTR="\n"
360 # shellcheck disable=SC2012
361 ls -F --group-directories-first | head -n "$((lines - 3))" | "$(dirname "$0")"/.iconlookup -l "$cols" -B "$BSTR" -b " "
362 elif exists tree; then
363 fifo_pager tree --filelimit "$(find . -maxdepth 1 | wc -l)" -L 3 -C -F --dirsfirst --noreport
364 elif exists exa; then
365 exa -G --group-directories-first --colour=always
366 elif exists eza; then # eza is a community fork of exa (exa is unmaintained)
367 eza -G --group-directories-first --colour=always
369 fifo_pager ls -F --group-directories-first --color=always
372 elif [ "${encoding#*)}" = "binary" ]; then
373 handle_mime "$1" "$mimetype" "$ext" "bin"
375 handle_mime "$1" "$mimetype" "$ext"
380 if [ -n "$QLPATH" ] && stat "$3"; then
381 f="$(wslpath -w "$3")" && "$QLPATH" "$f" &
382 elif [ -n "$NNN_PREVIEWVIDEO" ] && [[ "$4" == +(gif|video) ]]; then
383 [ "$4" = "video" ] && args=(--start=10% --length=4) || args=()
384 video_preview "$1" "$2" "$3" "${args[@]}" && return
385 elif [ ! -f "$NNN_PREVIEWDIR/$3.jpg" ] || [ -n "$(find -L "$3" -newer "$NNN_PREVIEWDIR/$3.jpg")" ]; then
386 mkdir -p "$NNN_PREVIEWDIR/${3%/*}"
388 audio) ffmpeg -i "$3" -filter_complex "scale=iw*min(1\,min($NNN_PREVIEWWIDTH/iw\,ih)):-1" "$NNN_PREVIEWDIR/$3.jpg" -y ;;
389 epub) gnome-epub-thumbnailer "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
390 font) fontpreview -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" ;;
391 gif) if [ -p "$FIFO_UEBERZUG" ] && exists convert; then
392 frameprefix="$NNN_PREVIEWDIR/$3/${3##*/}"
393 if [ ! -d "$NNN_PREVIEWDIR/$3" ]; then
394 mkdir -p "$NNN_PREVIEWDIR/$3"
395 convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg" ||
396 MAGICK_TMPDIR="/tmp" convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg"
398 frames=$(($(find "$NNN_PREVIEWDIR/$3" | wc -l) - 2))
399 [ $frames -lt 0 ] && return
401 for i in $(seq 0 $frames); do
402 image_preview "$1" "$2" "$frameprefix-$i.jpg"
406 printf "%s" "$!" > "$PREVIEWPID"
408 elif [ -n "$NNN_PREVIEWVIDEO" ]; then
409 video_preview "$1" "$2" "$3" && return
411 image_preview "$1" "$2" "$3" && return
413 image) if exists convert; then
414 convert "$3" -flatten -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$NNN_PREVIEWDIR/$3.jpg"
416 image_preview "$1" "$2" "$3" && return
418 office) libreoffice --convert-to jpg "$3" --outdir "$NNN_PREVIEWDIR/${3%/*}"
419 filename="$(printf "%s" "${3##*/}" | cut -d. -f1)"
420 mv "$NNN_PREVIEWDIR/${3%/*}/$filename.jpg" "$NNN_PREVIEWDIR/$3.jpg" ;;
421 pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$NNN_PREVIEWDIR/$3" ;;
422 djvu) ddjvu -format=ppm -page=1 "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
423 video) video_preview "$1" "$2" "$3" && return ;;
426 if [ -f "$NNN_PREVIEWDIR/$3.jpg" ]; then
427 image_preview "$1" "$2" "$NNN_PREVIEWDIR/$3.jpg"
429 fifo_pager print_bin_info "$3"
436 if [ "$NNN_TERMINAL" = "kitty" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|icat) ]]; then
437 kitty +kitten icat --silent --scale-up --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no "$3" &
438 elif [ "$NNN_TERMINAL" = "wezterm" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|imgcat) ]]; then
439 wezterm imgcat "$3" &
440 elif exists ueberzug && [[ "$NNN_PREVIEWIMGPROG" == +(|ueberzug) ]]; then
441 ueberzug_layer "$1" "$2" "$3" && return
442 elif exists catimg && [[ "$NNN_PREVIEWIMGPROG" == +(|catimg) ]]; then
444 elif exists viu && [[ "$NNN_PREVIEWIMGPROG" == +(|viu) ]]; then
446 elif exists chafa && [[ "$NNN_PREVIEWIMGPROG" == +(|chafa) ]]; then
448 elif exists img2sixel && [[ "$NNN_PREVIEWIMGPROG" == +(|img2sixel) ]]; then
451 fifo_pager print_bin_info "$3" && return
453 printf "%s" "$!" > "$PREVIEWPID"
459 if [ -n "$NNN_PREVIEWVIDEO" ]; then
460 mpv --no-config --really-quiet --vo="$NNN_PREVIEWVIDEO" --profile=sw-fast --loop-file --no-audio "$4" "$3" &
462 ffmpegthumbnailer -m -s0 -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" || rm "$NNN_PREVIEWDIR/$3.jpg" &
464 printf "%s" "$!" > "$PREVIEWPID"
468 [ -f "$POSOFFSET" ] && read -r x y < "$POSOFFSET"
469 printf '{"action": "add", "identifier": "nnn_ueberzug", "x": %d, "y": %d, "width": "%d", "height": "%d", "scaler": "fit_contain", "path": "%s"}\n'\
470 "${x:-0}" "${y:-0}" "$1" "$2" "$3" > "$FIFO_UEBERZUG"
474 printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
479 pidkill "$PREVIEWPID"
480 if [ -p "$FIFO_UEBERZUG" ]; then
481 pkill -f "tail --follow $FIFO_UEBERZUG"
482 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
484 preview_file "$(cat "$CURSEL")"
488 while read -r selection; do
489 if [ -n "$selection" ]; then
490 pidkill "$PREVIEWPID"
491 [ -p "$FIFO_UEBERZUG" ] && ueberzug_remove
492 [ "$selection" = "close" ] && break
493 preview_file "$selection"
494 printf "%s" "$selection" > "$CURSEL"
497 sleep 0.1 # make sure potential preview by winch_handler is killed
501 if [ "$PREVIEW_MODE" -eq 1 ] 2>/dev/null; then
502 if exists ueberzug && [ "$NNN_TERMINAL" != "kitty" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|ueberzug) ]]; then
503 mkfifo "$FIFO_UEBERZUG"
504 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
507 preview_file "$PWD/$1"
508 preview_fifo & WAITPID=$!
509 printf "%s" "$!" > "$FIFOPID"
510 printf "%s" "$PWD/$1" > "$CURSEL"
511 trap 'winch_handler' WINCH
512 trap 'rm "$PREVIEWPID" "$CURSEL" "$FIFO_UEBERZUG" "$FIFOPID" "$POSOFFSET" 2>/dev/null' INT HUP EXIT
513 while kill -s 0 $WAITPID; do
514 wait $WAITPID 2>/dev/null
518 if [ ! -r "$NNN_FIFO" ]; then
519 prompt "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')\nPlease read Usage in '$0'."
520 elif [ "$KITTY_WINDOW_ID" ] && [ -z "$TMUX" ] && [ -z "$KITTY_LISTEN_ON" ]; then
521 prompt "\$KITTY_LISTEN_ON not set!\nPlease read Usage in '$0'."
523 toggle_preview "$1" &