按說,檔案結尾沒有eol是一種不正確的檔案格式,但是許多windows下的軟體喜歡這樣。這個我們暫且不討論,先看看去除eol的需求是怎麼來的:
php檔案結尾如果是 ?>, 並且這個php被include了,並且......(這個條件我忘記了,總之我還沒有碰見過也不想碰),那麼?>後面的分行符號會被輸出到頁面上。
其實這個問題很好解決,php檔案可以不用?>結尾,官方都這麼推薦的。然而,偏偏人家要求你用?>結尾,並且不許有eol,怎麼辦呢?
下面是我找到了一些解決方案:
方法一:
autocmd BufWritePre *.php setlocal binary autocmd BufWritePre *.php setlocal noeol autocmd BufWritePost *.php setlocal nobinary
缺點,有個副作用。設定了bin後,檔案自動用unix格式儲存,這個會有很多麻煩,例如,svn提交會與別人衝突,svn衝突當然也可以用svn的方式解決,但是不在本文探討範圍之內。
方法二:
fun! a:remove_eol() silent !~/bin/noeol <afile>endfunautocmd BufWritePost *.php call a:remove_eol()
其實這就是自己寫了個小工具用來移除eol。缺點呢,需要unix環境支援,普通windows環境上沒有那麼方便讓你隨便弄個指令碼在上面。
方法三:
參見 http://vim.wikia.com/wiki/Preserve_missing_end-of-line_at_end_of_text_files
不過這個方法在較新的vim版本上不好用,需要改一個地方,我把修改完的貼出來:
" Preserve noeol (missing trailing eol) when saving file. In order" to do this we need to temporarily 'set binary' for the duration of" file writing, and for DOS line endings, add the CRs manually." For Mac line endings, also must join everything to one line since it doesn't" use a LF character anywhere and 'binary' writes everything as if it were Unix." This works because 'eol' is set properly no matter what file format is used," even if it is only used when 'binary' is set.augroup automatic_noeolau!autocmd BufRead *.php setlocal noeol au BufWritePre *.php call TempSetBinaryForNoeol()au BufWritePost *.php call TempRestoreBinaryForNoeol()fun! TempSetBinaryForNoeol() let s:save_binary = &binary if ! &eol && ! &binary setlocal binary if &ff == "dos" || &ff == "mac" undojoin | silent 1,$-1s#$#\^M endif if &ff == "mac" let s:save_eol = &eol undojoin | %join! " mac format does not use a \n anywhere, so don't add one when writing in " binary (uses unix format always) setlocal noeol endif endifendfunfun! TempRestoreBinaryForNoeol() if ! &eol && ! s:save_binary if &ff == "dos" undojoin | silent 1,$-1s/\r$/ elseif &ff == "mac" undojoin | %s/\r/\r/g let &l:eol = s:save_eol endif setlocal nobinary endifendfunaugroup END
和原版的區別就在那個^M的地方,手頭有vim的可以試一下,:%s/$/^M 不管用,變成插入空行了。help: replace可以看到,現在新版本需要加斜杠了。
(註:^M的輸入方法,<Ctrl+V><Ctrl+M>)