4

I have a key mapped to a command which runs a function, and I would like to detect whether it has been passed a range (prefixed with a count) or not.

The difficultly is that I need to be able to differentiate between 1CTRL E and plain CTRL E.

(CTRL E is actually my interactive buffer selector. But when a range is passed I would like it to act like CTRL ^. That is because I like the functionality of CTRL ^, but it is too much of a stretch for my left hand!)

So I have:

nnoremap <C-E> :JoeysBufferSwitch<Enter>
command! -range JoeysBufferSwitch <line1>,<line2>call JoeysBufferSwitch()

Now I can tell if 5CTRL E was pressed, because a:lastline - a:firstline will be 4 inside the function.

Unfortunately I cannot detect whether 1CTRL E was pressed or CTRL E was pressed, because in both cases a:lastline == a.firstline inside the function.

Is there any way I can detect the difference between these two situations, or otherwise behave differently when a count is passed and when a count is not passed?

5

To get the count given to <C-E>, you don't need to use the range to do it. There are two pre-defined variables you can use, v:count and v:count1, which contain the count given to the last normal mode command. The former should work for you, as it will be zero when no count has been given. The latter defaults to 1 in same situation.

Here is a minimal working example:

function! EchoCount()
    echo v:count
endfunction

nnoremap <C-E> :<C-u>call EchoCount()<Enter>

<C-u> is used to clear the range before issuing :call.

As for the range, I don't think there is a way to distinguish between :.Command (which is what happens when you press 1 before :) and :Command, when no count is given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.