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

例如:

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

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


当前回答

短,安全,无插件:

:sav new_name
:!rm <C-R>#  // or !del <C-R># for windows

control + R, #将立即展开到一个备用文件(先前在当前窗口中编辑的路径),然后按Enter。这样我们就可以查看要删除的内容。 在这种情况下使用管道|是不安全的,因为如果sav因任何原因失败,#仍将指向另一个地方(或不指向任何地方)。这意味着!rm #或delete(expand(#))可能会删除完全不同的文件! 所以要小心地手工或使用好的脚本(在这里的许多答案中都提到了它们)。

教育

...或者尝试自己构建一个函数/命令/脚本。从简单的事物开始:

command! -nargs=1 Rename saveas <args> | call delete(expand('#')) | bd #

在vimrc重载后,只需键入:重命名new_filename。 这个命令有什么问题?

安全测试1:干什么:不带参数地重命名?

是的,它删除隐藏在“#”中的文件!

解决方法:你可以用eg。条件或try语句:

command! -nargs=1 Rename try | saveas <args> | call delete(expand('#')) | bd # | endtry

安全测试一: :Rename(不带参数)将抛出一个错误:

E471:必需参数

安全测试二: 如果名字和之前的一样怎么办?

安全测试三: 如果文件的位置与实际位置不同怎么办?

自己修理。 为了可读性,你可以这样写:

function! s:localscript_name(name):
  try
    execute 'saveas ' . a:name
    ...
  endtry
endfunction
command! -nargs=1 Rename call s:localscript_name(<f-args>)

笔记

!rm # is better than !rm old_name -> you don't need remember the old name !rm <C-R># is better than !rm # when do it by hand -> you will see what you actually remove (safety reason) !rm is generally not very secure... mv to a trash location is better call delete(expand('#')) is better than shell command (OS agnostic) but longer to type and impossible to use control + R try | code1 | code2 | tryend -> when error occurs while code1, don't run code2 :sav (or :saveas) is equivalent to :f new_name | w - see file_f - and preserves undo history expand('%:p') gives whole path of your location (%) or location of alternate file (#)

其他回答

这样怎么样(经过杰克的建议改进):

:exe "!mv % newfilename" | e newfilename

我建议:从tpope的eunuch(太监)来命名这个。

它还包括一系列其他方便的命令。

Rename命令目前定义如下(检查repo是否有更新!):

command! -bar -nargs=1 -bang -complete=file Rename :
  \ let s:file = expand('%:p') |
  \ setlocal modified |
  \ keepalt saveas<bang> <args> |
  \ if s:file !=# expand('%:p') |
  \   call delete(s:file) |
  \ endif |
  \ unlet s:file

:h rename()是迄今为止最简单、最干净的方法。 就叫它吧 :调用重命名("oldname", "newnane")

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

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

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>