百度首页 | 百度空间
 
查看文章
 
Vim Tips - 处理行尾的空格以及文件尾部的多余空行
2007-03-12 04:49 P.M.

打开或者关闭文件时,自动删除行尾的空格。 另外提供了一个 CleanupBuffer 函数,这个函数也提供类似的功能,此外还提供了删除文件尾部空格的能力,参数的意思就是在尾部保留几个空行,不过并没有加入自动命令,也就是说不会自动执行,而是绑定了一个热键 F2


"Automatically remove trailing spaces when saving a file.
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif

"Remove indenting on empty line
map <F2> :w<CR>:call CleanupBuffer(1)<CR>:noh<CR>
function! CleanupBuffer(keep)
    " Skip binary files
    if (&bin > 0)
        return
    endif

    " Remove spaces and tabs from end of every line, if possible
    silent! %s/\s\+$//ge

    " Save current line number
    let lnum = line(".")

    " number of last line
    let lastline = line("$")
    let n        = lastline

    " while loop
    while (1)
        " content of last line
        let line = getline(n)

        " remove spaces and tab
        if (!empty(line))
            break
        endif

        let n = n - 1
    endwhile

    " Delete all empty lines at the end of file
    let start = n+1+a:keep
    if (start < lastline)
        execute n+1+a:keep . "," . lastline . "d"
    endif

    " after clean spaces and tabs, jump back
    exec "normal " . lnum . "G"
endfunction



Auto posted by Wicklow

类别:默认分类 | 添加到搜藏 | 浏览() | 评论 (3)
 
最近读者:
 
网友评论:
1
2007-03-14 00:22 A.M.
这里有个 BUG,不过不影响使用:

start < lastline,改成 <= ,否则当剩余 keep+1 行的时候,会比预期的多一行。
 
2
2008-03-23 06:25 P.M.
这怎么用呢??没讲解一下使用方法??
 
3
2008-03-23 06:26 P.M.
这怎么用呢??没讲解一下使用方法??
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码:
 

     

©2008 Baidu