Vim counts filenames beginning with /
as file system root always, as
you observed. If that wasn't the case, of if 'isf'
(the option that
controls what is considered file name) accepted a regex, this would be
easier to solve. But if you remove /
from 'isf'
then no slashes are
considered part of a file name anymore.
The only solution to this I can think of is using the visual mode for
gf
. As you may know, if you have text selected visually and use gf
then the visual selection will be considered, instead of the 'isf'
match. Then all we need to do is to visually select the file name under
cursor excluding a possible leading /
. This can be solved in a map, if
you don't mind messing your previous search:
nnoremap <silent> gf :let @/ = substitute(expand('<cfile>'), '^/', '', '')
\ <bar>normal gngf<cr>
This overwrites your gf
to set the search to the filename under cursor
(expand()
), minus leading slash if any (substitute()
) and then run
the normal commands gn
which selects the match and finally the
original gf
.
If you want to save your previous search and restore, you can easily
create a function to wrap this all. Note that I also wrote this is two
lines just because I'm a declared enemy of long lines. But if you just
want to test it remove the \
and write in a single line.
Now your gf
will interpret /file
as file
. Thus if you're on the
correcty directory this will work. If you need to search in a different
directory, the option you're looking for is 'path'
, or 'pa'
for
short. You can give a list of directories to search. Much like Unix
shell's $PATH
. Separated by commas. From the help (be sure to read the
rest yourself, with :h 'pa
):
This is a list of directories which will be searched when using the
gf
, [f
, ]f
, ^Wf
, :find
, :sfind
, :tabfind
and other
commands, provided that the file being searched for has a relative
path (not starting with "/", "./" or "../"). The directories in the
'path' option may be relative or absolute.
In conclusion, to use this in your project, set your 'path'
if needed
as you wish and enable this map. Or run it all automatically in a
:autocmd
or something similar. You aren't changing the root of the
project as you initially suggested, but you're kind of emulating this by
including the desired directory in 'path'
and then forcing gf
to
ignore the leading /
.