Yank file name / path of current buffer in Vim

Viewed 57606

Assuming the current buffer is a file open for edit, so :e does not display E32: No file name.

I would like to yank one or all of:

  • The file name exactly as show on the status line, e.g. ~\myfile.txt
  • A full path to the file, e.g. c:\foo\bar\myfile.txt
  • Just the file name, e.g. myfile.txt
11 Answers

TL;DR

:let @" = expand("%")>

this will copy the file name to the unamed register, then you can use good old p to paste it. and of course you can map this to a key for quicker use.

:nmap cp :let @" = expand("%")<cr>

you can also use this for full path

:let @" = expand("%:p")

Explanation

Vim uses the unnamed register to store text that has been deleted or copied (yanked), likewise when you paste it reads the text from this register.

Using let we can manually store text in the register using :let @" = "text" but we can also store the result of an expression.

In the above example we use the function expand which expands wildcards and keywords. in our example we use expand('%') to expand the current file name. We can modify it as expand('%:p') for the full file name.

See :help let :help expand :help registers for details

Almost what you're asking for, and it might do: Ctrl+R % pulls the current filename into where you are (command prompt, edit buffer, ...). See this Vim Tip for more.

Answer tested on Neovim/Ubunutu.

:let @+=@%

From what I can tell, the % register already contains the relative filepath, so it's as simple as moving the contents of the % register to whatever register represents your favourite clipboard.

This SO answer deals with copying from one register to another

Seems pretty straightforward to me. No need for any hard-to-remember expand() stuff.

If you're on terminal vim, and want to copy to system clipboard: For something easy to remember, that doesn't requiring predefined mappings/functions:

:!echo %

prints the current buffer's relative path to terminal, where you can copy it and then ENTER back to vim. (as already mentioned, you can postfix the command with :p or :t to get absolute or basename, if you can remember that....)

I put it in my vimc:

nnoremap yl :let @" = expand("%:p")<cr>

If you wish to simply yank the path of the currently open file name then simply press:

  1. step1: ctrl + g [You will see the entire root path at the bottom of window]
  2. step2: select the path with the mouse
  3. step3: Paste with the middle mouse wheel
Related