]> git.rmz.io Git - dotfiles.git/blob - ranger/scope.sh
lazyvim: absorb snacks notifier
[dotfiles.git] / ranger / scope.sh
1 #!/usr/bin/env bash
2
3 set -o noclobber -o noglob -o nounset -o pipefail
4 IFS=$'\n'
5
6 ## If the option `use_preview_script` is set to `true`,
7 ## then this script will be called and its output will be displayed in ranger.
8 ## ANSI color codes are supported.
9 ## STDIN is disabled, so interactive scripts won't work properly
10
11 ## This script is considered a configuration file and must be updated manually.
12 ## It will be left untouched if you upgrade ranger.
13
14 ## Because of some automated testing we do on the script #'s for comments need
15 ## to be doubled up. Code that is commented out, because it's an alternative for
16 ## example, gets only one #.
17
18 ## Meanings of exit codes:
19 ## code | meaning | action of ranger
20 ## -----+------------+-------------------------------------------
21 ## 0 | success | Display stdout as preview
22 ## 1 | no preview | Display no preview at all
23 ## 2 | plain text | Display the plain content of the file
24 ## 3 | fix width | Don't reload when width changes
25 ## 4 | fix height | Don't reload when height changes
26 ## 5 | fix both | Don't ever reload
27 ## 6 | image | Display the image `$IMAGE_CACHE_PATH` points to as an image preview
28 ## 7 | image | Display the file directly as an image
29
30 ## Script arguments
31 FILE_PATH="${1}" # Full path of the highlighted file
32 PV_WIDTH="${2}" # Width of the preview pane (number of fitting characters)
33 ## shellcheck disable=SC2034 # PV_HEIGHT is provided for convenience and unused
34 PV_HEIGHT="${3}" # Height of the preview pane (number of fitting characters)
35 IMAGE_CACHE_PATH="${4}" # Full path that should be used to cache image preview
36 PV_IMAGE_ENABLED="${5}" # 'True' if image previews are enabled, 'False' otherwise.
37
38 FILE_EXTENSION="${FILE_PATH##*.}"
39 FILE_EXTENSION_LOWER="$(printf "%s" "${FILE_EXTENSION}" | tr '[:upper:]' '[:lower:]')"
40
41 ## Settings
42 HIGHLIGHT_SIZE_MAX=262143 # 256KiB
43 HIGHLIGHT_TABWIDTH="${HIGHLIGHT_TABWIDTH:-8}"
44 HIGHLIGHT_STYLE="${HIGHLIGHT_STYLE:-pablo}"
45 HIGHLIGHT_OPTIONS="--replace-tabs=${HIGHLIGHT_TABWIDTH} --style=${HIGHLIGHT_STYLE} ${HIGHLIGHT_OPTIONS:-}"
46 PYGMENTIZE_STYLE="${PYGMENTIZE_STYLE:-autumn}"
47 OPENSCAD_IMGSIZE="${RNGR_OPENSCAD_IMGSIZE:-1000,1000}"
48 OPENSCAD_COLORSCHEME="${RNGR_OPENSCAD_COLORSCHEME:-Tomorrow Night}"
49
50 handle_extension() {
51 case "${FILE_EXTENSION_LOWER}" in
52 ## Archive
53 a|ace|alz|arc|arj|bz|bz2|cab|cpio|deb|gz|jar|lha|lz|lzh|lzma|lzo|\
54 rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z|zip)
55 atool --list -- "${FILE_PATH}" && exit 5
56 bsdtar --list --file "${FILE_PATH}" && exit 5
57 exit 1;;
58 rar)
59 ## Avoid password prompt by providing empty password
60 unrar lt -p- -- "${FILE_PATH}" && exit 5
61 exit 1;;
62 7z)
63 ## Avoid password prompt by providing empty password
64 7z l -p -- "${FILE_PATH}" && exit 5
65 exit 1;;
66
67 ## PDF
68 pdf)
69 ## Preview as text conversion
70 pdftotext -l 10 -nopgbrk -q -- "${FILE_PATH}" - | \
71 fmt -w "${PV_WIDTH}" && exit 5
72 mutool draw -F txt -i -- "${FILE_PATH}" 1-10 | \
73 fmt -w "${PV_WIDTH}" && exit 5
74 exiftool "${FILE_PATH}" && exit 5
75 exit 1;;
76
77 ## BitTorrent
78 torrent)
79 transmission-show -- "${FILE_PATH}" && exit 5
80 exit 1;;
81
82 ## OpenDocument
83 odt|sxw)
84 ## Preview as text conversion
85 odt2txt "${FILE_PATH}" && exit 5
86 ## Preview as markdown conversion
87 pandoc -s -t markdown -- "${FILE_PATH}" && exit 5
88 exit 1;;
89 ods|odp)
90 ## Preview as text conversion (unsupported by pandoc for markdown)
91 odt2txt "${FILE_PATH}" && exit 5
92 exit 1;;
93
94 ## XLSX
95 xlsx)
96 ## Preview as csv conversion
97 ## Uses: https://github.com/dilshod/xlsx2csv
98 xlsx2csv -- "${FILE_PATH}" && exit 5
99 exit 1;;
100
101 ## HTML
102 htm|html|xhtml)
103 ## Preview as text conversion
104 w3m -dump "${FILE_PATH}" && exit 5
105 lynx -dump -- "${FILE_PATH}" && exit 5
106 elinks -dump "${FILE_PATH}" && exit 5
107 pandoc -s -t markdown -- "${FILE_PATH}" && exit 5
108 ;;
109
110 # GnuPG
111 gpg)
112 gpg --decrypt "$path" | trim && exit 5
113 ;;
114
115 ## JSON
116 json)
117 jq --color-output . "${FILE_PATH}" && exit 5
118 python -m json.tool -- "${FILE_PATH}" && exit 5
119 ;;
120
121 ## Jupyter Notebooks
122 ipynb)
123 jupyter nbconvert --to markdown "${FILE_PATH}" --stdout | env COLORTERM=8bit bat --color=always --style=plain --language=markdown && exit 5
124 jupyter nbconvert --to markdown "${FILE_PATH}" --stdout && exit 5
125 jq --color-output . "${FILE_PATH}" && exit 5
126 python -m json.tool -- "${FILE_PATH}" && exit 5
127 ;;
128
129 ## Direct Stream Digital/Transfer (DSDIFF) and wavpack aren't detected
130 ## by file(1).
131 dff|dsf|wv|wvc)
132 mediainfo "${FILE_PATH}" && exit 5
133 exiftool "${FILE_PATH}" && exit 5
134 ;; # Continue with next handler on failure
135 esac
136 }
137
138 handle_image() {
139 ## Size of the preview if there are multiple options or it has to be
140 ## rendered from vector graphics. If the conversion program allows
141 ## specifying only one dimension while keeping the aspect ratio, the width
142 ## will be used.
143 local DEFAULT_SIZE="1920x1080"
144
145 local mimetype="${1}"
146 case "${mimetype}" in
147 ## SVG
148 image/svg+xml|image/svg)
149 rsvg-convert --keep-aspect-ratio --width "${DEFAULT_SIZE%x*}" "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}.png" \
150 && mv "${IMAGE_CACHE_PATH}.png" "${IMAGE_CACHE_PATH}" \
151 && exit 6
152 exit 1;;
153
154 ## DjVu
155 # image/vnd.djvu)
156 # ddjvu -format=tiff -quality=90 -page=1 -size="${DEFAULT_SIZE}" \
157 # - "${IMAGE_CACHE_PATH}" < "${FILE_PATH}" \
158 # && exit 6 || exit 1;;
159
160 ## Image
161 image/*)
162 local orientation
163 orientation="$( identify -format '%[EXIF:Orientation]\n' -- "${FILE_PATH}" )"
164 ## If orientation data is present and the image actually
165 ## needs rotating ("1" means no rotation)...
166 if [[ -n "$orientation" && "$orientation" != 1 ]]; then
167 ## ...auto-rotate the image according to the EXIF data.
168 convert -- "${FILE_PATH}" -auto-orient "${IMAGE_CACHE_PATH}" && exit 6
169 fi
170
171 ## `w3mimgdisplay` will be called for all images (unless overridden
172 ## as above), but might fail for unsupported types.
173 exit 7;;
174
175 ## Video
176 # video/*)
177 # # Get embedded thumbnail
178 # ffmpeg -i "${FILE_PATH}" -map 0:v -map -0:V -c copy "${IMAGE_CACHE_PATH}" && exit 6
179 # # Get frame 10% into video
180 # ffmpegthumbnailer -i "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}" -s 0 && exit 6
181 # exit 1;;
182
183 ## Audio
184 # audio/*)
185 # # Get embedded thumbnail
186 # ffmpeg -i "${FILE_PATH}" -map 0:v -map -0:V -c copy \
187 # "${IMAGE_CACHE_PATH}" && exit 6;;
188
189 ## PDF
190 # application/pdf)
191 # pdftoppm -f 1 -l 1 \
192 # -scale-to-x "${DEFAULT_SIZE%x*}" \
193 # -scale-to-y -1 \
194 # -singlefile \
195 # -jpeg -tiffcompression jpeg \
196 # -- "${FILE_PATH}" "${IMAGE_CACHE_PATH%.*}" \
197 # && exit 6 || exit 1;;
198
199
200 ## ePub, MOBI, FB2 (using Calibre)
201 # application/epub+zip|application/x-mobipocket-ebook|\
202 # application/x-fictionbook+xml)
203 # # ePub (using https://github.com/marianosimone/epub-thumbnailer)
204 # epub-thumbnailer "${FILE_PATH}" "${IMAGE_CACHE_PATH}" \
205 # "${DEFAULT_SIZE%x*}" && exit 6
206 # ebook-meta --get-cover="${IMAGE_CACHE_PATH}" -- "${FILE_PATH}" \
207 # >/dev/null && exit 6
208 # exit 1;;
209
210 ## Font
211 application/font*|application/*opentype)
212 preview_png="/tmp/$(basename "${IMAGE_CACHE_PATH%.*}").png"
213 if fontimage -o "${preview_png}" \
214 --pixelsize "120" \
215 --fontname \
216 --pixelsize "80" \
217 --text " ABCDEFGHIJKLMNOPQRSTUVWXYZ " \
218 --text " abcdefghijklmnopqrstuvwxyz " \
219 --text " 0123456789.:,;(*!?') ff fl fi ffi ffl " \
220 --text " The quick brown fox jumps over the lazy dog. " \
221 "${FILE_PATH}";
222 then
223 convert -- "${preview_png}" "${IMAGE_CACHE_PATH}" \
224 && rm "${preview_png}" \
225 && exit 6
226 else
227 exit 1
228 fi
229 ;;
230
231 ## Preview archives using the first image inside.
232 ## (Very useful for comic book collections for example.)
233 # application/zip|application/x-rar|application/x-7z-compressed|\
234 # application/x-xz|application/x-bzip2|application/x-gzip|application/x-tar)
235 # local fn=""; local fe=""
236 # local zip=""; local rar=""; local tar=""; local bsd=""
237 # case "${mimetype}" in
238 # application/zip) zip=1 ;;
239 # application/x-rar) rar=1 ;;
240 # application/x-7z-compressed) ;;
241 # *) tar=1 ;;
242 # esac
243 # { [ "$tar" ] && fn=$(tar --list --file "${FILE_PATH}"); } || \
244 # { fn=$(bsdtar --list --file "${FILE_PATH}") && bsd=1 && tar=""; } || \
245 # { [ "$rar" ] && fn=$(unrar lb -p- -- "${FILE_PATH}"); } || \
246 # { [ "$zip" ] && fn=$(zipinfo -1 -- "${FILE_PATH}"); } || return
247 #
248 # fn=$(echo "$fn" | python -c "from __future__ import print_function; \
249 # import sys; import mimetypes as m; \
250 # [ print(l, end='') for l in sys.stdin if \
251 # (m.guess_type(l[:-1])[0] or '').startswith('image/') ]" |\
252 # sort -V | head -n 1)
253 # [ "$fn" = "" ] && return
254 # [ "$bsd" ] && fn=$(printf '%b' "$fn")
255 #
256 # [ "$tar" ] && tar --extract --to-stdout \
257 # --file "${FILE_PATH}" -- "$fn" > "${IMAGE_CACHE_PATH}" && exit 6
258 # fe=$(echo -n "$fn" | sed 's/[][*?\]/\\\0/g')
259 # [ "$bsd" ] && bsdtar --extract --to-stdout \
260 # --file "${FILE_PATH}" -- "$fe" > "${IMAGE_CACHE_PATH}" && exit 6
261 # [ "$bsd" ] || [ "$tar" ] && rm -- "${IMAGE_CACHE_PATH}"
262 # [ "$rar" ] && unrar p -p- -inul -- "${FILE_PATH}" "$fn" > \
263 # "${IMAGE_CACHE_PATH}" && exit 6
264 # [ "$zip" ] && unzip -pP "" -- "${FILE_PATH}" "$fe" > \
265 # "${IMAGE_CACHE_PATH}" && exit 6
266 # [ "$rar" ] || [ "$zip" ] && rm -- "${IMAGE_CACHE_PATH}"
267 # ;;
268 esac
269
270 openscad_image() {
271 TMPPNG="$(mktemp -t XXXXXX.png)"
272 openscad --colorscheme="${OPENSCAD_COLORSCHEME}" \
273 --imgsize="${OPENSCAD_IMGSIZE/x/,}" \
274 -o "${TMPPNG}" "${1}" \
275 && mv "${TMPPNG}" "${IMAGE_CACHE_PATH}"
276 }
277
278 case "${FILE_EXTENSION_LOWER}" in
279 ## 3D models
280 ## OpenSCAD only supports png image output, and ${IMAGE_CACHE_PATH}
281 ## is hardcoded as jpeg. So we make a tempfile.png and just
282 ## move/rename it to jpg. This works because image libraries are
283 ## smart enough to handle it.
284 csg|scad)
285 openscad_image "${FILE_PATH}" && exit 6
286 ;;
287 # 3mf|amf|dxf|off|stl)
288 # openscad_image <(echo "import(\"${FILE_PATH}\");") && exit 6
289 # ;;
290 drawio)
291 draw.io -x "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}" \
292 --width "${DEFAULT_SIZE%x*}" && exit 6
293 exit 1;;
294 esac
295 }
296
297 handle_mime() {
298 local mimetype="${1}"
299 case "${mimetype}" in
300 ## RTF and DOC
301 text/rtf|*msword)
302 ## Preview as text conversion
303 ## note: catdoc does not always work for .doc files
304 ## catdoc: http://www.wagner.pp.ru/~vitus/software/catdoc/
305 catdoc -- "${FILE_PATH}" && exit 5
306 exit 1;;
307
308 ## DOCX, ePub, FB2 (using markdown)
309 ## You might want to remove "|epub" and/or "|fb2" below if you have
310 ## uncommented other methods to preview those formats
311 *wordprocessingml.document|*/epub+zip|*/x-fictionbook+xml)
312 ## Preview as markdown conversion
313 pandoc -s -t markdown -- "${FILE_PATH}" && exit 5
314 exit 1;;
315
316 ## E-mails
317 message/rfc822)
318 ## Parsing performed by mu: https://github.com/djcb/mu
319 mu view -- "${FILE_PATH}" && exit 5
320 exit 1;;
321
322 ## XLS
323 *ms-excel)
324 ## Preview as csv conversion
325 ## xls2csv comes with catdoc:
326 ## http://www.wagner.pp.ru/~vitus/software/catdoc/
327 xls2csv -- "${FILE_PATH}" && exit 5
328 exit 1;;
329
330 ## Text
331 text/* | */xml)
332 ## Syntax highlight
333 if [[ "$( stat --printf='%s' -- "${FILE_PATH}" )" -gt "${HIGHLIGHT_SIZE_MAX}" ]]; then
334 exit 2
335 fi
336 if [[ "$( tput colors )" -ge 256 ]]; then
337 local pygmentize_format='terminal256'
338 local highlight_format='xterm256'
339 else
340 local pygmentize_format='terminal'
341 local highlight_format='ansi'
342 fi
343 env HIGHLIGHT_OPTIONS="${HIGHLIGHT_OPTIONS}" highlight \
344 --out-format="${highlight_format}" \
345 --force -- "${FILE_PATH}" && exit 5
346 env COLORTERM=8bit bat --color=always --style="plain" \
347 -- "${FILE_PATH}" && exit 5
348 pygmentize -f "${pygmentize_format}" -O "style=${PYGMENTIZE_STYLE}"\
349 -- "${FILE_PATH}" && exit 5
350 exit 2;;
351
352 ## DjVu
353 image/vnd.djvu)
354 ## Preview as text conversion (requires djvulibre)
355 djvutxt "${FILE_PATH}" | fmt -w "${PV_WIDTH}" && exit 5
356 exiftool "${FILE_PATH}" && exit 5
357 exit 1;;
358
359 ## Image
360 image/*)
361 ## Preview as text conversion
362 # img2txt --gamma=0.6 --width="${PV_WIDTH}" -- "${FILE_PATH}" && exit 4
363 exiftool "${FILE_PATH}" && exit 5
364 exit 1;;
365
366 ## Video and audio
367 video/* | audio/*)
368 mediainfo "${FILE_PATH}" && exit 5
369 exiftool "${FILE_PATH}" && exit 5
370 exit 1;;
371
372 ## ELF files (executables and shared objects)
373 application/x-executable | application/x-pie-executable | application/x-sharedlib)
374 readelf -WCa "${FILE_PATH}" && exit 5
375 exit 1;;
376 esac
377 }
378
379 handle_fallback() {
380 echo '----- File Type Classification -----' && file --dereference --brief -- "${FILE_PATH}" && exit 5
381 exit 1
382 }
383
384
385 MIMETYPE="$( file --dereference --brief --mime-type -- "${FILE_PATH}" )"
386 if [[ "${PV_IMAGE_ENABLED}" == 'True' ]]; then
387 handle_image "${MIMETYPE}"
388 fi
389 handle_extension
390 handle_mime "${MIMETYPE}"
391 handle_fallback
392
393 exit 1