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, viu, catimg or chafa for images
25 # - optional: convert(ImageMagick) for playing gif preview (required for kitty image previews)
26 # - optional: ffmpegthumbnailer for video thumbnails (https://github.com/dirkvdb/ffmpegthumbnailer)
27 # - optional: ffmpeg for audio thumbnails
28 # - optional: libreoffce for opendocument/officedocument preview
29 # - optional: pdftoppm(poppler) for pdf thumbnails
30 # - optional: gnome-epub-thumbnailer for epub thumbnails (https://gitlab.gnome.org/GNOME/gnome-epub-thumbnailer)
31 # - optional: fontpreview for font preview (https://github.com/sdushantha/fontpreview)
32 # - optional: djvulibre for djvu
33 # - optional: glow or lowdown for markdown
34 # - optional: w3m or lynx or elinks for html
35 # - optional: set/export NNN_ICONLOOKUP as 1 to enable file icons in front of directory previews with .iconlookup
36 # Icons and colors are configurable in .iconlookup
37 # - optional: scope.sh file viewer from ranger.
38 # 1. drop scope.sh executable in $PATH
39 # 2. set/export $NNN_SCOPE as 1
40 # - optional: pistol file viewer (https://github.com/doronbehar/pistol).
42 # 2. set/export $NNN_PISTOL as 1
44 # - terminal with sixel support. ex. foot, wezterm, iterm2, macterm, mintty, etc. (check https://www.arewesixelyet.com/)
45 # - tmux with sixel support (should be compiled with `./configure --enable-sixel`)
46 # dependencies: mpv, img2sixel
50 # You need to set a NNN_FIFO path and a key for the plugin with NNN_PLUG,
57 # $ NNN_FIFO=/tmp/nnn.fifo nnn
59 # Then launch the `preview-tui` plugin in `nnn`.
61 # If you provide the same NNN_FIFO to all nnn instances, there will be a
62 # single common preview window. If you provide different FIFO path (e.g.
63 # with -a), they will be independent.
65 # The previews will be shown in a tmux split. If that isn't possible, it
66 # will try to use a kitty terminal split. And as a final fallback, a
67 # different terminal window will be used ($NNN_TERMINAL).
69 # Kitty users need something similar to the following in their kitty.conf:
70 # - `allow_remote_control yes`
71 # - `listen_on unix:$TMPDIR/kitty`
72 # - `enabled_layouts splits` (optional)
73 # With ImageMagick installed, this terminal can use the icat kitten to display images.
74 # Refer to kitty documentation for further details.
76 # Wezterm should work out of the box. If `NNN_PREVIEWIMGPROG` is not specified it will use
77 # built in iTerm2 image protocol.
79 # Note that GNU ls is used for its `--group-directories-first` flag.
80 # On MacOS this may be installed with `brew install coreutils`, or the flag can be removed.
81 # iTerm2 users are recommended to use viu to view images without getting pixelated.
83 # Windows Terminal users can set "Profile termination behavior" under "Profile > Advanced" settings
84 # to automatically close pane on quit when exit code is 0.
86 # When specifying a different terminal, additional arguments are supported. In particular, you can
87 # append a specific title to the terminal and set it to "nofocus" in your WM config.
88 # E.g for alacritty and i3, you can set $NNN_TERMINAL to 'alacritty --title preview-tui' and add
89 # 'no_focus [title="preview-tui"]' to your i3 config file.
91 # Shell: Bash (for environment manipulation through arrays)
92 # Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal, @WanderLanz
94 NNN_SPLIT=${NNN_SPLIT:-} # Set permanent split direction
95 NNN_TERMINAL=${NNN_TERMINAL:-} # Set external terminal to be used
96 NNN_SPLITSIZE=${NNN_SPLITSIZE:-50} # Set previewer split size percentage
97 TMPDIR=${TMPDIR:-/tmp}
98 NNN_PARENT=${NNN_FIFO#*.}
99 [ "$NNN_PARENT" -eq "$NNN_PARENT" ] 2>/dev/null || NNN_PARENT="" # Make empty if non-numeric
104 "NNN_SCOPE=${NNN_SCOPE:-0}"
105 "NNN_PISTOL=${NNN_PISTOL:-0}"
106 "NNN_ICONLOOKUP=${NNN_ICONLOOKUP:-0}"
107 "NNN_PAGER=${NNN_PAGER:-less -P?n -R -C}"
108 "NNN_BATTHEME=${NNN_BATTHEME:-ansi}"
109 "NNN_BATSTYLE=${NNN_BATSTYLE:-numbers}"
110 "NNN_PREVIEWWIDTH=${NNN_PREVIEWWIDTH:-1920}"
111 "NNN_PREVIEWHEIGHT=${NNN_PREVIEWHEIGHT:-1080}"
112 "NNN_PREVIEWDIR=${NNN_PREVIEWDIR:-$TMPDIR/nnn/previews}"
113 "NNN_PREVIEWIMGPROG=${NNN_PREVIEWIMGPROG:-}"
114 "FIFOPID=$TMPDIR/nnn-preview-tui-fifopid.$NNN_PARENT"
115 "FIFOPATH=$TMPDIR/nnn-preview-tui-fifo.$NNN_PARENT"
116 "PREVIEWPID=$TMPDIR/nnn-preview-tui-previewpid.$NNN_PARENT"
117 "CURSEL=$TMPDIR/nnn-preview-tui-selection.$NNN_PARENT"
118 "FIFO_UEBERZUG=$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NNN_PARENT"
119 "POSOFFSET=$TMPDIR/nnn-preview-tui-posoffset"
123 exists() { type "$1" >/dev/null 2>&1 ;}
124 pkill() { command pkill "$@" >/dev/null 2>&1 ;}
125 prompt() { clear; printf "%b" "$@"; cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg" ;}
128 PID="$(cat "$1" 2>/dev/null)" || return 1
129 kill "$PID" >/dev/null 2>&1
131 wait "$PID" 2>/dev/null
138 if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
140 elif [ -n "$KITTY_LISTEN_ON" ]; then
142 elif [ -n "$WEZTERM_PANE" ]; then
144 elif [ -z "$NNN_TERMINAL" ] && [ "$TERM_PROGRAM" = "iTerm.app" ]; then
146 elif [ -n "$WT_SESSION" ]; then
149 NNN_TERMINAL="${NNN_TERMINAL:-xterm}"
152 if [ -z "$NNN_SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
154 elif [ "$NNN_SPLIT" != 'h' ]; then
158 ENVVARS+=("NNN_TERMINAL=$NNN_TERMINAL" "NNN_SPLIT=$NNN_SPLIT" "QLPATH=$2" "PREVIEW_MODE=1")
159 case "$NNN_TERMINAL" in
160 iterm|winterm) # need run in separate shell command: escape
161 ENVVARS=("${ENVVARS[@]/#/\\\"}")
162 ENVVARS=("${ENVVARS[@]/%/\\\"}")
163 command="$SHELL -c 'env ${ENVVARS[*]} \\\"$0\\\" \\\"$1\\\"'" ;;
166 case "$NNN_TERMINAL" in
167 tmux) # tmux splits are inverted
168 ENVVARS=("${ENVVARS[@]/#/-e}")
169 if [ "$NNN_SPLIT" = "v" ]; then split="h"; else split="v"; fi
170 tmux split-window -l"$NNN_SPLITSIZE"% "${ENVVARS[@]}" -d"$split" -p"$NNN_SPLITSIZE" "$0" "$1" ;;
171 kitty) # Setting the layout for the new window. It will be restored after the script ends.
172 ENVVARS=("${ENVVARS[@]/#/--env=}")
173 kitty @ goto-layout splits
174 # Trying to use kitty's integrated window management as the split window.
175 kitty @ launch --no-response --title "preview-tui" --keep-focus \
176 --cwd "$PWD" "${ENVVARS[@]}" --location "${NNN_SPLIT}split" "$0" "$1" ;;
178 export "${ENVVARS[@]}"
179 if [ "$NNN_SPLIT" = "v" ]; then split="--horizontal"; else split="--bottom"; fi
180 wezterm cli split-pane --cwd "$PWD" $split --percent "$NNN_SPLITSIZE" "$0" "$1" >/dev/null
181 wezterm cli activate-pane-direction Prev ;;
183 if [ "$NNN_SPLIT" = "h" ]; then split="horizontally"; else split="vertically"; fi
185 tell application "iTerm"
186 tell current session of current window
187 split $split with default profile command "$command"
193 if [ "$NNN_SPLIT" = "h" ]; then split="H"; else split="V"; fi
194 wt -w 0 sp -$split -s"0.$NNN_SPLITSIZE" "$command" \; -w 0 mf previous 2>/dev/null ;;
195 *) if [ -n "$2" ]; then
196 env "${ENVVARS[@]}" QUICKLOOK=1 "$0" "$1" &
198 # shellcheck disable=SC2086 # (allow arguments)
199 env "${ENVVARS[@]}" $NNN_TERMINAL -e "$0" "$1" &
205 export "${ENVVARS[@]}"
206 if exists QuickLook.exe; then
207 QLPATH="QuickLook.exe"
208 elif exists Bridge.exe; then
211 if pidkill "$FIFOPID"; then
212 [ -p "$NNN_PPIPE" ] && printf "0" > "$NNN_PPIPE"
213 pidkill "$PREVIEWPID"
214 pkill -f "tail --follow $FIFO_UEBERZUG"
215 if [ -n "$QLPATH" ] && stat "$1"; then
216 f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
219 [ -p "$NNN_PPIPE" ] && printf "1" > "$NNN_PPIPE"
220 start_preview "$1" "$QLPATH"
228 # We use a FIFO to access $NNN_PAGER PID in jobs control
229 mkfifo "$FIFOPATH" || return
231 $NNN_PAGER < "$FIFOPATH" &
232 printf "%s" "$!" > "$PREVIEWPID"
236 if [ "$cmd" = "pager" ]; then
238 bat --terminal-width="$cols" --decorations=always --color=always \
239 --paging=never --style="$NNN_BATSTYLE" --theme="$NNN_BATTHEME" "$@" &
251 # Binary file: show file info inside the pager
253 printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
254 if exists mediainfo; then
263 image/jpeg) image_preview "$cols" "$lines" "$1" ;;
264 image/gif) generate_preview "$cols" "$lines" "$1" "gif" ;;
265 image/vnd.djvu) generate_preview "$cols" "$lines" "$1" "djvu" ;;
266 image/*) generate_preview "$cols" "$lines" "$1" "image" ;;
267 video/*) generate_preview "$cols" "$lines" "$1" "video" ;;
268 audio/*) generate_preview "$cols" "$lines" "$1" "audio" ;;
269 application/font*|application/*opentype|font/*) generate_preview "$cols" "$lines" "$1" "font" ;;
270 */*office*|*/*document*|*/*msword|*/*ms-excel) generate_preview "$cols" "$lines" "$1" "office" ;;
271 application/zip) fifo_pager unzip -l "$1" ;;
274 fifo_pager man -Pcat -l "$1"
276 fifo_pager pager "$1"
278 *) handle_ext "$1" "$3" "$4" ;;
284 epub) generate_preview "$cols" "$lines" "$1" "epub" ;;
285 pdf) generate_preview "$cols" "$lines" "$1" "pdf" ;;
286 gz|bz2) fifo_pager tar -tvf "$1" ;;
287 md) if exists glow; then
288 fifo_pager glow -s dark "$1"
289 elif exists lowdown; then
290 fifo_pager lowdown -Tterm "$1"
292 fifo_pager pager "$1"
297 elif exists lynx; then
299 elif exists elinks; then
300 fifo_pager elinks "$1"
302 fifo_pager pager "$1"
304 7z|a|ace|alz|arc|arj|bz|cab|cpio|deb|jar|lha|lz|lzh|lzma|lzo\
305 |rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z)
306 if exists atool; then
307 fifo_pager atool -l "$1"
308 elif exists bsdtar; then
309 fifo_pager bsdtar -tvf "$1"
311 *) if [ "$3" = "bin" ]; then
312 fifo_pager print_bin_info "$1"
314 fifo_pager pager "$1"
321 # Trying to use pistol if it's available.
322 if [ "$NNN_PISTOL" -ne 0 ] && exists pistol; then
323 fifo_pager pistol "$1"
327 # Trying to use scope.sh if it's available.
328 if [ "$NNN_SCOPE" -ne 0 ] && exists scope.sh; then
329 fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" "True"
333 # Use QuickLook if it's available.
334 if [ -n "$QUICKLOOK" ]; then
335 stat "$1" && f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
339 # Detecting the exact type of the file: the encoding, mime type, and extension in lowercase.
340 encoding="$(file -bL --mime-encoding -- "$1")"
341 mimetype="$(file -bL --mime-type -- "$1")"
343 [ -n "$ext" ] && ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
347 # Otherwise, falling back to the defaults.
350 if [ "$NNN_ICONLOOKUP" -ne 0 ] && [ -f "$(dirname "$0")"/.iconlookup ]; then
351 [ "$NNN_SPLIT" = v ] && BSTR="\n"
352 # shellcheck disable=SC2012
353 ls -F --group-directories-first | head -n "$((lines - 3))" | "$(dirname "$0")"/.iconlookup -l "$cols" -B "$BSTR" -b " "
354 elif exists tree; then
355 fifo_pager tree --filelimit "$(find . -maxdepth 1 | wc -l)" -L 3 -C -F --dirsfirst --noreport
356 elif exists exa; then
357 exa -G --group-directories-first --colour=always
358 elif exists eza; then # eza is a community fork of exa (exa is unmaintained)
359 eza -G --group-directories-first --colour=always
361 fifo_pager ls -F --group-directories-first --color=always
364 elif [ "${encoding#*)}" = "binary" ]; then
365 handle_mime "$1" "$mimetype" "$ext" "bin"
367 handle_mime "$1" "$mimetype" "$ext"
372 if [ -n "$QLPATH" ] && stat "$3"; then
373 f="$(wslpath -w "$3")" && "$QLPATH" "$f" &
374 elif [ ! -f "$NNN_PREVIEWDIR/$3.jpg" ] || [ -n "$(find -L "$3" -newer "$NNN_PREVIEWDIR/$3.jpg")" ]; then
375 mkdir -p "$NNN_PREVIEWDIR/${3%/*}"
377 audio) ffmpeg -i "$3" -filter_complex "scale=iw*min(1\,min($NNN_PREVIEWWIDTH/iw\,ih)):-1" "$NNN_PREVIEWDIR/$3.jpg" -y ;;
378 epub) gnome-epub-thumbnailer "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
379 font) fontpreview -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" ;;
380 gif) if [ -p "$FIFO_UEBERZUG" ] && exists convert; then
381 frameprefix="$NNN_PREVIEWDIR/$3/${3##*/}"
382 if [ ! -d "$NNN_PREVIEWDIR/$3" ]; then
383 mkdir -p "$NNN_PREVIEWDIR/$3"
384 convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg" ||
385 MAGICK_TMPDIR="/tmp" convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg"
387 frames=$(($(find "$NNN_PREVIEWDIR/$3" | wc -l) - 2))
388 [ $frames -lt 0 ] && return
390 for i in $(seq 0 $frames); do
391 image_preview "$1" "$2" "$frameprefix-$i.jpg"
395 printf "%s" "$!" > "$PREVIEWPID"
397 elif exists mpv; then
398 video_preview "$1" "$2" "$3" 1
401 image_preview "$1" "$2" "$3"
404 image) if exists convert; then
405 convert "$3" -flatten -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$NNN_PREVIEWDIR/$3.jpg"
407 image_preview "$1" "$2" "$3" && return
409 office) libreoffice --convert-to jpg "$3" --outdir "$NNN_PREVIEWDIR/${3%/*}"
410 filename="$(printf "%s" "${3##*/}" | cut -d. -f1)"
411 mv "$NNN_PREVIEWDIR/${3%/*}/$filename.jpg" "$NNN_PREVIEWDIR/$3.jpg" ;;
412 pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$NNN_PREVIEWDIR/$3" ;;
413 djvu) ddjvu -format=ppm -page=1 "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
414 video) video_preview "$1" "$2" "$3" && return ;;
417 if [ -f "$NNN_PREVIEWDIR/$3.jpg" ]; then
418 image_preview "$1" "$2" "$NNN_PREVIEWDIR/$3.jpg"
420 fifo_pager print_bin_info "$3"
427 if [ "$NNN_TERMINAL" = "kitty" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
428 kitty +kitten icat --silent --scale-up --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no "$3" &
429 elif [ "$NNN_TERMINAL" = "wezterm" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
430 wezterm imgcat "$3" &
431 elif exists ueberzug && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "ueberzug" ] ;}; then
432 ueberzug_layer "$1" "$2" "$3" && return
433 elif exists catimg && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "catimg" ] ;}; then
435 elif exists viu && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "viu" ] ;}; then
437 elif exists chafa && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "chafa" ] ;}; then
439 elif exists img2sixel && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "img2sixel" ] ;}; then
440 img2sixel -p16 -g "$3" &
442 fifo_pager print_bin_info "$3" && return
444 printf "%s" "$!" > "$PREVIEWPID"
450 if type mpv >/dev/null 2>&1 ; then
451 if [ "$4" -eq 1 ]; then # not gif
452 mpv --no-config --really-quiet --vo=sixel --profile=sw-fast --loop-file --mute=yes --start="10%" --length=4 "$3" &
454 mpv --no-config --really-quiet --vo=sixel --profile=sw-fast --loop-file --mute=yes "$3" &
457 ffmpegthumbnailer -m -s0 -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" || rm "$NNN_PREVIEWDIR/$3.jpg" &
459 printf "%s" "$!" > "$PREVIEWPID"
463 [ -f "$POSOFFSET" ] && read -r x y < "$POSOFFSET"
464 printf '{"action": "add", "identifier": "nnn_ueberzug", "x": %d, "y": %d, "width": "%d", "height": "%d", "scaler": "fit_contain", "path": "%s"}\n'\
465 "${x:-0}" "${y:-0}" "$1" "$2" "$3" > "$FIFO_UEBERZUG"
469 printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
474 pidkill "$PREVIEWPID"
475 if [ -p "$FIFO_UEBERZUG" ]; then
476 pkill -f "tail --follow $FIFO_UEBERZUG"
477 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
479 preview_file "$(cat "$CURSEL")"
483 while read -r selection; do
484 if [ -n "$selection" ]; then
485 pidkill "$PREVIEWPID"
486 [ -p "$FIFO_UEBERZUG" ] && ueberzug_remove
487 [ "$selection" = "close" ] && break
488 preview_file "$selection"
489 printf "%s" "$selection" > "$CURSEL"
492 sleep 0.1 # make sure potential preview by winch_handler is killed
496 if [ "$PREVIEW_MODE" -eq 1 ] 2>/dev/null; then
497 if [ "$NNN_TERMINAL" != "kitty" ] && exists ueberzug; then
498 mkfifo "$FIFO_UEBERZUG"
499 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
502 preview_file "$PWD/$1"
503 preview_fifo & WAITPID=$!
504 printf "%s" "$!" > "$FIFOPID"
505 printf "%s" "$PWD/$1" > "$CURSEL"
506 trap 'winch_handler' WINCH
507 trap 'rm "$PREVIEWPID" "$CURSEL" "$FIFO_UEBERZUG" "$FIFOPID" "$POSOFFSET" 2>/dev/null' INT HUP EXIT
508 while kill -s 0 $WAITPID; do
509 wait $WAITPID 2>/dev/null
513 if [ ! -r "$NNN_FIFO" ]; then
514 prompt "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')\nPlease read Usage in '$0'."
515 elif [ "$KITTY_WINDOW_ID" ] && [ -z "$TMUX" ] && [ -z "$KITTY_LISTEN_ON" ]; then
516 prompt "\$KITTY_LISTEN_ON not set!\nPlease read Usage in '$0'."
518 toggle_preview "$1" &