vimvim-fzf

Fuzzy set working directory from bookmarked directories in vim


Sometimes I need to change the current working directory to a different location (e.g. to search in different project). This can for example be achived with lcd /path/to/dir. However writing out paths is ofter too slow and I often find myself using the same locations. Ideally I'd have a fuzzy finder such as fzf popping up with a preset list of bookmarked directories to choose from. Fuzzy searching would allow to quickly select and change the working dir (obviously without changing the current file it was called from).

Shortly, I'm looking for the equivalent of the fzf-marks tool for vim.


Solution

  • Having done some more reading, I've found in fact a way to integrate to fzf-marks into vim, (which also work nicely without fzf-marks).

    All you need is a file listing bookmarked directories, with a variable pointing at it, e.g. FZF_MARKS_FILE="${HOME}/.fzf-marks

    This file is formatted as follows, cat $FZF_MARKS_FILE:

    project1 : /home/user/project1/code
    project2 : /home/user/project2/code
    vimswapdir : /home/user/.local/share/nvim/swap
    rlibsloc : /home/user/R/x86_64-pc-linux-gnu-library
    trash : /home/user/.local/share/Trash/files
    vim-plugins : /home/user/.config/nvim/plugged
    

    The idea now is to load and parse it similar to as its done in fzf-marks jump function and make it fuzzy searchable for quick access defining a function FM:

    command! -bang FM call fzf#run(fzf#wrap({'source': 'cat ~/.fzf-marks | sed "s/.*: \(.*\)$/\1/" | sed "s#~#${HOME}#"', 'sink': 'lcd'}, <bang>0))
    

    Calling :FM now pops up a fzf window with the bookmarked directories to select from.

    Use case (which I often find myself):

    Say I've started editing a file somewhere (say in ~/myproject), but needed to search (:grep) for a sentence containing the word foo which I know is in a file within /home/user/project1/code. I never quite can remember the path of project1, just that is has code in its path. For that reason I've bookmarked it (see above).

    Previously, have to somewhere look up the path and type it into vim i.e. typing :grep foo /home/user/project1/code. Now this works quicker as follows:

    :FM in vim, bringing up up the list of bookmarked directories, typing bits of code, e.g. co quickly confines the search:

    enter image description here

    selecting the first line does set the current directory to project1 (which can be confirmed by :pwd) but leaving the edited file as it is. Now, :grep! foo does indeed search recursively in project1.

    Having finished the search, I can reset the working dir to the current files dir :cd %:h or it's root with rooter: :Rooter.