# https://junegunn.github.io/fzf

define-command fzf-buflist -docstring "Use fzf to select buffer" %{
    set-register f %sh{ printf "%s" "$kak_buflist" | tr ' ' '\n' }
    wezterm-terminal-tab sh -c %{
        PATH=$PATH:~/.fzf/bin/
        kak_session=$1 kak_client=$2 buflist=$3
        shift 3
        # Note: we need to replace ~ with $HOME here; otherwise bat can't find the file for preview
        output=$(printf "$buflist" | sed "s|~|$HOME|" | fzf --preview 'bat --color=always {}')
        kak_cmd="evaluate-commands -client $kak_client buffer $output"
        echo $kak_cmd | kak -p $kak_session
    } -- %val{session} %val{client} %reg{f}
}

define-command fzf-lines -docstring "Use fzf to jump to line in current buffer" %{
    set-register f %sh{ mktemp }
    execute-keys -draft '%<a-|> nl -b a > $kak_reg_f<ret>'
    wezterm-terminal-tab sh -c %{
        PATH=$PATH:~/.fzf/bin/
        kak_session=$1 kak_client=$2 buffile=$3
        shift 3
        output=$(fzf --layout=reverse < $buffile)
        set -- $output
        kak_cmd="evaluate-commands -client $kak_client execute-keys '${1}g'"
        rm $buffile
        echo $kak_cmd | kak -p $kak_session
    } -- %val{session} %val{client} %reg{f}
}
