vim裡面如何去掉檔案最後一行的eol

來源:互聯網
上載者:User

按說,檔案結尾沒有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>)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.