VIM: optional line range for command / function

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

 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 spaces for a visually selected range of lines. However, when I just call :RT , it only works with the current line. However, I want to apply the command to the entire buffer. How can this be achieved?

+6
source share
3 answers

If you do not give range , the command with range will apply to the current line. If you want to do this on the entire buffer, use :%RT or :1,$RT

What you can do to make the entire default buffer:

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

detail:

 :h command-range 

then you will see:

 Possible attributes are: -range Range allowed, default is current line -range=% Range allowed, default is whole file (1,$) -range=NA count (default N) which is specified in the line number position (like |:split|); allows for zero line number. -count=NA 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 information, why not just call vim-build in the command :[range]s to make a replacement? then you can save these lines getline , setline , also loop .

+11
source

In the end, I went with this much simpler solution, which also retains the cursor position:

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

Thanks for the @Kent suggestions!

+1
source
 command! TrimAllWhitespace %s/\s\+$// 
0
source

All Articles