Skip to content

Instantly share code, notes, and snippets.

@kyokley
Last active July 12, 2017 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyokley/944de46ab0b35ef4df14 to your computer and use it in GitHub Desktop.
Save kyokley/944de46ab0b35ef4df14 to your computer and use it in GitHub Desktop.
Trailing whitespace handling in VIM

Trailing whitespace handling in VIM (Buffer Pre-write Hook Part 1)

Introduction

It is a common coding practice to remove trailing whitespace. Below are some suggestions about how to handle it.

Highlighting

Adding the following to your .vimrc will highlight any trailing whitespace:

highlight ExtraWhitespace ctermbg=darkred guibg=darkred ctermfg=yellow guifg=yellow
match ExtraWhitespace /\s\+$/

I've chosen to create a new match group called ExtraWhitespace. Trailing whitespace will be automatically highlighted red.

Removal

It's also possible to automatically remove any whitespace while writing a file.

autocmd BufWritePre * %s/\s\+$//e

Or alternatively, to only apply the auto-command to python files, use the following:

autocmd BufWritePre *.py %s/\s\+$//e

Adding User Intervention

If you're hesitant to have the editor automatically making changes without your knowledge, try this:

function! RaiseExceptionForUnresolvedIssues()
    if search('\s\+$', 'nw') != 0
        throw 'Found trailing whitespace'
    endif
endfunction
autocmd BufWritePre * call RaiseExceptionForUnresolvedIssues()

Again, to apply only to python files, replace the last line with:

autocmd BufWritePre *.py call RaiseExceptionForUnresolvedIssues()

An exception will be thrown when attempting to write any file containing trailing whitespace. Of course, if you really meant to write the file as is, execute:

:noautocmd w

Or,

:noa w

Next steps

Please check out the other gists in the series

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment