vim里面如何去掉文件最后一行的eol

按说,文件结尾没有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>
endfun
autocmd 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_noeol
au!

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
  endif
endfun

fun! 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
  endif
endfun
augroup END

和原版的区别就在那个^M的地方,手头有vim的可以试一下,:%s/$/^M 不管用,变成插入空行了。help: replace可以看到,现在新版本需要加斜杠了。

(注:^M的输入方法,<Ctrl+V><Ctrl+M>)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值