简体   繁体   中英

Vim: how to refresh buffer to point to new filepath

I was wondering if it was possible to refresh an open buffer to point to a new path if I've modified it.

Ex:

  1. Open ./dest1/foo in vim
  2. Move foo to ./dest2/foo
  3. Update open buffer to reflect new path ./dest2/foo instead of read/writing to old path

Yes, its possible but not without a minor disruption.

  1. Open ./dest1/foo in vim
  2. Get into vim's command mode by pressing ":"
  3. Issue the following command at the prompt-- !mv '%:p' "./dest2/foo"

You may now get a message that 'File "foo" is no longer available. Press ENTER or type command to continue'. Press ENTER. Vim now re-opens the file from the new location.

The next function does what you need:

function Saveas(newfile)                                                 
    let oldfile=expand("%:p")                                            
    silent! exe 'saveas!' fnameescape(a:newfile)                         
    bd #                                                                 
    exe 'cd ' . expand('%:h')                                            
    call delete(oldfile)                                                 
endfunction                                                              
command! -nargs=1 -complete=dir -complete=file Saveas call Saveas('<args>')

How to use it: If currently editing ./foo , you can do :Saveas ./dest1/foo (assuming dest1 directory exists). Now the current buffer will be ./dest/foo whereas foo will be deleted from the buffer list. Also the current directory ( pwd ) will be updated to ./dest .

Note : File foo will be removed. A new file ./dest1/foo with the contents of foo will be created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM