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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With