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 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
45 # You need to set a NNN_FIFO path and a key for the plugin with NNN_PLUG,
52 # $ NNN_FIFO=/tmp/nnn.fifo nnn
54 # Then launch the `preview-tui` plugin in `nnn`.
56 # If you provide the same NNN_FIFO to all nnn instances, there will be a
57 # single common preview window. If you provide different FIFO path (e.g.
58 # with -a), they will be independent.
60 # The previews will be shown in a tmux split. If that isn't possible, it
61 # will try to use a kitty terminal split. And as a final fallback, a
62 # different terminal window will be used ($NNN_TERMINAL).
64 # Kitty users need something similar to the following in their kitty.conf:
65 # - `allow_remote_control yes`
66 # - `listen_on unix:$TMPDIR/kitty`
67 # - `enabled_layouts splits` (optional)
68 # With ImageMagick installed, this terminal can use the icat kitten to display images.
69 # Refer to kitty documentation for further details.
71 # Wezterm should work out of the box. If `NNN_PREVIEWIMGPROG` is not specified it will use
72 # built in iTerm2 image protocol.
74 # Note that GNU ls is used for its `--group-directories-first` flag.
75 # On MacOS this may be installed with `brew install coreutils`, or the flag can be removed.
76 # iTerm2 users are recommended to use viu to view images without getting pixelated.
78 # Windows Terminal users can set "Profile termination behavior" under "Profile > Advanced" settings
79 # to automatically close pane on quit when exit code is 0.
81 # Shell: Bash (for environment manipulation through arrays)
82 # Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal, @WanderLanz
84 NNN_SPLIT=${NNN_SPLIT:-} # Set permanent split direction
85 NNN_TERMINAL=${NNN_TERMINAL:-} # Set external terminal to be used
86 NNN_SPLITSIZE=${NNN_SPLITSIZE:-50} # Set previewer split size percentage
87 TMPDIR=${TMPDIR:-/tmp}
88 NNN_PARENT=${NNN_FIFO#*.}
89 [ "$NNN_PARENT" -eq "$NNN_PARENT" ] 2>/dev/null || NNN_PARENT="" # Make empty if non-numeric
94 "NNN_SCOPE=${NNN_SCOPE:-0}"
95 "NNN_PISTOL=${NNN_PISTOL:-0}"
96 "NNN_ICONLOOKUP=${NNN_ICONLOOKUP:-0}"
97 "NNN_PAGER=${NNN_PAGER:-less -P?n -R}"
98 "NNN_BATTHEME=${NNN_BATTHEME:-ansi}"
99 "NNN_BATSTYLE=${NNN_BATSTYLE:-numbers}"
100 "NNN_PREVIEWWIDTH=${NNN_PREVIEWWIDTH:-1920}"
101 "NNN_PREVIEWHEIGHT=${NNN_PREVIEWHEIGHT:-1080}"
102 "NNN_PREVIEWDIR=${NNN_PREVIEWDIR:-$TMPDIR/nnn/previews}"
103 "NNN_PREVIEWIMGPROG=${NNN_PREVIEWIMGPROG:-}"
104 "FIFOPID=$TMPDIR/nnn-preview-tui-fifopid.$NNN_PARENT"
105 "FIFOPATH=$TMPDIR/nnn-preview-tui-fifo.$NNN_PARENT"
106 "PREVIEWPID=$TMPDIR/nnn-preview-tui-previewpid.$NNN_PARENT"
107 "CURSEL=$TMPDIR/nnn-preview-tui-selection.$NNN_PARENT"
108 "FIFO_UEBERZUG=$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NNN_PARENT"
109 "POSOFFSET=$TMPDIR/nnn-preview-tui-posoffset"
113 exists() { type "$1" >/dev/null 2>&1 ;}
114 pkill() { command pkill "$@" >/dev/null 2>&1 ;}
115 prompt() { clear; printf "%b" "$@"; cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg" ;}
118 PID="$(cat "$1" 2>/dev/null)" || return 1
119 kill "$PID" >/dev/null 2>&1
121 wait "$PID" 2>/dev/null
128 if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
130 elif [ -n "$KITTY_LISTEN_ON" ]; then
132 elif [ -n "$WEZTERM_PANE" ]; then
134 elif [ -z "$NNN_TERMINAL" ] && [ "$TERM_PROGRAM" = "iTerm.app" ]; then
136 elif [ -n "$WT_SESSION" ]; then
139 NNN_TERMINAL="${NNN_TERMINAL:-xterm}"
142 if [ -z "$NNN_SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
144 elif [ "$NNN_SPLIT" != 'h' ]; then
148 ENVVARS+=("NNN_TERMINAL=$NNN_TERMINAL" "NNN_SPLIT=$NNN_SPLIT" "QLPATH=$2" "PREVIEW_MODE=1")
149 case "$NNN_TERMINAL" in
150 iterm|winterm) # need run in separate shell command: escape
151 ENVVARS=("${ENVVARS[@]/#/\\\"}")
152 ENVVARS=("${ENVVARS[@]/%/\\\"}")
153 command="$SHELL -c 'env ${ENVVARS[*]} \\\"$0\\\" \\\"$1\\\"'" ;;
156 case "$NNN_TERMINAL" in
157 tmux) # tmux splits are inverted
158 ENVVARS=("${ENVVARS[@]/#/-e}")
159 if [ "$NNN_SPLIT" = "v" ]; then split="h"; else split="v"; fi
160 tmux split-window "${ENVVARS[@]}" -d"$split" -p"$NNN_SPLITSIZE" "$0" "$1" ;;
161 kitty) # Setting the layout for the new window. It will be restored after the script ends.
162 ENVVARS=("${ENVVARS[@]/#/--env=}")
163 kitty @ goto-layout splits
164 # Trying to use kitty's integrated window management as the split window.
165 kitty @ launch --no-response --title "preview-tui" --keep-focus \
166 --cwd "$PWD" "${ENVVARS[@]}" --location "${NNN_SPLIT}split" "$0" "$1" ;;
168 export "${ENVVARS[@]}"
169 if [ "$NNN_SPLIT" = "v" ]; then split="--horizontal"; else split="--bottom"; fi
170 wezterm cli split-pane --cwd "$PWD" $split --percent "$NNN_SPLITSIZE" "$0" "$1" >/dev/null
171 wezterm cli activate-pane-direction Prev ;;
173 if [ "$NNN_SPLIT" = "h" ]; then split="horizontally"; else split="vertically"; fi
175 tell application "iTerm"
176 tell current session of current window
177 split $split with default profile command "$command"
183 if [ "$NNN_SPLIT" = "h" ]; then split="H"; else split="V"; fi
184 wt -w 0 sp -$split -s"0.$NNN_SPLITSIZE" "$command" \; -w 0 mf previous 2>/dev/null ;;
185 *) if [ -n "$2" ]; then
186 env "${ENVVARS[@]}" QUICKLOOK=1 "$0" "$1" &
188 env "${ENVVARS[@]}" "$NNN_TERMINAL" -e "$0" "$1" &
194 export "${ENVVARS[@]}"
195 if exists QuickLook.exe; then
196 QLPATH="QuickLook.exe"
197 elif exists Bridge.exe; then
200 if pidkill "$FIFOPID"; then
201 [ -p "$NNN_PPIPE" ] && printf "0" > "$NNN_PPIPE"
202 pidkill "$PREVIEWPID"
203 pkill -f "tail --follow $FIFO_UEBERZUG"
204 if [ -n "$QLPATH" ] && stat "$1"; then
205 f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
208 [ -p "$NNN_PPIPE" ] && printf "1" > "$NNN_PPIPE"
209 start_preview "$1" "$QLPATH"
217 # We use a FIFO to access $NNN_PAGER PID in jobs control
218 mkfifo "$FIFOPATH" || return
220 $NNN_PAGER < "$FIFOPATH" &
221 printf "%s" "$!" > "$PREVIEWPID"
225 if [ "$cmd" = "pager" ]; then
227 bat --terminal-width="$cols" --decorations=always --color=always \
228 --paging=never --style="$NNN_BATSTYLE" --theme="$NNN_BATTHEME" "$@" &
240 # Binary file: show file info inside the pager
242 printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
243 if exists mediainfo; then
252 image/jpeg) image_preview "$cols" "$lines" "$1" ;;
253 image/gif) generate_preview "$cols" "$lines" "$1" "gif" ;;
254 image/vnd.djvu) generate_preview "$cols" "$lines" "$1" "djvu" ;;
255 image/*) generate_preview "$cols" "$lines" "$1" "image" ;;
256 video/*) generate_preview "$cols" "$lines" "$1" "video" ;;
257 audio/*) generate_preview "$cols" "$lines" "$1" "audio" ;;
258 application/font*|application/*opentype|font/*) generate_preview "$cols" "$lines" "$1" "font" ;;
259 */*office*|*/*document*|*/*msword|*/*ms-excel) generate_preview "$cols" "$lines" "$1" "office" ;;
260 application/zip) fifo_pager unzip -l "$1" ;;
263 fifo_pager man -Pcat -l "$1"
265 fifo_pager pager "$1"
267 *) handle_ext "$1" "$3" "$4" ;;
273 epub) generate_preview "$cols" "$lines" "$1" "epub" ;;
274 pdf) generate_preview "$cols" "$lines" "$1" "pdf" ;;
275 gz|bz2) fifo_pager tar -tvf "$1" ;;
276 md) if exists glow; then
277 fifo_pager glow -s dark "$1"
278 elif exists lowdown; then
279 fifo_pager lowdown -Tterm "$1"
281 fifo_pager pager "$1"
286 elif exists lynx; then
288 elif exists elinks; then
289 fifo_pager elinks "$1"
291 fifo_pager pager "$1"
293 7z|a|ace|alz|arc|arj|bz|cab|cpio|deb|jar|lha|lz|lzh|lzma|lzo\
294 |rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z)
295 if exists atool; then
296 fifo_pager atool -l "$1"
297 elif exists bsdtar; then
298 fifo_pager bsdtar -tvf "$1"
300 *) if [ "$3" = "bin" ]; then
301 fifo_pager print_bin_info "$1"
303 fifo_pager pager "$1"
310 # Trying to use pistol if it's available.
311 if [ "$NNN_PISTOL" -ne 0 ] && exists pistol; then
312 fifo_pager pistol "$1"
316 # Trying to use scope.sh if it's available.
317 if [ "$NNN_SCOPE" -ne 0 ] && exists scope.sh; then
318 fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" "True"
322 # Use QuickLook if it's available.
323 if [ -n "$QUICKLOOK" ]; then
324 stat "$1" && f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
328 # Detecting the exact type of the file: the encoding, mime type, and extension in lowercase.
329 encoding="$(file -bL --mime-encoding -- "$1")"
330 mimetype="$(file -bL --mime-type -- "$1")"
332 [ -n "$ext" ] && ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
336 # Otherwise, falling back to the defaults.
339 if [ "$NNN_ICONLOOKUP" -ne 0 ] && [ -f "$(dirname "$0")"/.iconlookup ]; then
340 [ "$NNN_SPLIT" = v ] && BSTR="\n"
341 # shellcheck disable=SC2012
342 ls -F --group-directories-first | head -n "$((lines - 3))" | "$(dirname "$0")"/.iconlookup -l "$cols" -B "$BSTR" -b " "
343 elif exists tree; then
344 fifo_pager tree --filelimit "$(find . -maxdepth 1 | wc -l)" -L 3 -C -F --dirsfirst --noreport
345 elif exists exa; then
346 exa -G --group-directories-first --colour=always
348 fifo_pager ls -F --group-directories-first --color=always
351 elif [ "${encoding#*)}" = "binary" ]; then
352 handle_mime "$1" "$mimetype" "$ext" "bin"
354 handle_mime "$1" "$mimetype" "$ext"
359 if [ -n "$QLPATH" ] && stat "$3"; then
360 f="$(wslpath -w "$3")" && "$QLPATH" "$f" &
361 elif [ ! -f "$NNN_PREVIEWDIR/$3.jpg" ] || [ -n "$(find -L "$3" -newer "$NNN_PREVIEWDIR/$3.jpg")" ]; then
362 mkdir -p "$NNN_PREVIEWDIR/${3%/*}"
364 audio) ffmpeg -i "$3" -filter_complex "scale=iw*min(1\,min($NNN_PREVIEWWIDTH/iw\,ih)):-1" "$NNN_PREVIEWDIR/$3.jpg" -y ;;
365 epub) gnome-epub-thumbnailer "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
366 font) fontpreview -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" ;;
367 gif) if [ -p "$FIFO_UEBERZUG" ] && exists convert; then
368 frameprefix="$NNN_PREVIEWDIR/$3/${3##*/}"
369 if [ ! -d "$NNN_PREVIEWDIR/$3" ]; then
370 mkdir -p "$NNN_PREVIEWDIR/$3"
371 convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg" ||
372 MAGICK_TMPDIR="/tmp" convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg"
374 frames=$(($(find "$NNN_PREVIEWDIR/$3" | wc -l) - 2))
375 [ $frames -lt 0 ] && return
377 for i in $(seq 0 $frames); do
378 image_preview "$1" "$2" "$frameprefix-$i.jpg"
382 printf "%s" "$!" > "$PREVIEWPID"
385 image_preview "$1" "$2" "$3"
388 image) if exists convert; then
389 convert "$3" -flatten -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$NNN_PREVIEWDIR/$3.jpg"
391 image_preview "$1" "$2" "$3" && return
393 office) libreoffice --convert-to jpg "$3" --outdir "$NNN_PREVIEWDIR/${3%/*}"
394 filename="$(printf "%s" "${3##*/}" | cut -d. -f1)"
395 mv "$NNN_PREVIEWDIR/${3%/*}/$filename.jpg" "$NNN_PREVIEWDIR/$3.jpg" ;;
396 pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$NNN_PREVIEWDIR/$3" ;;
397 djvu) ddjvu -format=ppm -page=1 "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
398 video) ffmpegthumbnailer -m -s0 -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" || rm "$NNN_PREVIEWDIR/$3.jpg" ;;
401 if [ -f "$NNN_PREVIEWDIR/$3.jpg" ]; then
402 image_preview "$1" "$2" "$NNN_PREVIEWDIR/$3.jpg"
404 fifo_pager print_bin_info "$3"
411 if [ "$NNN_TERMINAL" = "kitty" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
412 kitty +kitten icat --silent --scale-up --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no "$3" &
413 elif [ "$NNN_TERMINAL" = "wezterm" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
414 wezterm imgcat "$3" &
415 elif exists ueberzug && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "ueberzug" ] ;}; then
416 ueberzug_layer "$1" "$2" "$3" && return
417 elif exists catimg && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "catimg" ] ;}; then
419 elif exists viu && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "viu" ] ;}; then
421 elif exists chafa && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "chafa" ] ;}; then
424 fifo_pager print_bin_info "$3" && return
426 printf "%s" "$!" > "$PREVIEWPID"
430 [ -f "$POSOFFSET" ] && read -r x y < "$POSOFFSET"
431 printf '{"action": "add", "identifier": "nnn_ueberzug", "x": %d, "y": %d, "width": "%d", "height": "%d", "scaler": "fit_contain", "path": "%s"}\n'\
432 "${x:-0}" "${y:-0}" "$1" "$2" "$3" > "$FIFO_UEBERZUG"
436 printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
441 pidkill "$PREVIEWPID"
442 if [ -p "$FIFO_UEBERZUG" ]; then
443 pkill -f "tail --follow $FIFO_UEBERZUG"
444 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
446 preview_file "$(cat "$CURSEL")"
450 while read -r selection; do
451 if [ -n "$selection" ]; then
452 pidkill "$PREVIEWPID"
453 [ -p "$FIFO_UEBERZUG" ] && ueberzug_remove
454 [ "$selection" = "close" ] && break
455 preview_file "$selection"
456 printf "%s" "$selection" > "$CURSEL"
459 sleep 0.1 # make sure potential preview by winch_handler is killed
463 if [ "$PREVIEW_MODE" -eq 1 ] 2>/dev/null; then
464 if [ "$NNN_TERMINAL" != "kitty" ] && exists ueberzug; then
465 mkfifo "$FIFO_UEBERZUG"
466 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
469 preview_file "$PWD/$1"
471 printf "%s" "$!" > "$FIFOPID"
472 printf "%s" "$PWD/$1" > "$CURSEL"
473 trap 'winch_handler; wait' WINCH
474 trap 'rm "$PREVIEWPID" "$CURSEL" "$FIFO_UEBERZUG" "$FIFOPID" "$POSOFFSET" 2>/dev/null' INT HUP EXIT
475 wait "$!" 2>/dev/null
478 if [ ! -r "$NNN_FIFO" ]; then
479 prompt "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')\nPlease read Usage in '$0'."
480 elif [ "$KITTY_WINDOW_ID" ] && [ -z "$TMUX" ] && [ -z "$KITTY_LISTEN_ON" ]; then
481 prompt "\$KITTY_LISTEN_ON not set!\nPlease read Usage in '$0'."
483 toggle_preview "$1" &