Get the current file path


There are many uses for the current file path and many ways to get it:

  • When typing a command, press %<tab> to complete the current file path.
  • While in insert mode, press <ctrl-r>% to insert the current file path.

But an even more useful capability is yanking, or copying, the current file path into a register or your system clipboard. From there, you can paste it into another buffer or externally into another program. Here’s how to create a simple mapping in your .vimrc to copy the the current file path:

map <leader>l :let @*=expand("%")<CR>

This takes the current relative path to the present buffer and copies it to the * register, which is the system clipboard on most systems. (If you’re on Linux, try swapping the * to a + if you have problems. Read more about the clipboard register.) You can paste this anywhere on your system now or use "*p to paste it in Vim from the star register.

We can expand that a bit, too. It can also be useful to copy the relative path with the current line number appended to the end. Let’s improve our mapping:

map <leader>l :let @*=fnamemodify(expand("%"), ":~:.") . ":" . line(".")<CR>

If it’s more useful to you, there are some variations you can use in place of % in these mappings:

  • Relative path to file: %
  • Absolute path to file: %:p
  • Filename only: %:t
  • Directory name only: %:p:h

I find the relative path with line number the most useful of these. I can paste it to a terminal to run tests, to a Slack message to discuss code, or into my notes file in another Vim buffer. From there, I can press gF to go to that file and line number.

How useful was this tip?

Average rating 4.1 / 5. Vote count: 888

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts