我应该如何重命名我的当前文件在Vim?

例如:

我正在编辑person.html_erb_spec.rb 我希望它重命名为person.haml_spec.rb 我想继续编辑person.haml_spec.rb

我该如何优雅地做这件事呢?


当前回答

在Gary Bernhardt的.vimrc中有一个函数处理这个问题。

function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
    exec ':saveas ' . new_name
    exec ':silent !rm ' . old_name
    redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>

其他回答

有一个小插件可以让你这么做。

Vim确实有一个重命名函数,但不幸的是它不保留历史。

在不丢失历史的情况下重命名文件的最简单的操作系统不可知的方法是:

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

Expand ('#:p')返回旧文件的完整路径。

如果你还想从缓冲区列表中删除旧文件,请使用:bd #。

或者创建一个插件

如果希望使用快速命令重命名文件,请在~/下添加一个新文件。Vim /plugin包含以下内容:

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 <SID>rename_file(<f-args>)

Rename命令可以帮助您快速重命名文件。

这个小脚本并不完美(你必须按下额外的回车键),但它完成了工作。

function Rename()
  let new_file_name = input('New filename: ')
  let full_path_current_file = expand("%:p")
  let new_full_path = expand("%:p:h")."/".new_file_name
  bd    
  execute "!mv ".full_path_current_file." ".new_full_path
  execute "e ".new_full_path
endfunction                                                                                                                                                                                                                                 

command! Rename :call Rename()
nmap RN :Rename<CR>

我不知道这是否是“最简单”的方法,但假设你已经保存了你的文件(:w),我会调用shell (:sh)并做一个简单的cp foo foo.bak返回编辑器使用Ctrl-D/Exit。 此链接上的vi编辑器命令的有用列表

要重命名现有文件而不使用插件,您应该使用命令

:Explore

这个命令允许您浏览文件。目录,删除或重命名它们。然后你应该在资源管理器中导航到必要的文件,而不是键入R命令,这将允许你重命名文件名