Hubro
Hubro

Reputation: 59323

How do I create a Vim keybind that involves numbers (0-9)?

I want to create a keybind for setting the fold level to a specific number. The ex command is:

:set foldlevel=n

Where n is the fold level. I want to bind <leader>z plus a number to set the fold level. My goal is this invocation (assuming my leader key is \):

\z3

And it should in turn invoke this command:

:set foldlevel=3

Is it possible to involve numbers in keybinds like this? If so, how is it done?

Upvotes: 2

Views: 626

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172520

The usual way is the other way around, with [count] coming first. This makes is easy to handle numbers larger than single-digit (though it's probably not so important for foldlevels). You can use the v:count special variable, as in:

:nnoremap <silent> <Leader>z :<C-u>let &foldlevel = v:count<CR>

The <C-u> is needed to remove the automatically inserted range. I use :let for the option assignment, though :execute would have worked, too.

Upvotes: 5

mihai
mihai

Reputation: 38543

This should do it

for key in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  exe "nmap <silent> <leader>" . key . " " . ":set foldlevel=" . key . "<cr>"
endfor

You need to use to use the execute command if you want to build up dynamic mappings. The dot stands for string concatenation, in case you're not familiar with vimscript.

Upvotes: 2

Related Questions