]> git.rmz.io Git - dotfiles.git/blob - ranger/scope.sh
ranger: replace scope.sh with new upstream version
[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 ## JSON
111 json)
112 jq --color-output . "${FILE_PATH}" && exit 5
113 python -m json.tool -- "${FILE_PATH}" && exit 5
114 ;;
115
116 ## Jupyter Notebooks
117 ipynb)
118 jupyter nbconvert --to markdown "${FILE_PATH}" --stdout | env COLORTERM=8bit bat --color=always --style=plain --language=markdown && exit 5
119 jupyter nbconvert --to markdown "${FILE_PATH}" --stdout && exit 5
120 jq --color-output . "${FILE_PATH}" && exit 5
121 python -m json.tool -- "${FILE_PATH}" && exit 5
122 ;;
123
124 ## Direct Stream Digital/Transfer (DSDIFF) and wavpack aren't detected
125 ## by file(1).
126 dff|dsf|wv|wvc)
127 mediainfo "${FILE_PATH}" && exit 5
128 exiftool "${FILE_PATH}" && exit 5
129 ;; # Continue with next handler on failure
130 esac
131 }
132
133 handle_image() {
134 ## Size of the preview if there are multiple options or it has to be
135 ## rendered from vector graphics. If the conversion program allows
136 ## specifying only one dimension while keeping the aspect ratio, the width
137 ## will be used.
138 local DEFAULT_SIZE="1920x1080"
139
140 local mimetype="${1}"
141 case "${mimetype}" in
142 ## SVG
143 image/svg+xml|image/svg)
144 rsvg-convert --keep-aspect-ratio --width "${DEFAULT_SIZE%x*}" "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}.png" \
145 && mv "${IMAGE_CACHE_PATH}.png" "${IMAGE_CACHE_PATH}" \
146 && exit 6
147 exit 1;;
148
149 ## DjVu
150 # image/vnd.djvu)
151 # ddjvu -format=tiff -quality=90 -page=1 -size="${DEFAULT_SIZE}" \
152 # - "${IMAGE_CACHE_PATH}" < "${FILE_PATH}" \
153 # && exit 6 || exit 1;;
154
155 ## Image
156 image/*)
157 local orientation
158 orientation="$( identify -format '%[EXIF:Orientation]\n' -- "${FILE_PATH}" )"
159 ## If orientation data is present and the image actually
160 ## needs rotating ("1" means no rotation)...
161 if [[ -n "$orientation" && "$orientation" != 1 ]]; then
162 ## ...auto-rotate the image according to the EXIF data.
163 convert -- "${FILE_PATH}" -auto-orient "${IMAGE_CACHE_PATH}" && exit 6
164 fi
165
166 ## `w3mimgdisplay` will be called for all images (unless overridden
167 ## as above), but might fail for unsupported types.
168 exit 7;;
169
170 ## Video
171 # video/*)
172 # # Get embedded thumbnail
173 # ffmpeg -i "${FILE_PATH}" -map 0:v -map -0:V -c copy "${IMAGE_CACHE_PATH}" && exit 6
174 # # Get frame 10% into video
175 # ffmpegthumbnailer -i "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}" -s 0 && exit 6
176 # exit 1;;
177
178 ## Audio
179 # audio/*)
180 # # Get embedded thumbnail
181 # ffmpeg -i "${FILE_PATH}" -map 0:v -map -0:V -c copy \
182 # "${IMAGE_CACHE_PATH}" && exit 6;;
183
184 ## PDF
185 # application/pdf)
186 # pdftoppm -f 1 -l 1 \
187 # -scale-to-x "${DEFAULT_SIZE%x*}" \
188 # -scale-to-y -1 \
189 # -singlefile \
190 # -jpeg -tiffcompression jpeg \
191 # -- "${FILE_PATH}" "${IMAGE_CACHE_PATH%.*}" \
192 # && exit 6 || exit 1;;
193
194
195 ## ePub, MOBI, FB2 (using Calibre)
196 # application/epub+zip|application/x-mobipocket-ebook|\
197 # application/x-fictionbook+xml)
198 # # ePub (using https://github.com/marianosimone/epub-thumbnailer)
199 # epub-thumbnailer "${FILE_PATH}" "${IMAGE_CACHE_PATH}" \
200 # "${DEFAULT_SIZE%x*}" && exit 6
201 # ebook-meta --get-cover="${IMAGE_CACHE_PATH}" -- "${FILE_PATH}" \
202 # >/dev/null && exit 6
203 # exit 1;;
204
205 ## Font
206 application/font*|application/*opentype)
207 preview_png="/tmp/$(basename "${IMAGE_CACHE_PATH%.*}").png"
208 if fontimage -o "${preview_png}" \
209 --pixelsize "120" \
210 --fontname \
211 --pixelsize "80" \
212 --text " ABCDEFGHIJKLMNOPQRSTUVWXYZ " \
213 --text " abcdefghijklmnopqrstuvwxyz " \
214 --text " 0123456789.:,;(*!?') ff fl fi ffi ffl " \
215 --text " The quick brown fox jumps over the lazy dog. " \
216 "${FILE_PATH}";
217 then
218 convert -- "${preview_png}" "${IMAGE_CACHE_PATH}" \
219 && rm "${preview_png}" \
220 && exit 6
221 else
222 exit 1
223 fi
224 ;;
225
226 ## Preview archives using the first image inside.
227 ## (Very useful for comic book collections for example.)
228 # application/zip|application/x-rar|application/x-7z-compressed|\
229 # application/x-xz|application/x-bzip2|application/x-gzip|application/x-tar)
230 # local fn=""; local fe=""
231 # local zip=""; local rar=""; local tar=""; local bsd=""
232 # case "${mimetype}" in
233 # application/zip) zip=1 ;;
234 # application/x-rar) rar=1 ;;
235 # application/x-7z-compressed) ;;
236 # *) tar=1 ;;
237 # esac
238 # { [ "$tar" ] && fn=$(tar --list --file "${FILE_PATH}"); } || \
239 # { fn=$(bsdtar --list --file "${FILE_PATH}") && bsd=1 && tar=""; } || \
240 # { [ "$rar" ] && fn=$(unrar lb -p- -- "${FILE_PATH}"); } || \
241 # { [ "$zip" ] && fn=$(zipinfo -1 -- "${FILE_PATH}"); } || return
242 #
243 # fn=$(echo "$fn" | python -c "from __future__ import print_function; \
244 # import sys; import mimetypes as m; \
245 # [ print(l, end='') for l in sys.stdin if \
246 # (m.guess_type(l[:-1])[0] or '').startswith('image/') ]" |\
247 # sort -V | head -n 1)
248 # [ "$fn" = "" ] && return
249 # [ "$bsd" ] && fn=$(printf '%b' "$fn")
250 #
251 # [ "$tar" ] && tar --extract --to-stdout \
252 # --file "${FILE_PATH}" -- "$fn" > "${IMAGE_CACHE_PATH}" && exit 6
253 # fe=$(echo -n "$fn" | sed 's/[][*?\]/\\\0/g')
254 # [ "$bsd" ] && bsdtar --extract --to-stdout \
255 # --file "${FILE_PATH}" -- "$fe" > "${IMAGE_CACHE_PATH}" && exit 6
256 # [ "$bsd" ] || [ "$tar" ] && rm -- "${IMAGE_CACHE_PATH}"
257 # [ "$rar" ] && unrar p -p- -inul -- "${FILE_PATH}" "$fn" > \
258 # "${IMAGE_CACHE_PATH}" && exit 6
259 # [ "$zip" ] && unzip -pP "" -- "${FILE_PATH}" "$fe" > \
260 # "${IMAGE_CACHE_PATH}" && exit 6
261 # [ "$rar" ] || [ "$zip" ] && rm -- "${IMAGE_CACHE_PATH}"
262 # ;;
263 esac
264
265 # openscad_image() {
266 # TMPPNG="$(mktemp -t XXXXXX.png)"
267 # openscad --colorscheme="${OPENSCAD_COLORSCHEME}" \
268 # --imgsize="${OPENSCAD_IMGSIZE/x/,}" \
269 # -o "${TMPPNG}" "${1}"
270 # mv "${TMPPNG}" "${IMAGE_CACHE_PATH}"
271 # }
272
273 case "${FILE_EXTENSION_LOWER}" in
274 ## 3D models
275 ## OpenSCAD only supports png image output, and ${IMAGE_CACHE_PATH}
276 ## is hardcoded as jpeg. So we make a tempfile.png and just
277 ## move/rename it to jpg. This works because image libraries are
278 ## smart enough to handle it.
279 # csg|scad)
280 # openscad_image "${FILE_PATH}" && exit 6
281 # ;;
282 # 3mf|amf|dxf|off|stl)
283 # openscad_image <(echo "import(\"${FILE_PATH}\");") && exit 6
284 # ;;
285 drawio)
286 draw.io -x "${FILE_PATH}" -o "${IMAGE_CACHE_PATH}" \
287 --width "${DEFAULT_SIZE%x*}" && exit 6
288 exit 1;;
289 esac
290 }
291
292 handle_mime() {
293 local mimetype="${1}"
294 case "${mimetype}" in
295 ## RTF and DOC
296 text/rtf|*msword)
297 ## Preview as text conversion
298 ## note: catdoc does not always work for .doc files
299 ## catdoc: http://www.wagner.pp.ru/~vitus/software/catdoc/
300 catdoc -- "${FILE_PATH}" && exit 5
301 exit 1;;
302
303 ## DOCX, ePub, FB2 (using markdown)
304 ## You might want to remove "|epub" and/or "|fb2" below if you have
305 ## uncommented other methods to preview those formats
306 *wordprocessingml.document|*/epub+zip|*/x-fictionbook+xml)
307 ## Preview as markdown conversion
308 pandoc -s -t markdown -- "${FILE_PATH}" && exit 5
309 exit 1;;
310
311 ## E-mails
312 message/rfc822)
313 ## Parsing performed by mu: https://github.com/djcb/mu
314 mu view -- "${FILE_PATH}" && exit 5
315 exit 1;;
316
317 ## XLS
318 *ms-excel)
319 ## Preview as csv conversion
320 ## xls2csv comes with catdoc:
321 ## http://www.wagner.pp.ru/~vitus/software/catdoc/
322 xls2csv -- "${FILE_PATH}" && exit 5
323 exit 1;;
324
325 ## Text
326 text/* | */xml)
327 ## Syntax highlight
328 if [[ "$( stat --printf='%s' -- "${FILE_PATH}" )" -gt "${HIGHLIGHT_SIZE_MAX}" ]]; then
329 exit 2
330 fi
331 if [[ "$( tput colors )" -ge 256 ]]; then
332 local pygmentize_format='terminal256'
333 local highlight_format='xterm256'
334 else
335 local pygmentize_format='terminal'
336 local highlight_format='ansi'
337 fi
338 env HIGHLIGHT_OPTIONS="${HIGHLIGHT_OPTIONS}" highlight \
339 --out-format="${highlight_format}" \
340 --force -- "${FILE_PATH}" && exit 5
341 env COLORTERM=8bit bat --color=always --style="plain" \
342 -- "${FILE_PATH}" && exit 5
343 pygmentize -f "${pygmentize_format}" -O "style=${PYGMENTIZE_STYLE}"\
344 -- "${FILE_PATH}" && exit 5
345 exit 2;;
346
347 ## DjVu
348 image/vnd.djvu)
349 ## Preview as text conversion (requires djvulibre)
350 djvutxt "${FILE_PATH}" | fmt -w "${PV_WIDTH}" && exit 5
351 exiftool "${FILE_PATH}" && exit 5
352 exit 1;;
353
354 ## Image
355 image/*)
356 ## Preview as text conversion
357 # img2txt --gamma=0.6 --width="${PV_WIDTH}" -- "${FILE_PATH}" && exit 4
358 exiftool "${FILE_PATH}" && exit 5
359 exit 1;;
360
361 ## Video and audio
362 video/* | audio/*)
363 mediainfo "${FILE_PATH}" && exit 5
364 exiftool "${FILE_PATH}" && exit 5
365 exit 1;;
366
367 ## ELF files (executables and shared objects)
368 application/x-executable | application/x-pie-executable | application/x-sharedlib)
369 readelf -WCa "${FILE_PATH}" && exit 5
370 exit 1;;
371 esac
372 }
373
374 handle_fallback() {
375 echo '----- File Type Classification -----' && file --dereference --brief -- "${FILE_PATH}" && exit 5
376 exit 1
377 }
378
379
380 MIMETYPE="$( file --dereference --brief --mime-type -- "${FILE_PATH}" )"
381 if [[ "${PV_IMAGE_ENABLED}" == 'True' ]]; then
382 handle_image "${MIMETYPE}"
383 fi
384 handle_extension
385 handle_mime "${MIMETYPE}"
386 handle_fallback
387
388 exit 1