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

例如:

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

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


当前回答

另一种方法是只使用netrw,它是vim的原生部分。

:e path/to/whatever/folder/

然后还有删除、重命名等选项。

下面是打开netrw到你正在编辑的文件文件夹的键图:

map <leader>e :e <C-R>=expand("%:p:h") . '/'<CR><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命令可以帮助您快速重命名文件。

你也可以使用netw

explore命令在打开文件的目录中打开netrw

:E

将光标移到需要重命名的文件上:

R

输入新名字,回车,按y。

在编辑时写入文件-:w newname -以创建一个副本。 开始编辑新副本-:e#。 (可选)删除旧副本-:!rm oldname。

在Windows上,可选的第三步略有变化:

(可选)删除旧的Windows副本-:!德尔oldname。

在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>

如果文件已经保存:

:!mv {file location} {new file location}
:e {new file location}

例子:

:!mv src/test/scala/myFile.scala src/test/scala/myNewFile.scala
:e src/test/scala/myNewFile.scala

权限要求:

:!sudo mv src/test/scala/myFile.scala src/test/scala/myNewFile.scala

保存为:

:!mv {file location} {save_as file location}
:w
:e {save_as file location} 

Windows未验证

:!move {file location} {new file location}
:e {new file location}