Say I am running Vim and pwd returns
/home/rafid/myproject
And say I am currently editing the file
/home/rafid/myproject/website/editpage.php
Is there any command that returns this for me?
website/editpage.php
That is, the path of the file relative to the current folder.
The Linux relative path the path is defined with the current working directory (for a present relative path, we can use the “pwd” command).
Sometimes, you might want to view the full path of the file. To do that, press 1 followed by Ctrl-G . The full path of the file is displayed in the command line at the bottom.
Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With