VIM:命令/功能的可选行范围

Pat*_*ity 7 vim

我有这个.vimrc删除尾随空格:

function! RemoveTrailingWhitespace()
  for lineno in range(a:firstline, a:lastline)
    let line = getline(lineno)
    let cleanLine = substitute(line, '\(\s\| \)\+$', '', 'e')
    call setline(lineno, cleanLine)
  endfor
endfunction
command -range RemoveTrailingWhitespace <line1>,<line2>call RemoveTrailingWhitespace()
command -range RT                       <line1>,<line2>call RemoveTrailingWhitespace()
Run Code Online (Sandbox Code Playgroud)

这允许我调用:'<,'>RT为视觉选择的行范围删除尾随空格.:RT但是,当我打电话时,它只能在当前行上运行.我想要的是将命令应用于整个缓冲区.怎么能实现这一目标?

Ken*_*ent 12

如果你不给range,那么命令range将适用于当前行.如果要在整个缓冲区上执行此操作,请使用:%RT:1,$RT

将整个缓冲区作为默认范围可以做的是:

command -range=% RT  <line1>,<line2>call RemoveTrailingWhitespace()
Run Code Online (Sandbox Code Playgroud)

详情:

:h command-range
Run Code Online (Sandbox Code Playgroud)

然后你看到:

Possible attributes are:

-range      Range allowed, default is current line
-range=%    Range allowed, default is whole file (1,$)
-range=N    A count (default N) which is specified in the line
        number position (like |:split|); allows for zero line
        number.
-count=N    A count (default N) which is specified either in the line
        number position, or as an initial argument (like |:Next|).
        Specifying -count (without a default) acts like -count=0
Run Code Online (Sandbox Code Playgroud)

对您的功能有一个评论/问题

如果你有范围信息,为什么不直接调用vim-build in命令:[range]s进行替换?那么你可以保存这些线路getline,setline也对loop.