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

来源:互联网 发布:斯维尔绿色建筑软件 编辑:程序博客网 时间:2024/04/29 05:22

按说,文件结尾没有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>)

原创粉丝点击