DEV Community

t-o-d
t-o-d

Posted on

4

【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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay