Yank file name / path of current buffer in Vim

后端 未结 8 1367
死守一世寂寞
死守一世寂寞 2020-12-07 07:26

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:

8条回答
  •  -上瘾入骨i
    2020-12-07 07:47

    If you want to put the current buffer filename in your system-level clipboard, try changing the register to @+:

    " relative path
    :let @+ = expand("%")
    
    " full path
    :let @+ = expand("%:p")
    
    " just filename
    :let @+ = expand("%:t")
    

    Edit 20140421: I commonly use these, so I created some shortcuts. Linux Vims apparently operate slightly differently than Mac Vims, so there is a special case for that as well. If you put the following in your ~/.vimrc:

    " copy current file name (relative/absolute) to system clipboard
    if has("mac") || has("gui_macvim") || has("gui_mac")
      " relative path  (src/foo.txt)
      nnoremap cf :let @*=expand("%")
    
      " absolute path  (/something/src/foo.txt)
      nnoremap cF :let @*=expand("%:p")
    
      " filename       (foo.txt)
      nnoremap ct :let @*=expand("%:t")
    
      " directory name (/something/src)
      nnoremap ch :let @*=expand("%:p:h")
    endif
    
    " copy current file name (relative/absolute) to system clipboard (Linux version)
    if has("gui_gtk") || has("gui_gtk2") || has("gui_gnome") || has("unix")
      " relative path (src/foo.txt)
      nnoremap cf :let @+=expand("%")
    
      " absolute path (/something/src/foo.txt)
      nnoremap cF :let @+=expand("%:p")
    
      " filename (foo.txt)
      nnoremap ct :let @+=expand("%:t")
    
      " directory name (/something/src)
      nnoremap ch :let @+=expand("%:p:h")
    endif
    

    Then for example cf will copy the relative path of the current buffer (the default leader is backslash (\)). I often use these for running commands on a file or doing other things on the command line. I don't really use the last filename / directory name often.

    You might consider more intuitive mappings like cfr for relative, cfa for absolute, cff for just filename, cfd for directory.

提交回复
热议问题