vim9script: <c-r>=Function()<cr> in a mapping fails to work

23 views
Skip to first unread message

Christian J. Robinson

unread,
Feb 26, 2022, 8:53:21 PM2/26/22
to vim_dev
Source the attached script to see the error. If I prefix Function() with <SID> it does work.  Is this correct behavior?

--
Christian J. Robinson <hep...@gmail.com>

Bram Moolenaar

unread,
Feb 27, 2022, 6:43:39 AM2/27/22
to vim...@googlegroups.com, Christian J. Robinson

Christian J. Robinson wrote:

> Source the attached script to see the error. If I prefix Function() with
> <SID> it does work. Is this correct behavior?

I cannot see an attachment.

--
hundred-and-one symptoms of being an internet addict:
113. You are asked about a bus schedule, you wonder if it is 16 or 32 bits.

/// Bram Moolenaar -- Br...@Moolenaar.net -- http://www.Moolenaar.net \\\
/// \\\
\\\ sponsor Vim, vote for features -- http://www.Vim.org/sponsor/ ///
\\\ help me help AIDS victims -- http://ICCF-Holland.org ///

Christian J. Robinson

unread,
Feb 27, 2022, 10:30:04 AM2/27/22
to Bram Moolenaar, vim_dev
Oops, here it is.
ctrl-r_bug.vim

Bram Moolenaar

unread,
Feb 27, 2022, 11:36:58 AM2/27/22
to vim...@googlegroups.com, Christian J. Robinson

Christian J. Robinson wrote:

> > > Source the attached script to see the error. If I prefix Function() with
> > > <SID> it does work. Is this correct behavior?
> >
> > I cannot see an attachment.
>
> Oops, here it is.

Which is:

vim9script
def Foo(): string
return "bar"
enddef
vnoremap <leader>foo s<C-R>=Foo()<CR><ESC>
normal v\foo

A mapping does not keep the context of where it was defined, since
it changes typed keys into other keys, without knowing what they mean.

In Vim9 script a function is defined script-local by default.
While "<C-R>=Foo()" calls Foo() from the command line, thus it searches
for a global function.

You can either make Foo() global:
def g:Foo(): string

Or (recommended) prefix <SID> in the mapping. That will be replaced
when the mapping is defined, so that when the mapping is used the right
function can be found:
vnoremap <leader>foo s<C-R>=<SID>Foo()<CR><ESC>

--
An actual excerpt from a classified section of a city newspaper:
"Illiterate? Write today for free help!"
Reply all
Reply to author
Forward
0 new messages