DEV Community

t-o-d
t-o-d

Posted on

【Vim】Setting to make renaming a file during editing easier with a shortcut

Introduction

  • When I want to do file renaming even when editing vim, I was wondering if it is possible because of the following points.
    • I don't want to use a long command, but a shortcut using key bindings.
    • If I forget to save a command like :w, I want to save it automatically.
    • I want to perform a process interactively.
  • So, I'll write a simple setting for renaming with the Leader.

Result

  1. Open .vimrc (configuration file)
vim ~/.vimrc
  1. Write the following to .vimrc.
" setting leader
" Use 「Space + other keys」.
let mapleader = "\<Space>"

" Calling a renaming function
" Enables the renaming process in the vim with 「space + n」.
map <leader>n :call RenameCurrentFile()<cr>

" Define the renaming function
function! RenameCurrentFile()
  let old = expand('%')
  let new = input('NewFileName: ', old , 'file')
  if new != '' && new != old
    exec ':saveas ' . new
    exec ':silent !rm ' . old
    redraw!
  endif
endfunction
  1. Loading settings in the vim
:source ~/.vimrc
  1. As a test, open the file you want to change with vim, press "spacebar + n" to change it as follows, and if it's OK, it's done.

test

Link

Top comments (1)

Collapse
 
axiol profile image
Arnaud Delante •

That's quite helpful! And yes, everyone should have space as a leader key 😀