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

最新文章

  1. c++2008 并行配置文件和获取字典的所有key的方法
  2. mysql 创建索引和删除索引
  3. CentOS 7 程序自启动的问题
  4. bootstrap深入理解之格子布局
  5. 常见浏览器兼容问题、盒模型2种模式以及css hack知识讲解
  6. this关键字的使用
  7. 我的权限系统设计实现MVC4 + WebAPI + EasyUI + Knockout(二)菜单导航
  8. commonJS — 函数操作(for Function)
  9. MyBatis执行过程显示SQL语句的log4j配置
  10. gitlb gerrit jenkins CI整合调试
  11. 颜色空间转换 cvtColor()[OpenCV 笔记13]
  12. TEXT文本编辑框3 点击按钮添加文本至文本输入框
  13. JMM内存管理
  14. YII使用PHPExcel导入Excel文件的方法
  15. 使用 Http 的 Post 方式与网络交互通信
  16. 7、Kafka、AMQ、RabbitMQ对比
  17. Django-认证系统
  18. 20155310 Exp6 信息收集与漏洞扫描
  19. 【转】把Git Repository建到U盘上去
  20. elasticsearch安装指导(new)

热门文章

  1. [R]R的工作流
  2. Android &amp; iOS 第三方 Crash ANR 捕捉上传
  3. Java中集合Set的用法
  4. git 设置多项目实现多账号登陆
  5. [BZOJ2793][Poi2012]Vouchers
  6. HDU-2084 数塔 经典dp,水
  7. Timestame类型和String 类型的转化
  8. 在Eclipse中在线安装Emmet和图文使用教程
  9. JAVA复制网络图片到本地
  10. PHP如何关闭notice级别的错误提示