2010年2月15日星期一

Vim Tips-处理行尾的空格以及文件尾部的多余空行

转载:
Vim Tips-处理行尾的空格以及文件尾部的多余空行
打开或者关闭文件时,自动删除行尾的空格。另外提供了一个 CleanupBuffer 函数,这个函数也提供类似的功能,此外还提供了删除文件尾部空格的能力,参数的意思就是在尾部保留几个空行,不过并没有加入自动命令,也就是说不会自动执行,而是绑定了一个热键 F2。


"Automatically remove trailing spaces when saving a file.
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif

"Remove indenting on empty line
map <F2> :w<CR>:call CleanupBuffer(1)<CR>:noh<CR>
function! CleanupBuffer(keep)
" Skip binary files
if (&bin > 0)
return
endif

" Remove spaces and tabs from end of every line, if possible
silent! %s/\s\+$//ge

" Save current line number
let lnum = line(".")

" number of last line
let lastline = line("$")
let n = lastline

" while loop
while (1)
" content of last line
let line = getline(n)

" remove spaces and tab
if (!empty(line))
break
endif

let n = n - 1
endwhile

" Delete all empty lines at the end of file
let start = n+1+a:keep
if (start < lastline)
execute n+1+a:keep . "," . lastline . "d"
endif

" after clean spaces and tabs, jump back
exec "normal " . lnum . "G"
endfunction

--
陈永林 <vnresearch@gmail.com>

没有评论: