Reputation: 396
I am trying to write a function to simplify the command to switch windows in Vim.
I have managed to get it to work as :W <argument>
:
function! s:winswitch(...)
let i = 0
while i < argc()
let command = ":wincmd ".a:1
execute command
let i = i + 1
endwhile
endfunction
command! -nargs=+ W call s:winswitch(<f-args>)
This works in making :W l
function as :wincmd l
.
I'm looking for a way for it to execute the commands based on an arbitrary number of arguments such as I can use :W j h
to function as :wincmd j|wincmd h
.
Upvotes: 1
Views: 422
Reputation: 172520
The optional function arguments (...)
are available in the List a:000
, in addition to the separate a:1
, a:2
, ...
You actually don't need to use the length (via a:0
, not argc()
!) and explicit indexing if you switch from :while
to a :for
loop:
for arg in a:000
let command = 'wincmd ' . arg
If for some reason you need to use indexing, I would still prefer :for
:
for i in range(a:0)
let command = 'wincmd ' . a:000[i]
Upvotes: 3
Reputation: 94417
The problem in your code is in argc()
— it doesn't count the arguments to the function, it counts the file arguments in the command line. Most probably argc()
is 1 when you run the code so the loop is executing only once.
To count the arguments to the function use a:0
instead of argc()
:
while i < a:0
let command = ":wincmd " . a:000[i]
Upvotes: 2