Renaming the current file in Vim

前端 未结 21 1047
轻奢々
轻奢々 2021-01-29 17:15

How should I rename my current file in Vim?

For example:

  • I am editing person.html_erb_spec.rb
  • I would like it renamed to person
21条回答
  •  南笙
    南笙 (楼主)
    2021-01-29 17:56

    Vim does have a rename function, but unfortunately it does not retain the history.

    The easiest OS agnostic way to rename a file without losing the history would be:

    :saveas new_file_name
    :call delete(expand('#:p'))
    

    expand('#:p') returns the full path of the older file.

    Use :bd # if you also want to delete the older file from the buffer list.

    Or create a plugin

    If you want to use a quick command to rename the file, add a new file under ~/.vim/plugin with the following contents:

    function! s:rename_file(new_file_path)
      execute 'saveas ' . a:new_file_path
      call delete(expand('#:p'))
      bd #
    endfunction
    
    command! -nargs=1 -complete=file Rename call rename_file()
    

    The command Rename will help you to quickly rename a file.

提交回复
热议问题