I've read :help write-plugin
to understand a bit more about how to write a plugin in Vim9script, but there aspects of that that puzzle me.
Here's a very simplified, working version of the example constructed at the aforementioned help page (the following file is in ~/.vim/plugin/.
):
vim9script noclear
if exists("g:loaded_messingaround")
finish
endif
g:loaded_messingaround = 1
var save_cpo = &cpo
set cpo&vim
if !hasmapto('<Plug>MessingAround;')
map <unique> <Leader>a <Plug>MessingAround;
endif
noremap <unique> <script> <Plug>MessingAround; :echo <SID>Say(expand("<cword>"))<CR>
def Say(str: string): string
return str
enddef
&cpo = save_cpo
Leaving aside the boilerplate, the code above essentially maps Leadera to the ex command :echo …
, which prints to screen whatever Say
returns, which is the same as it gets as argument.
This piece of code works as expected; or, at least, as I expect: if I hit Leadera on a word, that word is echo
ed back.
But what if I want to have Say
defined in autoload
?
In an attempt to do so, I changed the file above to look like this:
vim9script noclear
import autoload 'messingaround.vim' as xyz
if exists("g:loaded_messingaround")
finish
endif
g:loaded_messingaround = 1
var save_cpo = &cpo
set cpo&vim
if !hasmapto('<Plug>MessingAround;')
map <unique> <Leader>a <Plug>MessingAround;
endif
noremap <unique> <script> <Plug>MessingAround; :echo <ScriptCmd>xyz.Say(expand("<cword>"))<CR>
&cpo = save_cpo
Essentially, I added the import
line and removed the definition of Say
, which I've moved into a ~/.vim/autoload/messingaround.vim
and modified by adding the export
keyword:
vim9script noclear
export def Say(str: string): string
return str
enddef
At this point, if I open a new Vim session, put my cursor on a word, and hit Leadera, what I get is that the command line is populated with :echo
(including the trailing space), which looks a bit like Vim hasn't even read the <ScriptCmd>xyz.Say(expand("<cword>"))<CR>
part of the noremap
ping.