在Vim中重命名当前文件。

时间:2021-03-30 19:19:41

How should I rename my current file in Vim?

如何在Vim中重命名当前文件?

For example:

例如:

  • I am editing person.html_erb_spec.rb
  • 我编辑person.html_erb_spec.rb
  • I would like it renamed to person.haml_spec.rb
  • 我想把它重命名为person.haml_spec.rb。
  • I would like to continue editing person.haml_spec.rb
  • 我想继续编辑person.haml_spec.rb。

How would I go about doing this, elegantly?

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

19 个解决方案

#1


81  

There's a little plugin that let's you do this.

有一个小插件让你做这个。

#2


364  

The command is called :saveas, but unfortunately it will not delete your old file, you'll have to do that manually. see :help saveas for more info.

命令被调用:saveas,但不幸的是它不会删除旧文件,您必须手动执行。参见:帮助saveas了解更多信息。

EDIT:

编辑:

Most vim installations have an integrated file explorer, which you can use for such operations. Try :Explore in command mode (I would actually map that to a function key, it's very handy). You can rename files with R or delete them with D, for example. But pressing <F1> in the explorer will give you a better overview.

大多数vim安装都有一个集成的文件资源管理器,您可以使用它来进行此类操作。尝试:在命令模式下进行探索(我将把它映射到一个函数键,这非常方便)。例如,您可以用R重命名文件或用D删除它们。但是在浏览器中按下 会给你一个更好的概述。

#3


119  

If you use git and already have the tpope's plugin fugitive.vim then simply:

如果你使用git,并且已经有了tpope的插件。vim那么简单:

:Gmove newname

This will:

这将:

  1. Rename your file on disk.
  2. 在磁盘上重命名文件。
  3. Rename the file in git repo.
  4. 将文件重命名为git repo。
  5. Reload the file into the current buffer.
  6. 将文件重新加载到当前缓冲区中。
  7. Preserve undo history.
  8. 保留撤销历史。

If your file was not yet added to a git repo then first add it:

如果您的文件还没有添加到一个git repo,那么首先添加它:

:Gwrite

#4


61  

  • Write the file while editing - :w newname - to create a copy.
  • 在编辑-:w newname -创建一个副本的同时写入文件。
  • Start editing the new copy - :e#.
  • 开始编辑新的拷贝-:e#。
  • (Optionally) remove the old copy - :!rm oldname.
  • (可选)删除旧副本-:!rm oldname。

On Windows, the optional 3rd step changes a little:

在Windows上,可选的第3步改变了一点:

  • (Optionally) remove old Windows copy - :!del oldname.
  • (可选)删除旧的Windows拷贝-:!德尔oldname。

#5


56  

I'm doing it with NERDTree plugin:

我使用NERDTree插件:

:NERDTreeFind

then press m

然后按米

And next you can choose between delete, copy, move, etc...

然后你可以在删除,复制,移动,等等之间进行选择。

#6


26  

I'd recommend :Rename from tpope's eunuch for this.

我建议:从tpope的宦官那里重新命名。

It also includes a bunch of other handy commands.

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

The Rename command is defined as follows therein currently (check the repo for any updates!):

重命名命令的定义如下所示(检查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

#7


23  

If the file is already saved:

如果文件已经保存:

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

Example:

例子:

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

Permission Requirements:

权限要求:

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

Save As:

保存为:

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


For Windows Unverified

对于Windows未经证实的

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

#8


21  

You can also do it using netrw

你也可以使用netrw。

The explore command opens up netrw in the directory of the open file

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

:E

Move the cursor over the file you want to rename:

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

R

Type in the new name, press enter, press y.

输入新名称,按enter键,按y键。

#9


17  

sav person.haml_spec.rb | call delete(expand('#'))

#10


11  

Short, secure, without plugin:

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

control + R, # will show what exactly we have to delete before wipeout the World... Using pipe | in such a case is not secure, because if sav fails for any reason that alternate filename # not changes, !rm # or delete(expand(#)) will delete completly different file! So. Do it by hand carefully or use good script (they are mentioned in many answers here).

控制+ R, #将会显示我们必须删除的内容,然后在世界范围内…在这样的情况下使用管道|是不安全的,因为如果因为任何原因而没有更改,那么!rm #或delete(扩展(#))将删除完全不同的文件!所以。小心使用或使用好的脚本(在这里的许多答案中都有提及)。

Educational

...or try build a function/command/script yourself. Start from sth simple like:

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

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

after vimrc reload, just type :Rename new_filename. What is the problem with this command?

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

Security test 1: What does:Rename without argument?

安全性测试1:没有参数的重命名?

Yes, it deletes file hidden in '#' !

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

Solution: you can use eg. conditions or try statement like that:

解决方法:你可以用eg。条件或试述如下:

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

Security test 1: :Rename (without argument) will throw an error:

安全测试1::重命名(没有参数)会抛出一个错误:

E471: Argument required

E471:参数要求

Security test 2: What if the name will be the same like previous one?

安全性测试2:如果名称与之前的名称相同,该怎么办?

Security test 3: What if the file will be in different location than your actual?

安全性测试3:如果文件的位置与实际的不同,会怎么样?

Fix it yourself. For readability you can write it in this manner:

修复它自己。为了便于阅读,你可以这样写:

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

notes

笔记

  • !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 #是最好的!当你用手->时,你会看到你实际移除的东西(安全原因)

  • !rm is generally not very secure... mv to a trash location is better

    !rm通常不太安全……mv到垃圾地点比较好。

  • call delete(expand('#')) is better than shell command (OS agnostic) but longer to type and impossible to use control + R

    调用delete(扩展('#'))比shell命令(OS agnostic)好,但类型更长,无法使用control + R。

  • try | code1 | code2 | tryend -> when error occurs while code1, don't run code2

    当code1出现错误时,请尝试| code1 | code2| tryend ->,不要运行code2。

  • :saveas is equivalent to :f new_name | w - see file_f

    :saveas等价于:f new_name | w -见file_f。

  • expand('%:p') gives whole path of your location (%) or location of alternate file (#)

    扩展('%:p')给出位置的整个路径(%)或替换文件的位置(#)

#11


10  

There’s a function in Gary Bernhardt’s .vimrc that handles this.

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

#12


7  

How about this (improved by Jake's suggestion):

这个(由杰克的建议改进):

:exe "!mv % newfilename" | e newfilename

#13


6  

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

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

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.

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

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

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

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:

如果您想要使用快速命令来重命名文件,请在~/中添加一个新文件。vim/插件有以下内容:

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

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

命令重命名将帮助您快速重命名一个文件。

#14


5  

There's a sightly larger plugin called vim-eunuch by Tim Pope that includes a rename function as well as some other goodies (delete, find, save all, chmod, sudo edit, ...).

蒂姆·波普(Tim Pope)设计了一个更大的插件,名为vim-eunuch,它包括一个重命名功能和其他一些东西(删除、查找、保存所有、chmod、sudo编辑、…)。

To rename a file in vim-eunuch:

在vim-eunuch中重命名文件:

:Move filename.ext

:请确保移动

Compared to rename.vim:

rename.vim相比:

:rename[!] filename.ext

:重命名!)请

Saves a few keystrokes :)

节省几个按键:)

#15


3  

You can also use :f followed by :w

你也可以使用:f后跟:w。

#16


2  

I don't know if this is the "easiest" method, but assuming you've already saved your file (:w) I would invoke the shell (:sh) and do a simple cp foo foo.bak To go back to editor use Ctrl-D/Exit. Useful list of vi editor commands on this link

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

#17


1  

This little script isn't perfect (the extra carriage-return you have to press) but it get's the job done.

这个小脚本并不是完美的(你需要按下额外的回车键),但是任务完成了。

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>

#18


0  

Another way is to just use netrw, which is a native part of vim.

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

:e path/to/whatever/folder/

Then there are options to delete, rename, etc.

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

Here's a keymap to open netrw to the folder of the file you are editing:

这是一个打开netrw文件夹的keymap,它是你正在编辑的文件的文件夹:

map <leader>e :e <C-R>=expand("%:p:h") . '/'<CR><CR>

#19


0  

:sav newfile | !rm #

:新文件| !

Note that it does not remove the old file from the buffer list. If that's important to you, you can use the following instead:

注意,它不会从缓冲区列表中删除旧文件。如果这对你很重要,你可以用下面的方法:

:sav newfile | bd# | !rm #

:新文件| bd# | !

#1


81  

There's a little plugin that let's you do this.

有一个小插件让你做这个。

#2


364  

The command is called :saveas, but unfortunately it will not delete your old file, you'll have to do that manually. see :help saveas for more info.

命令被调用:saveas,但不幸的是它不会删除旧文件,您必须手动执行。参见:帮助saveas了解更多信息。

EDIT:

编辑:

Most vim installations have an integrated file explorer, which you can use for such operations. Try :Explore in command mode (I would actually map that to a function key, it's very handy). You can rename files with R or delete them with D, for example. But pressing <F1> in the explorer will give you a better overview.

大多数vim安装都有一个集成的文件资源管理器,您可以使用它来进行此类操作。尝试:在命令模式下进行探索(我将把它映射到一个函数键,这非常方便)。例如,您可以用R重命名文件或用D删除它们。但是在浏览器中按下 会给你一个更好的概述。

#3


119  

If you use git and already have the tpope's plugin fugitive.vim then simply:

如果你使用git,并且已经有了tpope的插件。vim那么简单:

:Gmove newname

This will:

这将:

  1. Rename your file on disk.
  2. 在磁盘上重命名文件。
  3. Rename the file in git repo.
  4. 将文件重命名为git repo。
  5. Reload the file into the current buffer.
  6. 将文件重新加载到当前缓冲区中。
  7. Preserve undo history.
  8. 保留撤销历史。

If your file was not yet added to a git repo then first add it:

如果您的文件还没有添加到一个git repo,那么首先添加它:

:Gwrite

#4


61  

  • Write the file while editing - :w newname - to create a copy.
  • 在编辑-:w newname -创建一个副本的同时写入文件。
  • Start editing the new copy - :e#.
  • 开始编辑新的拷贝-:e#。
  • (Optionally) remove the old copy - :!rm oldname.
  • (可选)删除旧副本-:!rm oldname。

On Windows, the optional 3rd step changes a little:

在Windows上,可选的第3步改变了一点:

  • (Optionally) remove old Windows copy - :!del oldname.
  • (可选)删除旧的Windows拷贝-:!德尔oldname。

#5


56  

I'm doing it with NERDTree plugin:

我使用NERDTree插件:

:NERDTreeFind

then press m

然后按米

And next you can choose between delete, copy, move, etc...

然后你可以在删除,复制,移动,等等之间进行选择。

#6


26  

I'd recommend :Rename from tpope's eunuch for this.

我建议:从tpope的宦官那里重新命名。

It also includes a bunch of other handy commands.

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

The Rename command is defined as follows therein currently (check the repo for any updates!):

重命名命令的定义如下所示(检查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

#7


23  

If the file is already saved:

如果文件已经保存:

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

Example:

例子:

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

Permission Requirements:

权限要求:

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

Save As:

保存为:

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


For Windows Unverified

对于Windows未经证实的

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

#8


21  

You can also do it using netrw

你也可以使用netrw。

The explore command opens up netrw in the directory of the open file

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

:E

Move the cursor over the file you want to rename:

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

R

Type in the new name, press enter, press y.

输入新名称,按enter键,按y键。

#9


17  

sav person.haml_spec.rb | call delete(expand('#'))

#10


11  

Short, secure, without plugin:

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

control + R, # will show what exactly we have to delete before wipeout the World... Using pipe | in such a case is not secure, because if sav fails for any reason that alternate filename # not changes, !rm # or delete(expand(#)) will delete completly different file! So. Do it by hand carefully or use good script (they are mentioned in many answers here).

控制+ R, #将会显示我们必须删除的内容,然后在世界范围内…在这样的情况下使用管道|是不安全的,因为如果因为任何原因而没有更改,那么!rm #或delete(扩展(#))将删除完全不同的文件!所以。小心使用或使用好的脚本(在这里的许多答案中都有提及)。

Educational

...or try build a function/command/script yourself. Start from sth simple like:

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

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

after vimrc reload, just type :Rename new_filename. What is the problem with this command?

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

Security test 1: What does:Rename without argument?

安全性测试1:没有参数的重命名?

Yes, it deletes file hidden in '#' !

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

Solution: you can use eg. conditions or try statement like that:

解决方法:你可以用eg。条件或试述如下:

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

Security test 1: :Rename (without argument) will throw an error:

安全测试1::重命名(没有参数)会抛出一个错误:

E471: Argument required

E471:参数要求

Security test 2: What if the name will be the same like previous one?

安全性测试2:如果名称与之前的名称相同,该怎么办?

Security test 3: What if the file will be in different location than your actual?

安全性测试3:如果文件的位置与实际的不同,会怎么样?

Fix it yourself. For readability you can write it in this manner:

修复它自己。为了便于阅读,你可以这样写:

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

notes

笔记

  • !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 #是最好的!当你用手->时,你会看到你实际移除的东西(安全原因)

  • !rm is generally not very secure... mv to a trash location is better

    !rm通常不太安全……mv到垃圾地点比较好。

  • call delete(expand('#')) is better than shell command (OS agnostic) but longer to type and impossible to use control + R

    调用delete(扩展('#'))比shell命令(OS agnostic)好,但类型更长,无法使用control + R。

  • try | code1 | code2 | tryend -> when error occurs while code1, don't run code2

    当code1出现错误时,请尝试| code1 | code2| tryend ->,不要运行code2。

  • :saveas is equivalent to :f new_name | w - see file_f

    :saveas等价于:f new_name | w -见file_f。

  • expand('%:p') gives whole path of your location (%) or location of alternate file (#)

    扩展('%:p')给出位置的整个路径(%)或替换文件的位置(#)

#11


10  

There’s a function in Gary Bernhardt’s .vimrc that handles this.

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

#12


7  

How about this (improved by Jake's suggestion):

这个(由杰克的建议改进):

:exe "!mv % newfilename" | e newfilename

#13


6  

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

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

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.

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

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

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

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:

如果您想要使用快速命令来重命名文件,请在~/中添加一个新文件。vim/插件有以下内容:

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

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

命令重命名将帮助您快速重命名一个文件。

#14


5  

There's a sightly larger plugin called vim-eunuch by Tim Pope that includes a rename function as well as some other goodies (delete, find, save all, chmod, sudo edit, ...).

蒂姆·波普(Tim Pope)设计了一个更大的插件,名为vim-eunuch,它包括一个重命名功能和其他一些东西(删除、查找、保存所有、chmod、sudo编辑、…)。

To rename a file in vim-eunuch:

在vim-eunuch中重命名文件:

:Move filename.ext

:请确保移动

Compared to rename.vim:

rename.vim相比:

:rename[!] filename.ext

:重命名!)请

Saves a few keystrokes :)

节省几个按键:)

#15


3  

You can also use :f followed by :w

你也可以使用:f后跟:w。

#16


2  

I don't know if this is the "easiest" method, but assuming you've already saved your file (:w) I would invoke the shell (:sh) and do a simple cp foo foo.bak To go back to editor use Ctrl-D/Exit. Useful list of vi editor commands on this link

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

#17


1  

This little script isn't perfect (the extra carriage-return you have to press) but it get's the job done.

这个小脚本并不是完美的(你需要按下额外的回车键),但是任务完成了。

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>

#18


0  

Another way is to just use netrw, which is a native part of vim.

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

:e path/to/whatever/folder/

Then there are options to delete, rename, etc.

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

Here's a keymap to open netrw to the folder of the file you are editing:

这是一个打开netrw文件夹的keymap,它是你正在编辑的文件的文件夹:

map <leader>e :e <C-R>=expand("%:p:h") . '/'<CR><CR>

#19


0  

:sav newfile | !rm #

:新文件| !

Note that it does not remove the old file from the buffer list. If that's important to you, you can use the following instead:

注意,它不会从缓冲区列表中删除旧文件。如果这对你很重要,你可以用下面的方法:

:sav newfile | bd# | !rm #

:新文件| bd# | !