Getting relative paths in Vim

Another option would be to write a vim function. Here's my humble attempt:

function! Relpath(filename)
    let cwd = getcwd()
    let s = substitute(a:filename, l:cwd . "/" , "", "")
    return s
endfunction

You call Relpath with any full path name, and it will strip the current directory name from its argument.

For example, try :echo Relpath(expand("%:p")) (the :p modifier asks Vim to return the full path). Obviously, this is not necessary in your case, since % by itself returns relative path. However, it might come in handy in other cases.


Although expand('%') often works, there are rare occasions where it does not. But you can force Vim to always present the relative path by calling fnamemodify:

:echo fnamemodify(expand("%"), ":~:.")

From the manual:

    :.      Reduce file name to be relative to current directory, if
            possible.  File name is unmodified if it is not below the
            current directory.
            For maximum shortness, use ":~:.".

The :~ is optional. It will reduce the path relative to your home folder if possible (~/...). (Unfortunately that only works on your home; it won't turn /home/fred into ~fred if you aren't logged in as fred.)

If you are limited for space, and can manage with "fuzzy" information about where the file is located, then check out pathshorten() which compresses folder names down to one character:

:echo pathshorten('~/.vim/autoload/myfile.vim')
~/.v/a/myfile.vim

Reference: :h fnamem<Tab> and :h pathsh<Tab>