Renaming the current file in Vim

前端 未结 21 728
轻奢々
轻奢々 2021-01-29 17:15

How should I rename my current file in Vim?

For example:

  • I am editing person.html_erb_spec.rb
  • I would like it renamed to person
21条回答
  •  庸人自扰
    2021-01-29 17:48

    Short, secure, without plugin:

    :sav new_name
    :!rm #  // or !del # for windows
    

    control + R, # will instantly expand to an alternate-file (previously edited path in current window) before pressing Enter. That allows us to review what exactly we're going to delete. Using pipe | in such a case is not secure, because if sav fails for any reason, # will still point to another place (or to nothing). That means !rm # or delete(expand(#)) may delete completely different file! So do it by hand carefully or use good script (they are mentioned in many answers here).

    Educational

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

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

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

    Security test 1: What does:Rename without argument?

    Yes, it deletes file hidden in '#' !

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

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

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

    E471: Argument required

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

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

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

    notes

    • !rm # is better than !rm old_name -> you don't need remember the old name

    • !rm # 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 (#)

提交回复
热议问题