How to preview images in Ranger file manager with iTerm and Tmux
Configure Ranger file manager to preview images in iTerm2 with Tmux, including HTML and JSON file previews.
I have been aware of ranger as a file system browser for quite some time.
Once you have installed ranger, go and edit the following file ~/.config/ranger/rc.conf. These settings adjust the column layout, enable image previews, and set the preview method to iTerm2.
1
2
3
4
5
6
7
8
9
10
vim ~/.config/ranger/scope.conf
...
# How many columns are there, and what are their relative widths?
set column_ratios 1,2,5
...
set preview_images true
set use_preview_script true
set preview_images_method iterm2
...
:wq!
Then it is important to set up HTML and JSON/Terraform file previews in ~/.config/ranger/scope.conf. This allows Ranger to render HTML files as markdown using pandoc and pretty-print JSON and Terraform state files using jq.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
vim ~/.config/ranger/scope.conf
...
## HTML
htm|html|xhtml)
## Preview as text conversion
# w3m -dump "${FILE_PATH}" && exit 5
# lynx -dump -- "${FILE_PATH}" && exit 5
# elinks -dump "${FILE_PATH}" && exit 5
pandoc -s -t markdown -- "${FILE_PATH}" && exit 5
;;
## JSON
json|tfstate)
jq --color-output . "${FILE_PATH}" && exit 5
python -m json.tool -- "${FILE_PATH}" && exit 5
;;
...
...
image/*)
local orientation
orientation="$( identify -format '%[EXIF:Orientation]\n' -- "${FILE_PATH}" )"
## If orientation data is present and the image actually
## needs rotating ("1" means no rotation)...
if [[ -n "$orientation" && "$orientation" != 1 ]]; then
## ...auto-rotate the image according to the EXIF data.
convert -- "${FILE_PATH}" -auto-orient "${IMAGE_CACHE_PATH}" && exit 6
convert -- "${FILE_PATH}" -quality 25 -resize 1080 -auto-orient "${IMAGE_CACHE_PATH}" && exit 6
else
convert -- "${FILE_PATH}" -quality 25 -resize 1080 "${IMAGE_CACHE_PATH}" && exit 6
fi
## `w3mimgdisplay` will be called for all images (unless overriden
## as above), but might fail for unsupported types.
exit 7;;
## Video
...
:wq!
And lastly I would recommend editing the ~/.config/ranger/rifle.conf file because HTML files were opened by elinks by default. I have changed it to the vim editor.
Please add one line of code at the very beginning of this file: ~/.config/ranger/rifle.conf
1
2
3
4
5
6
vim ~/.config/ranger/rifle.conf
...
ext x?html?, has vim, terminal = ${VISUAL:-$EDITOR} -- "$@"
...
:wq!