Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: Optional line range for command / function

Tags:

vim

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?

like image 639
Patrick Oscity Avatar asked Apr 23 '13 08:04

Patrick Oscity


1 Answers

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.

like image 141
Kent Avatar answered Nov 15 '22 21:11

Kent