DEV Community

t-o-d
t-o-d

Posted on

【Vim】Setting to automatically remove white space at the end of a line when starting and saving

Introduction

  • The following points bothered me when editing in vim and I investigated whether they could be resolved.
    • I have to remove it manually or by command every time because "habit or unintentional" whitespace is put at the end of a line.
    • Sometimes I forget to delete them.
    • In order to prevent deletion, I want to perform automatic deletion not only at the time of saving, but also at the time of starting.
  • So, we'll use the autocmd function to write an automatic deletion setting.

Result

  • Open .vimrc (configuration file)
vim ~/.vimrc
  • Write the following to .vimrc
" auto remove blank
augroup vimrc
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif
augroup END
  • Loading settings in the vim
:source ~/.vimrc
  • As a test, enter a blank space at the end of a line in the file, and if it is automatically deleted when the file is started or saved, it's done.

Link

Top comments (2)

Collapse
 
jingxue profile image
Jing Xue

Nice. A bit gutsy to set up BufRead to do this though. You might open a file only intending to read it, or the file itself is readonly.

Collapse
 
kamekuremaisuke profile image
t-o-d

Thank you for your comments and advice.
You are right.
So use should be taken with caution and I only use it in a limited environment.