Vim Script: Is it possible to refer to script-local variables in mappings?

5

I know that you can refer to script-local functions using <SID> but what about script-local variables? I tried the following, and hitting <c-space> fails:

let s:testVar = "foo"
function! s:GetTestVar()
  return s:testVar
endfunction

nnoremap <space> :echo <SID>GetTestVar()<cr>
nnoremap <c-space> :echo <SID>testVar<cr>

You can get around this by writing accessor functions (as above) but sometimes it would be nice to be able to refer directly.

Steve Vermeulen

Posted 2013-03-15T22:33:22.080

Reputation: 517

Answers

6

No, script-local variables are indeed private to the script. You have to write an accessor function indeed.

In plugins, this isn't so much an issue, because they should separate the functions (and with them the script's state variables) into autoload scripts, so mappings / commands (defined in the plugin script) have to refer to another script, anyway.

Ingo Karkat

Posted 2013-03-15T22:33:22.080

Reputation: 19 513

2

I originally wanted to comment this, but I need 50 rep. Here's a small suggestion, and I hope its on target.

its possible to use (within the script where the var is defined)

exe "nnoremap <c-space> :echo ".s:testVar."<cr>"

I'm using this for s:var path insertion in mappings defined in my .vimrc. Let me know if I missed the point, or something...

dabyly

Posted 2013-03-15T22:33:22.080

Reputation: 21

Note that this will capture the variable's value when the line is executed rather then using the "live" value when the mapping is triggered. – Kevin Cox – 2018-10-24T13:24:58.323