Vim 删除文件尾部的多余空行

May 19th, 2007 | Filed under Vim

恩… 删文件尾部的空格比较麻烦,好像没有现成的 pattern 拿来 COPY… 很多牛人都是在 Linux/Unix/Cygwin 下调用外部程序来做的,比如那个 sed, 这些 Linux/Unix 的程序偶一点也不会用,不过没关系啊,我自己写呵!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"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

把上面的代码加入到你的 _vimrc 配置文件中去,每次想 Clean Buffer 的时候,按下 F2 就可以啦!Very Simple!

Tags:
Comments are closed.