handy

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

fzf-preview.sh (1163B)


      1 #!/usr/bin/env bash
      2 
      3 REVERSE="\x1b[7m"
      4 RESET="\x1b[m"
      5 
      6 if [ -z "$1" ]; then
      7   echo "usage: $0 FILENAME[:LINENO][:IGNORED]"
      8   exit 1
      9 fi
     10 
     11 IFS=':' read -r -a INPUT <<< "$1"
     12 FILE=${INPUT[0]}
     13 CENTER=${INPUT[1]}
     14 
     15 if [[ $1 =~ ^[A-Z]:\\ ]]; then
     16   FILE=$FILE:${INPUT[1]}
     17   CENTER=${INPUT[2]}
     18 fi
     19 
     20 if [ ! -r "$FILE" ]; then
     21   echo "File not found ${FILE}"
     22   exit 1
     23 fi
     24 
     25 if [[ "$(file --dereference --mime "$FILE")" =~ binary ]]; then
     26   echo "$1 is a binary file"
     27   exit 0
     28 fi
     29 
     30 if [ -z "$CENTER" ]; then
     31   CENTER=0
     32 fi
     33 
     34 if [ -z "$LINES" ]; then
     35   if [ -r /dev/tty ]; then
     36     LINES=$(stty size < /dev/tty | awk '{print $1}')
     37   else
     38     LINES=40
     39   fi
     40 fi
     41 
     42 FIRST=$(($CENTER-$LINES/3))
     43 FIRST=$(($FIRST < 1 ? 1 : $FIRST))
     44 LAST=$((${FIRST}+${LINES}-1))
     45 
     46 DEFAULT_COMMAND="bat --style=numbers --color=always {} || highlight -O ansi -l {} || coderay {} || rougify {} || cat {}"
     47 CMD=${FZF_PREVIEW_COMMAND:-$DEFAULT_COMMAND}
     48 CMD=${CMD//{\}/$(printf %q "$FILE")}
     49 
     50 eval "$CMD" 2> /dev/null | awk "NR >= $FIRST && NR <= $LAST { \
     51     if (NR == $CENTER) \
     52         { gsub(/\x1b[[0-9;]*m/, \"&$REVERSE\"); printf(\"$REVERSE%s\n$RESET\", \$0); } \
     53     else printf(\"$RESET%s\n\", \$0); \
     54     }"