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
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 # When specifying a different terminal, additional arguments are supported. In particular, you can
82 # append a specific title to the terminal and set it to "nofocus" in your WM config.
83 # E.g for alacritty and i3, you can set $NNN_TERMINAL to 'alacritty --title preview-tui' and add
84 # 'no_focus [title="preview-tui"]' to your i3 config file.
86 # Shell: Bash (for environment manipulation through arrays)
87 # Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal, @WanderLanz
89 NNN_SPLIT=${NNN_SPLIT:-} # Set permanent split direction
90 NNN_TERMINAL=${NNN_TERMINAL:-} # Set external terminal to be used
91 NNN_SPLITSIZE=${NNN_SPLITSIZE:-50} # Set previewer split size percentage
92 TMPDIR=${TMPDIR:-/tmp}
93 NNN_PARENT=${NNN_FIFO#*.}
94 [ "$NNN_PARENT" -eq "$NNN_PARENT" ] 2>/dev/null || NNN_PARENT="" # Make empty if non-numeric
99 "NNN_SCOPE=${NNN_SCOPE:-0}"
100 "NNN_PISTOL=${NNN_PISTOL:-0}"
101 "NNN_ICONLOOKUP=${NNN_ICONLOOKUP:-0}"
102 "NNN_PAGER=${NNN_PAGER:-less -P?n -R -C}"
103 "NNN_BATTHEME=${NNN_BATTHEME:-ansi}"
104 "NNN_BATSTYLE=${NNN_BATSTYLE:-numbers}"
105 "NNN_PREVIEWWIDTH=${NNN_PREVIEWWIDTH:-1920}"
106 "NNN_PREVIEWHEIGHT=${NNN_PREVIEWHEIGHT:-1080}"
107 "NNN_PREVIEWDIR=${NNN_PREVIEWDIR:-$TMPDIR/nnn/previews}"
108 "NNN_PREVIEWIMGPROG=${NNN_PREVIEWIMGPROG:-}"
109 "FIFOPID=$TMPDIR/nnn-preview-tui-fifopid.$NNN_PARENT"
110 "FIFOPATH=$TMPDIR/nnn-preview-tui-fifo.$NNN_PARENT"
111 "PREVIEWPID=$TMPDIR/nnn-preview-tui-previewpid.$NNN_PARENT"
112 "CURSEL=$TMPDIR/nnn-preview-tui-selection.$NNN_PARENT"
113 "FIFO_UEBERZUG=$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NNN_PARENT"
114 "POSOFFSET=$TMPDIR/nnn-preview-tui-posoffset"
118 exists() { type "$1" >/dev/null 2>&1 ;}
119 pkill() { command pkill "$@" >/dev/null 2>&1 ;}
120 prompt() { clear; printf "%b" "$@"; cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg" ;}
123 PID="$(cat "$1" 2>/dev/null)" || return 1
124 kill "$PID" >/dev/null 2>&1
126 wait "$PID" 2>/dev/null
133 if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
135 elif [ -n "$KITTY_LISTEN_ON" ]; then
137 elif [ -n "$WEZTERM_PANE" ]; then
139 elif [ -z "$NNN_TERMINAL" ] && [ "$TERM_PROGRAM" = "iTerm.app" ]; then
141 elif [ -n "$WT_SESSION" ]; then
144 NNN_TERMINAL="${NNN_TERMINAL:-xterm}"
147 if [ -z "$NNN_SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
149 elif [ "$NNN_SPLIT" != 'h' ]; then
153 ENVVARS+=("NNN_TERMINAL=$NNN_TERMINAL" "NNN_SPLIT=$NNN_SPLIT" "QLPATH=$2" "PREVIEW_MODE=1")
154 case "$NNN_TERMINAL" in
155 iterm|winterm) # need run in separate shell command: escape
156 ENVVARS=("${ENVVARS[@]/#/\\\"}")
157 ENVVARS=("${ENVVARS[@]/%/\\\"}")
158 command="$SHELL -c 'env ${ENVVARS[*]} \\\"$0\\\" \\\"$1\\\"'" ;;
161 case "$NNN_TERMINAL" in
162 tmux) # tmux splits are inverted
163 ENVVARS=("${ENVVARS[@]/#/-e}")
164 if [ "$NNN_SPLIT" = "v" ]; then split="h"; else split="v"; fi
165 tmux split-window "${ENVVARS[@]}" -d"$split" -p"$NNN_SPLITSIZE" "$0" "$1" ;;
166 kitty) # Setting the layout for the new window. It will be restored after the script ends.
167 ENVVARS=("${ENVVARS[@]/#/--env=}")
168 kitty @ goto-layout splits
169 # Trying to use kitty's integrated window management as the split window.
170 kitty @ launch --no-response --title "preview-tui" --keep-focus \
171 --cwd "$PWD" "${ENVVARS[@]}" --location "${NNN_SPLIT}split" "$0" "$1" ;;
173 export "${ENVVARS[@]}"
174 if [ "$NNN_SPLIT" = "v" ]; then split="--horizontal"; else split="--bottom"; fi
175 wezterm cli split-pane --cwd "$PWD" $split --percent "$NNN_SPLITSIZE" "$0" "$1" >/dev/null
176 wezterm cli activate-pane-direction Prev ;;
178 if [ "$NNN_SPLIT" = "h" ]; then split="horizontally"; else split="vertically"; fi
180 tell application "iTerm"
181 tell current session of current window
182 split $split with default profile command "$command"
188 if [ "$NNN_SPLIT" = "h" ]; then split="H"; else split="V"; fi
189 wt -w 0 sp -$split -s"0.$NNN_SPLITSIZE" "$command" \; -w 0 mf previous 2>/dev/null ;;
190 *) if [ -n "$2" ]; then
191 env "${ENVVARS[@]}" QUICKLOOK=1 "$0" "$1" &
193 # shellcheck disable=SC2086 # (allow arguments)
194 env "${ENVVARS[@]}" $NNN_TERMINAL -e "$0" "$1" &
200 export "${ENVVARS[@]}"
201 if exists QuickLook.exe; then
202 QLPATH="QuickLook.exe"
203 elif exists Bridge.exe; then
206 if pidkill "$FIFOPID"; then
207 [ -p "$NNN_PPIPE" ] && printf "0" > "$NNN_PPIPE"
208 pidkill "$PREVIEWPID"
209 pkill -f "tail --follow $FIFO_UEBERZUG"
210 if [ -n "$QLPATH" ] && stat "$1"; then
211 f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
214 [ -p "$NNN_PPIPE" ] && printf "1" > "$NNN_PPIPE"
215 start_preview "$1" "$QLPATH"
223 # We use a FIFO to access $NNN_PAGER PID in jobs control
224 mkfifo "$FIFOPATH" || return
226 $NNN_PAGER < "$FIFOPATH" &
227 printf "%s" "$!" > "$PREVIEWPID"
231 if [ "$cmd" = "pager" ]; then
233 bat --terminal-width="$cols" --decorations=always --color=always \
234 --paging=never --style="$NNN_BATSTYLE" --theme="$NNN_BATTHEME" "$@" &
246 # Binary file: show file info inside the pager
248 printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
249 if exists mediainfo; then
258 image/jpeg) image_preview "$cols" "$lines" "$1" ;;
259 image/gif) generate_preview "$cols" "$lines" "$1" "gif" ;;
260 image/vnd.djvu) generate_preview "$cols" "$lines" "$1" "djvu" ;;
261 image/*) generate_preview "$cols" "$lines" "$1" "image" ;;
262 video/*) generate_preview "$cols" "$lines" "$1" "video" ;;
263 audio/*) generate_preview "$cols" "$lines" "$1" "audio" ;;
264 application/font*|application/*opentype|font/*) generate_preview "$cols" "$lines" "$1" "font" ;;
265 */*office*|*/*document*|*/*msword|*/*ms-excel) generate_preview "$cols" "$lines" "$1" "office" ;;
266 application/zip) fifo_pager unzip -l "$1" ;;
269 fifo_pager man -Pcat -l "$1"
271 fifo_pager pager "$1"
273 *) handle_ext "$1" "$3" "$4" ;;
279 epub) generate_preview "$cols" "$lines" "$1" "epub" ;;
280 pdf) generate_preview "$cols" "$lines" "$1" "pdf" ;;
281 gz|bz2) fifo_pager tar -tvf "$1" ;;
282 md) if exists glow; then
283 fifo_pager glow -s dark "$1"
284 elif exists lowdown; then
285 fifo_pager lowdown -Tterm "$1"
287 fifo_pager pager "$1"
292 elif exists lynx; then
294 elif exists elinks; then
295 fifo_pager elinks "$1"
297 fifo_pager pager "$1"
299 7z|a|ace|alz|arc|arj|bz|cab|cpio|deb|jar|lha|lz|lzh|lzma|lzo\
300 |rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z)
301 if exists atool; then
302 fifo_pager atool -l "$1"
303 elif exists bsdtar; then
304 fifo_pager bsdtar -tvf "$1"
306 *) if [ "$3" = "bin" ]; then
307 fifo_pager print_bin_info "$1"
309 fifo_pager pager "$1"
316 # Trying to use pistol if it's available.
317 if [ "$NNN_PISTOL" -ne 0 ] && exists pistol; then
318 fifo_pager pistol "$1"
322 # Trying to use scope.sh if it's available.
323 if [ "$NNN_SCOPE" -ne 0 ] && exists scope.sh; then
324 fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" "True"
328 # Use QuickLook if it's available.
329 if [ -n "$QUICKLOOK" ]; then
330 stat "$1" && f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
334 # Detecting the exact type of the file: the encoding, mime type, and extension in lowercase.
335 encoding="$(file -bL --mime-encoding -- "$1")"
336 mimetype="$(file -bL --mime-type -- "$1")"
338 [ -n "$ext" ] && ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
342 # Otherwise, falling back to the defaults.
345 if [ "$NNN_ICONLOOKUP" -ne 0 ] && [ -f "$(dirname "$0")"/.iconlookup ]; then
346 [ "$NNN_SPLIT" = v ] && BSTR="\n"
347 # shellcheck disable=SC2012
348 ls -F --group-directories-first | head -n "$((lines - 3))" | "$(dirname "$0")"/.iconlookup -l "$cols" -B "$BSTR" -b " "
349 elif exists tree; then
350 fifo_pager tree --filelimit "$(find . -maxdepth 1 | wc -l)" -L 3 -C -F --dirsfirst --noreport
351 elif exists exa; then
352 exa -G --group-directories-first --colour=always
353 elif exists eza; then # eza is a community fork of exa (exa is unmaintained)
354 eza -G --group-directories-first --colour=always
356 fifo_pager ls -F --group-directories-first --color=always
359 elif [ "${encoding#*)}" = "binary" ]; then
360 handle_mime "$1" "$mimetype" "$ext" "bin"
362 handle_mime "$1" "$mimetype" "$ext"
367 if [ -n "$QLPATH" ] && stat "$3"; then
368 f="$(wslpath -w "$3")" && "$QLPATH" "$f" &
369 elif [ ! -f "$NNN_PREVIEWDIR/$3.jpg" ] || [ -n "$(find -L "$3" -newer "$NNN_PREVIEWDIR/$3.jpg")" ]; then
370 mkdir -p "$NNN_PREVIEWDIR/${3%/*}"
372 audio) ffmpeg -i "$3" -filter_complex "scale=iw*min(1\,min($NNN_PREVIEWWIDTH/iw\,ih)):-1" "$NNN_PREVIEWDIR/$3.jpg" -y ;;
373 epub) gnome-epub-thumbnailer "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
374 font) fontpreview -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" ;;
375 gif) if [ -p "$FIFO_UEBERZUG" ] && exists convert; then
376 frameprefix="$NNN_PREVIEWDIR/$3/${3##*/}"
377 if [ ! -d "$NNN_PREVIEWDIR/$3" ]; then
378 mkdir -p "$NNN_PREVIEWDIR/$3"
379 convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg" ||
380 MAGICK_TMPDIR="/tmp" convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg"
382 frames=$(($(find "$NNN_PREVIEWDIR/$3" | wc -l) - 2))
383 [ $frames -lt 0 ] && return
385 for i in $(seq 0 $frames); do
386 image_preview "$1" "$2" "$frameprefix-$i.jpg"
390 printf "%s" "$!" > "$PREVIEWPID"
393 image_preview "$1" "$2" "$3"
396 image) if exists convert; then
397 convert "$3" -flatten -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$NNN_PREVIEWDIR/$3.jpg"
399 image_preview "$1" "$2" "$3" && return
401 office) libreoffice --convert-to jpg "$3" --outdir "$NNN_PREVIEWDIR/${3%/*}"
402 filename="$(printf "%s" "${3##*/}" | cut -d. -f1)"
403 mv "$NNN_PREVIEWDIR/${3%/*}/$filename.jpg" "$NNN_PREVIEWDIR/$3.jpg" ;;
404 pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$NNN_PREVIEWDIR/$3" ;;
405 djvu) ddjvu -format=ppm -page=1 "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
406 video) ffmpegthumbnailer -m -s0 -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" || rm "$NNN_PREVIEWDIR/$3.jpg" ;;
409 if [ -f "$NNN_PREVIEWDIR/$3.jpg" ]; then
410 image_preview "$1" "$2" "$NNN_PREVIEWDIR/$3.jpg"
412 fifo_pager print_bin_info "$3"
419 if [ "$NNN_TERMINAL" = "kitty" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
420 kitty +kitten icat --silent --scale-up --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no "$3" &
421 elif [ "$NNN_TERMINAL" = "wezterm" ] && [ -z "$NNN_PREVIEWIMGPROG" ]; then
422 wezterm imgcat "$3" &
423 elif exists ueberzug && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "ueberzug" ] ;}; then
424 ueberzug_layer "$1" "$2" "$3" && return
425 elif exists catimg && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "catimg" ] ;}; then
427 elif exists viu && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "viu" ] ;}; then
429 elif exists chafa && { [ -z "$NNN_PREVIEWIMGPROG" ] || [ "$NNN_PREVIEWIMGPROG" = "chafa" ] ;}; then
432 fifo_pager print_bin_info "$3" && return
434 printf "%s" "$!" > "$PREVIEWPID"
438 [ -f "$POSOFFSET" ] && read -r x y < "$POSOFFSET"
439 printf '{"action": "add", "identifier": "nnn_ueberzug", "x": %d, "y": %d, "width": "%d", "height": "%d", "scaler": "fit_contain", "path": "%s"}\n'\
440 "${x:-0}" "${y:-0}" "$1" "$2" "$3" > "$FIFO_UEBERZUG"
444 printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
449 pidkill "$PREVIEWPID"
450 if [ -p "$FIFO_UEBERZUG" ]; then
451 pkill -f "tail --follow $FIFO_UEBERZUG"
452 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
454 preview_file "$(cat "$CURSEL")"
458 while read -r selection; do
459 if [ -n "$selection" ]; then
460 pidkill "$PREVIEWPID"
461 [ -p "$FIFO_UEBERZUG" ] && ueberzug_remove
462 [ "$selection" = "close" ] && break
463 preview_file "$selection"
464 printf "%s" "$selection" > "$CURSEL"
467 sleep 0.1 # make sure potential preview by winch_handler is killed
471 if [ "$PREVIEW_MODE" -eq 1 ] 2>/dev/null; then
472 if [ "$NNN_TERMINAL" != "kitty" ] && exists ueberzug; then
473 mkfifo "$FIFO_UEBERZUG"
474 tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
477 preview_file "$PWD/$1"
479 printf "%s" "$!" > "$FIFOPID"
480 printf "%s" "$PWD/$1" > "$CURSEL"
481 trap 'winch_handler; wait' WINCH
482 trap 'rm "$PREVIEWPID" "$CURSEL" "$FIFO_UEBERZUG" "$FIFOPID" "$POSOFFSET" 2>/dev/null' INT HUP EXIT
483 wait "$!" 2>/dev/null
486 if [ ! -r "$NNN_FIFO" ]; then
487 prompt "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')\nPlease read Usage in '$0'."
488 elif [ "$KITTY_WINDOW_ID" ] && [ -z "$TMUX" ] && [ -z "$KITTY_LISTEN_ON" ]; then
489 prompt "\$KITTY_LISTEN_ON not set!\nPlease read Usage in '$0'."
491 toggle_preview "$1" &