1

I am looking for the proper way to specify 'command' argument of the win_execute() function in vim9script.

For example, the following script works fine as a legacy script:

function CheckIndent(lnum) let ind = {} for tif in gettabinfo() for wid in tif.windows call win_execute(wid, 'let ind[wid] = indent(a:lnum)') endfor endfor return ind endfunction echo CheckIndent(5) 

I converted it to vim9script like this:

vim9script def CheckIndent(lnum: number): dict<number> var ind = {} for tif in gettabinfo() for wid in tif.windows win_execute(wid, 'ind[wid] = indent(lnum)') endfor endfor return ind enddef echo CheckIndent(5) 

Then, it happens:

E121: Undefined variable: lnum 

How could I specify lnum as a defined variable in command argument? Is there any workaround or tips?

4
  • Does it work if you explicitly prefix the command inside the string with vim9cmd (or whatever the modifier is)? Commented Jun 20 at 14:58
  • github.com/vim/vim/issues/17585 Commented Jun 21 at 0:08
  • @BenKnoble in my tests it seems that the vim9cmd is supposed (i.e. automatically added) but it is not enough since the local variables are not accessible. Commented Jun 21 at 5:37
  • Do you still have something open in your question? How can we help you further? Otherwise maybe could you accept one of the solution using the v button next to the arrow voting buttons. It allow the question to rest :-) Commented Jun 23 at 7:37

1 Answer 1

1

I believe the local variables are not visible to the command executed by win_execute().

I would do:

vim9script def CheckIndent(lnum: number): dict<number> g:ind = {} for tif in gettabinfo() for wid in tif.windows var cmd = $'g:ind[{wid}] = indent({lnum})' win_execute(wid, cmd) endfor endfor return g:ind enddef echo CheckIndent(5) 

Remark: $'g:ind[{wid}] = indent({lnum})' is the Vimscript equivalent of f"g:ind[{wid}] = indent({lnum})" in Python. The {} placeholders are replaced by the evaluation of the contained expression.

More information with :help $quote

4
  • 1
    This answer is missing a link to the doc for $''. Commented Jun 20 at 12:04
  • @romainl thanks for the suggestion. I have expanded the answer accordingly. Commented Jun 20 at 13:19
  • 1
    Thank you. It works fine using a interpolated string. Instead of g: variable, is it possible to share a script local variable between functions? Maybe ':help vim9-scopes' says NO. Commented Jun 21 at 2:47
  • I believe it is indeed not possible. My understanding is that the local variable are somehow "compiled" and not accessible to other script. MaxKim has open an issue based on your question he knows quite well vim9script. I doubt there is a better answer as of now :-/ Commented Jun 21 at 5:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.