我应该如何重命名我的当前文件在Vim?
例如:
我正在编辑person.html_erb_spec.rb 我希望它重命名为person.haml_spec.rb 我想继续编辑person.haml_spec.rb
我该如何优雅地做这件事呢?
我应该如何重命名我的当前文件在Vim?
例如:
我正在编辑person.html_erb_spec.rb 我希望它重命名为person.haml_spec.rb 我想继续编辑person.haml_spec.rb
我该如何优雅地做这件事呢?
当前回答
你也可以使用netw
explore命令在打开文件的目录中打开netrw
:E
将光标移到需要重命名的文件上:
R
输入新名字,回车,按y。
其他回答
在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>
要重命名现有文件而不使用插件,您应该使用命令
:Explore
这个命令允许您浏览文件。目录,删除或重命名它们。然后你应该在资源管理器中导航到必要的文件,而不是键入R命令,这将允许你重命名文件名
如果文件已经保存:
:!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}
如果你使用git并且已经有tpope的插件逃犯。然后简单地Vim:
:Gmove newname
这将:
重命名磁盘上的文件。 在git repo中重命名文件。 将文件重新加载到当前缓冲区中。 保留撤销历史记录。
如果你的文件还没有添加到git repo,那么先添加它:
:Gwrite
短,安全,无插件:
: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 (#)