Bash – Use Netrw or Nerdtree in Zsh/Bash to select a file BY BROWSING

bashvimzsh

Often I find myself in the shell, wanting to insert a filename into a lengthy command.

I'd like to hit a shortcut, and use Netrw or Nerdtree to browse for a file or directory, and have it pasted in place into the command I’m building.

So if I was in a folder, and wanted to compare 2 files:

  • I'd type diff

  • then I'd like to hit my shortcut, and visually browse using Netrw or Nerdtree, and select a file.

  • That filename is now added to my diff command… e.g. diff /tmp/file1.txt

  • I hit the shortcut again, and browse for the second file,
    /super/ez/another/file/somewhere/else/compare.txt

  • this then adds the second file to my diff command, so I now have:

      diff /tmp/file1.txt /super/ez/another/file/somewhere/else/compare.txt
    

Is this possible using any tool? I like Netrw in Vim, but am willing to try new things!

Note that I'm not interested in Tab completion of filenames using globbing. That works sometimes, but not all the time. I like Netrw and would love to figure out how to use it to select a filename by browsing.

Best Answer

You basically already know the answer from here. It's quite easy to put this all together like this:

function insert_files() {
    vifm -f < /dev/tty > /dev/tty

    while read l; do
        LBUFFER+="'$l' "
    done < ~/.vifm/vimfiles

    zle reset-prompt
}
zle -N insert_files
bindkey '^t' insert_files

I'm not a zsh-user, so I stole structure of the code from answer by Lucas. As for bash, I was looking once for a way to process output of external command inside shortcut, but didn't find one.

Demonstration

P.S. My code contains quite primitive escaping, you might want to improve that and maybe change the way spacing is added between arguments.

Related Question