DEV Community

Cover image for Displaying Images in lf with Kitty and Tmux

Displaying Images in lf with Kitty and Tmux

Animation of lf terminal file manager displaying images

The Problem

When using lf (the terminal file manager) with Kitty and Tmux, image preview display often causes issues: graphical artifacts remain on screen when switching from one preview to another, making the interface unreadable.

Viewing images with issues

After several attempts, I found a solution that seems to work well. It relies on three elements:

  1. The redraw command in lf
  2. No cleaner script
  3. The on-select event in lf

Viewing images without issues

lf Configuration

Here's the configuration to add to your lfrc file:

set previewer ~/.local/bin/lfpreview
cmd on-select &{{
  exec lf -remote 'send redraw'
}}

Enter fullscreen mode Exit fullscreen mode

The preview script (previewer) will be detailed later. The key element here is using on-select to ask lf to redraw itself on each selection. This command performs the terminal cleanup and ensures clean preview display.

The Preview Script

Create the file ~/.local/bin/lfpreview with the following content:

#!/bin/sh
draw() {
  kitten icat --stdin no --transfer-mode memory \
  --place "${w}x${h}@${x}x${y}" "$1" </dev/null >/dev/tty
}

file="$1"
w="$2"
h="$3"
x="$4"
y="$5"

case "$(file -Lb --mime-type "$file")" in
  image/*)
    draw "$file"
  ;;
  application/pdf)
    pdftoppm -f 1 -singlefile "$file" "/tmp/lfoutput"
    draw "/tmp/lfoutput.ppm"
  ;;
  *)
    less "$1"
  ;;
esac

exit 1 # do not cache
Enter fullscreen mode Exit fullscreen mode

Don't forget to make it executable:

chmod +x ~/.local/bin/lfpreview
Enter fullscreen mode Exit fullscreen mode

This simplified version handles:

  • Images (via kitten icat)
  • PDFs (converting the first page to an image)
  • Other files (display via less)

Important Points

The exit 1 at the end of the script is crucial: it tells lf not to cache the previews. Without it, the refresh mechanism wouldn't work properly, as lf would reuse cached previews instead of redisplaying the image on each selection.

Conclusion

This configuration works well for my use case, but it may require adjustments depending on your environment. Feel free to adapt the preview script to handle other file types according to your needs.

Top comments (0)