简体   繁体   中英

Move File within Vim

Is there a way to move a file within Vim? Eg I opened a file foo/bar.txt in Vim. I know 2 ways to move this file:

First solution:

  1. Delete the buffer with :bd bar.txt
  2. Perform the move on the shell with mv foo/bar.txt foo/bar2.txt
  3. Load the file in vim with :e foo/bar2.txt

Second solution:

  1. Close Vim, so all buffer where closed.
  2. Perform the move on the shell...
  3. Start Vim and load the file.

But these two solutions are embarrassing. I know, there is a plugin for renaming files vim-enuch , but isn't there a Vim way for performing such basic functionality?

You could also use netrw (the default file explorer) rename functionality.

  1. Open netrw with :E
  2. Move your cursor to the line with the file you intend to rename, in this case bar.txt . You move to the file in question using h,j,k,l or you can search for it with / (eg /bar.txt )
  3. Hit R . You will then be prompted for a new filepath. When done entering the filepath hit <CR>
  4. Move your cursor to the new file and open it with <CR>

While this solution may not be as quick as using vim-eunch, it does allow you to see the project's structure as you rename the file. This will also allow you to move multiple files at once.

For further reading run :help netrw-move

There is no atomic way to move a file like that, but this should be close:

function! MoveFile(newspec)
     let old = expand('%')
     " could be improved:
     if (old == a:newspec)
         return 0
     endif
     exe 'sav' fnameescape(a:newspec)
     call delete(old)
endfunction

command! -nargs=1 -complete=file -bar MoveFile call MoveFile('<args>')

Now you could say:

:MoveFile file2.txt

To rename to file2.txt

:MoveFile %.0

to move file2.txt to file2.txt.0

if you're in the bar.txt buffer:

:w bar2.txt
:!rm bar.txt

If bar2.txt already exists in the current directory, use :w! .

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