当前位置: 动力学知识库 > 问答 > 编程问答 >

VIM: Optional line range for command / function

问题描述:

I have this in my .vimrc to remove trailing whitespace:

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()

This allows me to call :'<,'>RT to remove trailing whitespace for a visually selected range of lines. When i just call :RT, however, it only operates on the current line. What i want though, is to apply the command to the entire buffer. How can this be achieved?

网友答案:

if you don't give range, the command with range will apply on current line. If you want to do it on whole buffer, use :%RT or :1,$RT

What you could do to make whole buffer as default range is:

command -range=% RT  <line1>,<line2>call RemoveTrailingWhitespace()

detail:

:h command-range

then you see:

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

one comment/question to your function

if you have range info, why not just call vim-build in command :[range]s to do the substitution? then you could save those lines getline, setline, also the loop.

网友答案:

In the end i went with this much simpler solution, which also keeps the cursor position:

command -range=% RemoveTrailingWhitespace <line1>,<line2>s/\(\s\| \)\+$// | norm! ``
command -range=% RT                       <line1>,<line2>RemoveTrailingWhitespace

Thanks for the suggestions @Kent!

网友答案:
command! TrimAllWhitespace %s/\s\+$//
分享给朋友:
您可能感兴趣的文章:
随机阅读: