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
.)
As Adam pointed out the comments, this can be shortened to:
:echo expand("%:~:.")
Reference: :h expand<Tab>
and :h fnamem<Tab>
If you are limited for space (e.g. using this in your statusline), 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 pathsh<Tab>
<c-r>%
in insert mode to insert the current file name. – Boabdil