
# ██╗     ███████╗
# ██║     ██╔════╝
# ██║     █████╗
# ██║     ██╔══╝
# ███████╗██║
# ╚══════╝╚═╝
# Terminal file manager
# https://github.com/gokcehan/lf

set hidden false
set icons
set previewer ~/.config/lf/previewer.sh
set promptfmt "\033[34;1m%d\033[0m\033[1m%f\033[0m"
set shell bash
set shellopts '-eu'
set ifs "\n"
set scrolloff 10

map <enter> shell

# execute current file (must be executable)
map x $$f
map X !$f

# dedicated keys for file opener actions
map o &mimeopen $f
map O $mimeopen --ask $f

# define a custom 'open' command
# This command is called when current file is not a directory. You may want to
# use either file extensions and/or mime types here. Below uses an editor for
# text files and a file opener for the rest.
cmd open ${{
    case $(file --mime-type $f -b) in
        text/*) $EDITOR $fx;;
        *) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
    esac
}}

# make sure trash folder exists
# %mkdir -p ~/.trash

# move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options)
# cmd trash %set -f; mv $fx ~/.trash

cmd delete ${{
    set -f
    printf "$fx\n"
    printf "delete? [y/n]"
    read ans
    [ $ans = "y" ] && rm -rf $fx
}}

map <delete> delete

# extract the current file with the right command
# (xkcd link: https://xkcd.com/1168/)
cmd extract ${{
    set -f
    case $f in
        *.tar.bz|*.tar.bz2|*.tbz|*.tbz2) tar xjvf $f;;
        *.tar.gz|*.tgz) tar xzvf $f;;
        *.tar.xz|*.txz) tar xJvf $f;;
        *.zip) unzip $f;;
        *.rar) unrar x $f;;
        *.7z) 7z x $f;;
    esac
}}

# compress current file or selected files with tar and gunzip
cmd tar ${{
    set -f
    mkdir $1
    cp -r $fx $1
    tar czf $1.tar.gz $1
    rm -rf $1
}}

# compress current file or selected files with zip
cmd zip ${{
    set -f
    mkdir $1
    cp -r $fx $1
    zip -r $1.zip $1
    rm -rf $1
}}

cmd fzf_jump ${{
    res="$(find . -maxdepth 1 | fzf-tmux -p --reverse --header='Jump to location' | sed 's/\\/\\\\/g;s/"/\\"/g')"
    if [ -d "$res" ] ; then
        cmd="cd"
    elif [ -f "$res" ] ; then
        cmd="select"
    else
        exit 0
    fi
    lf -remote "send $id $cmd \"$res\""
}}

map <c-f> :fzf_jump

cmd z %{{
    result="$(zoxide query --exclude "${PWD}" -- "$1")"
    lf -remote "send ${id} cd '${result}'"
}}

cmd git_branch ${{
    git branch | fzf-tmux -p --reverse | xargs git checkout
    pwd_shell=$(pwd)
    lf -remote "send $id updir"
    lf -remote "send $id cd \"$pwd_shell\""
}}
map gb :git_branch
map gp ${{clear; git pull --rebase || true; echo "press ENTER"; read ENTER}}
map gs ${{clear; git status; echo "press ENTER"; read ENTER}}
map gl ${{clear; git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit}}

map f $nvim $(fzf)
