Renaming the current file in Vim

前端 未结 21 687
轻奢々
轻奢々 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:37

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

    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>
    
    0 讨论(0)
  • 2021-01-29 17:42

    For renaming existing file without using plugins you should use command

    :Explore
    

    This command allow you explore files in.directory, delete or rename them. than you should navigate to neccessary file in explorer than type R command which will allow you to rename file name

    0 讨论(0)
  • 2021-01-29 17:42

    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>
    
    0 讨论(0)
  • 2021-01-29 17:43

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

    :Gmove newname
    

    This will:

    1. Rename your file on disk.
    2. Rename the file in git repo.
    3. Reload the file into the current buffer.
    4. Preserve undo history.

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

    :Gwrite
    
    0 讨论(0)
  • 2021-01-29 17:44

    You can also do it using netrw

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

    :E
    

    Move the cursor over the file you want to rename:

    R
    

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

    0 讨论(0)
  • 2021-01-29 17:44

    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

    0 讨论(0)
提交回复
热议问题