vim - Simple commands to remove unwanted whitespace

http://vim.wikia.com/wiki/Remove_unwanted_spaces

1. manual command
remove trailing whitespace:
:%s/\s\+$//e
remove heading whitespace:
:%s/^\s\+//e
:%le

2. binding key - press F5 to delete all trailing whitespace
:nnoremap <silent> <F5> :let _s=@/ <Bar> :%s/\s\+$//e <Bar> :let @/=_s <Bar> :nohl <Bar> :unlet _s <CR>

3. Display or remove unwanted whitespace with a script
function ShowSpaces(...)
  let @/='\v(\s+$)|( +\ze\t)'
  let oldhlsearch=&hlsearch
  if !a:0
    let &hlsearch=!&hlsearch
  else
    let &hlsearch=a:1
  end
  return oldhlsearch
endfunction

function TrimSpaces() range
  let oldhlsearch=ShowSpaces(1)
  execute a:firstline.",".a:lastline."substitute ///gec"
  let &hlsearch=oldhlsearch
endfunction

command -bar -nargs=? ShowSpaces call ShowSpaces(<args>)
command -bar -nargs=0 -range=% TrimSpaces <line1>,<line2>call TrimSpaces()
nnoremap <F12>     :ShowSpaces 1<CR>
nnoremap <S-F12>   m`:TrimSpaces<CR>``
vnoremap <S-F12>   :TrimSpaces<CR>

4. Automatically removing all trailing whitespace before saving.
modify vimrc file:
autocmd BufWritePre * %s/\s\+$//e
However, this is a very dangerous autocmd to have as it will always strip trailing whitespace from every file a user saves.
Sometimes, trailing whitespace is desired, or even essential in a file so be careful when implementing this autocmd.

One method to mitigate this issue in a .vimrc file, where trailing whitespace matters, is to change how .vimrc prepends wrapped lines.
For example, add the following into the .vimrc:
set wrap
set linebreak
" note trailing space at end of next line
set showbreak=>\ \ \
Now when saving the .vimrc it will use ">  \" instead of ">   " to prepend wrapped lines.

A user can also specify a particular filetype in an autocmd so that only that filetype will be changed when saving.
The following only changes files with the extension .pl:
autocmd BufWritePre *.pl %s/\s\+$//e
Additionally, a FileType autocommand can be used to restrict the autocmd to certain file types only.
autocmd FileType c,cpp,java,php autocmd BufWritePre <buffer> %s/\s\+$//e

posted @ 2016-11-29 15:14  cnblogist  阅读(224)  评论(0编辑  收藏  举报