0

I want to remap <c-b> to foo<c-b>, being foo a number. However, it seems it won't work with function local variables.

For instance, the following works:

vim9script var foo = 4 if !hasmapto('<c-f>', 'n') nnoremap <expr> <c-f> repeat('<c-f>', foo) endif 

but the following does not work:

vim9script def Func() var foo = 4 if !hasmapto('<c-f>', 'n') nnoremap <expr> <c-f> repeat('<c-f>', foo) endif enddef Func() 

Is there any reason for it?

4
  • :var is not a command, do you intend to use :let as in let foo = 4 instead? I do see an error E116: Invalid arguments for function repeat if foo hasn't been defined, but as long as the variable is properly defined your second example (which is correct, using <expr>) should work as intended. I'll go ahead and recommend you might want to read Learn Vimscript the Hard Way if you'd like to get more familiar with Vimscript the language and be able to troubleshoot issues like this on your own. Commented Sep 3, 2024 at 16:12
  • 1
    var is used in Vim9 to define script-local variables. Commented Sep 3, 2024 at 17:17
  • I have updated the questions based on new findings. Commented Sep 3, 2024 at 18:48
  • Ah, vim9script changes everything! Commented Sep 3, 2024 at 19:44

1 Answer 1

2

I suspect that foo variable is not accessible when the mapping is executed since it is a local variable from a scope that is invalid long back and not a global variable.

The following should work:

vim9script var foo = 4 def Func() if !hasmapto('<c-f>', 'n') nnoremap <expr> <c-f> repeat('<c-f>', foo) endif enddef Func() 
4
  • 1
    Yes, this works. But I wonder why the previous didn't work. Weird. Commented Sep 3, 2024 at 19:01
  • 1
    Is my explanation not convincing? I suppose when the mapping is executed the foo local variable is not accessible anymore and either leading to an error or default to some value different from 4. Commented Sep 3, 2024 at 19:06
  • 1
    ah! Ok! Now I get it! Yes, it makes sense, but still, it is very subtle. The thing is that when I hit <c-f> then repeat does not know where to pick foo if it is defined inside the function because it is destroyed when the function finishes, whereas if it is script-local then foo is kept. Hence, foo is valid for the map definition at "script-source-time", but it does not exist at runtime and therefore <c-f> fails. Correct? Commented Sep 3, 2024 at 19:11
  • 1
    Exactly! You catch my point :-) Commented Sep 3, 2024 at 19:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.