7

I have created the following mapping:

:map <F8> 3w

When I pressed 2<F8>, I thought it would move six words (2*3w), but it moves 23 words. (This has been mentioned in help section of vim editor)

How to map it to work for 6 moves instead of 23? Also, please let me know if this feature is intentionally made to work like this for mappings?

(In all other cases, it is straightforward like 2*3 instead ad of 23, like 2d3w is same as 6dw, as well as d6w)

5

Another solution is to use the variable v:count like this:

nnoremap <F8> :<C-u>execute "normal! " . v:count1 * 3 . "w"<CR>

See :h v:count: The variable contains the count given for the last normal mode command and can thus be used to get a count before a mapping.

Here the mapping uses v:count1 which is like v:count but default to zero when no count is given.

The mapping execute the normal command normal! Xw where X is replaced by 3 times the count given before the mapping.

The <C-U> is required to remove the line range that get included when typing : after a count.


Also of course yes the behavior you observed is totally normal: your mapping makes Vim understand F8 as 3w when you types something before Vim as no way to understand that you want it to make a multiplication. Remember that a program can not understand your intention if you don't describes them to it.

8

You can use the expression register for this:

 :nnoremap <F8>  @='3w'<CR>

This will use the expression register to create a repeatable mapping you can prefix with a number:

 2<F8> will move 6 words

A mapping in vim will replace the meaning of a key/sequence of key pressed. So when you do

:map <F8> 3w

and

2<F8>
23w

Vim will convert the <F8> to 3w and what you execute is 23w.

On the other side, when using the expression register, you end up doing:

 2<F8>
 2@='3w'<CR>

Which means, "2 times, execute the content of the expression register".

My guess of if it has been done intentionally is that, given the meaning of mapping, it's the logical way it should execute.

  • Please let me know if this was done intentionally. – SibiCoder May 20 '16 at 6:49
  • Answer updated. – nobe4 May 20 '16 at 8:57
  • 2
    Related Vimcasts episode: Creating mappings that accept a count – Peter Rincker May 20 '16 at 14:23
  • The normal mode mapping does not work very robust because it works with a range. If you supply the mapping with a count at the last line of the file, you will get an error message: E16: Invalid range. – jdhao Apr 29 at 4:10

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.