讓VIM存檔時自動去除行尾的空白

PHP規範之一的PSR-2(前輩翻譯)裡面的2.3有規範了一點:

There MUST NOT be trailing whitespace at the end of non-blank lines.
 
意為非空白行的行尾不可有空白
 
要處理這種瑣碎的細節其實很麻煩,尤其code一多、以前又沒按照規定來走現在卻要修正的時候
 
這邊有前輩截錄了一段程式碼可以用來處理這種問題,也順便處理了自動刪除檔案結尾N行的空白行
 

” Remove trailing whitespace when writing a buffer, but not for diff files.
” From: Vigil
function RemoveTrailingWhitespace()
if &ft; != “diff”
let b:curcol = col(“.”)
let b:curline = line(“.”)
silent! %s/s+$//
silent! %s/(s*n)+%$//
call cursor(b:curline, b:curcol)
endif
endfunction
autocmd BufWritePre * call RemoveTrailingWhitespace()

只要寫入vimrc裡面就可以了!


如果不想要自動刪除檔案結尾N行的空白行,請把上面橘色標記的code註解或是拿掉!