我应该如何重命名我的当前文件在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
我该如何优雅地做这件事呢?
当前回答
在编辑时写入文件-:w newname -以创建一个副本。 开始编辑新副本-:e#。 (可选)删除旧副本-:!rm oldname。
在Windows上,可选的第三步略有变化:
(可选)删除旧的Windows副本-:!德尔oldname。
其他回答
短,安全,无插件:
: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 (#)
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命令可以帮助您快速重命名文件。
另一种方法是只使用netrw,它是vim的原生部分。
:e path/to/whatever/folder/
然后还有删除、重命名等选项。
下面是打开netrw到你正在编辑的文件文件夹的键图:
map <leader>e :e <C-R>=expand("%:p:h") . '/'<CR><CR>
这个小脚本并不完美(你必须按下额外的回车键),但它完成了工作。
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>
:sav newfile | !rm #
注意,它不会从缓冲区列表中删除旧文件。如果这对你来说很重要,你可以使用以下方法:
:sav newfile | bd# |