So I was looking for ways to get some object oriented stuff in vimcript when I found this page
So for instance:
function gnat#Make () dict
...
return
endfunction gnat#Make
What does the '#' mean?
Does it have to do with ending the function explicitly like that?
(usually one just endfu[nction] without the function name)
Thanks!
The # is for autoload scripts. Try :h autoload for more info.
I don't think that "explicit" function ending is allowed, as written in the vim help:
:endf[unction] The end of a function definition. Must be on a line
by its own, without other commands.
But it appears that when you try to put something after :endf, even if it's not the name of the function, no error occurs.
Related
I've been doing some trial-and-error on how functions can be called, and it seems like the following is my understanding:
From the command line, typing in :call MyFunction()
From the command line, typing in :call execute('call MyFunction'), where execute essentially performs a string escape (if that's the correct term?) to pass back to the first call param.
From within a function or vim file, typing in call MyFunction(). In other words, each line in a vim function/file acts like the command-line.
From within a function or vim file, typing in call execute('call MyFunction')
Is that a correct understanding of the various ways to call a function? Are there any other possible ways to do it?
I don't really understand what you are doing, but if you ask if there are other ways to call a function, yes, there are.
For example,
the eval(...) can call another function
echo getline('.') or something like this
:s/../\=getline(...)
in expr mappings
...
Simply put, in almost any place when a vimscript can be evaluated, a function can be called.
I have defined a function in my /.vim/ftplugin/python.vim file. The problem is that every time I open a .py file, I get the E122: Function MyFunction already exists, add ! to replace it.
I know that if I add ! then it will override the function (which is not a problem), but that means that it will replace it everytime, and it is a useless (and not very clean) supplementary action.
I guess that the problem come from the Python configuration file being sourced again and again every time I open a new .py file.
How can I tell VIM to source only once?
I would recommend putting the function in an autoload directory. (Read :help autoload it does a very good job explaining how this works). The quick version is below.
Edit the file ~/.vim/autoload/ftplugin/python.vim and add your function there. Everything after the autoload is part of the function signiture. (Instead of / use # between directories and leave off the .vim for the filename directory(s)#file#FunctionName)
function ftplugin#python#MyFunction()
...
endfunction
This function will automatically be loaded by vim the first time it is used.
Inside the filetype plugin you would just create the necessary mappings and commands.
command -buffer MyFunction call ftplugin#python#MyFunction()
nnoremap <buffer> <leader>m :call ftplugin#python#MyFunction()<CR>
and the function will automatically be loaded when it is called the first time. And other buffer that loads the ftplugin won't run into the redefinition problem.
One way: define a variable at the end of the file, check for its existence at the beginning (similar to a c include guard):
if exists('g:my_python')
finish
endif
fun MyFunction
...
endfun
" ... other stuff
let g:my_python = 1
Another way (if all you have is this function): check directly for the existence of its definition:
if !exists('*MyFunction')
fun MyFunction
...
endfun
endif
If you use ultisnips plugin would be great to have a snippet like:
snippet guard "add guard to functions" b
if !exists('*`!p
try:
func_name = re.search('\S+\s+(\S+)\(', snip.v.text.splitlines()[0]).group(1)
except AttributeError:
func_name = ''
snip.rv = func_name
`')
${VISUAL}
endif
${0:jump here <C-j>}
endsnippet
It allow us to select a function with vip, trigger the guard snippet and fix
any function with no effort. In the post quoted you can see a complete explanation about the code above
It came from a discussion on vim #stackexchange. Actually I already knew about !exists thing, so I was trying to create a snippet to make my snippets smarter.
I think I understand the difference between function and function!: if a function with the same name already exists function! silently replaces it, but function yields an error.
I end up using function! always. Because if I use simple function sooner or later it returns and bites me with:
E122: Function my_lib#MyHandyFunction already exists, add ! to replace it
Are there any situations when one should use simple function without !?
In scripts, it doesn't hurt to use :function!, but you should use script-local (s:Foo) or autoload-scoped (myscript#Foo) functions to properly namespace them. So, the override error for :function is helpful to alert you to redefinitions of global functions, but in scripts, you shouldn't need this precaution.
You have to use :function! when you want to reload the script during development (instead of restarting the whole Vim). (And plugins like my ReloadScript plugin can deal with the include guards.)
Another empirical point: Most of the plugins I have use :function!, probably for the easy reload.
The same goes for :command! and :normal!, where (usually), the version with ! should be used.
You should normally use function. Doing such, you would at least recognize when there's a name collision.
When using function! by default, you don't have any feedback that you're about to override an existing function (i.e. change existing functionality)!
Just have a look at the error message you've posted:
E122: Function my_lib#MyHandyFunction already exists, add ! to replace it
This means: careful, dude! If you use function! now, the users of my_lib#MyHandyFunction will experience things they never expected!
I am reading Learn Vim Script the Hard Way and hit something that confused me whilst doing the exercise to convert the folding functions to script local ones.
I tried to go this:
setlocal foldexpr=<SID>GetPotionFold(v:lnum)
and renamed all the functions to start with s:
To my surprise this didn't work and every line had a fold level of 0? It works if I put GetPotionFold into the global scope. Do you have to use a globally scoped function when assigning it to a option? Why?
The <SID> can be used in a mapping or menu, unfortunately not in an option. (This is a shortcoming in the implementation.)
You'd either have to translate it into the actual <SNR>NNN_ prefix (there's an s:SID() example function at :help <SID>), or use a different scope that is accessible from outside the script that defines the function. It's commendable that you want to avoid clobbering the global function namespace, as this is prone to name clashes.
A nice trick is using the autoload function prefix; it doesn't just work in autoload scripts, but can also be used elsewhere, e.g. in plugin scripts. Just prepend the script's name, and you'll have a function that can be invoked from anywhere, but scoped to the script's name:
:function! MyScriptName#GetPotionFold(lnum)
...
:setlocal foldexpr=MyScriptName#GetPotionFold(v:lnum)
Adding to the previous answer, you could define the function s:SID() to determine the script number as in the help documentation and then use execute to set the fold expression as following:
exe "setlocal foldexpr=<SNR>" . s:SID() . "_GetPotionFold(v:lnum)"
I have two question about understand those vim script. please give some help,
Question 1:
I download a.vim plugin, and i try to read this plugin, how to understand the below variable definition? the first line I can understand, but the second line, I don't know exactly "g:alternateExtensions_{'aspx.cs'}" means.
" E.g. let g:alternateExtensions_CPP = "inc,h,H,HPP,hpp"
" let g:alternateExtensions_{'aspx.cs'} = "aspx"
Question 2:
how to understand "SID" before the function name, using like below function definition and function call.
function! <SID>AddAlternateExtensionMapping(extension, alternates)
//omit define body
call <SID>AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
call <SID>AddAlternateExtensionMapping('H',"C,CPP,CXX,CC")
thanks for you kindly help.
let g:alternateExtensions_{'aspx.cs'} = "aspx"
That is an inline expansion of a Vimscript expression into a variable name, a rather obscure feature that is rarely used since Vim version 7. See :help curly-braces-names for details. It is usually used to interpolate a variable, not a string literal like here ('aspx.cs'). Furthermore, this here yields an error, because periods are forbidden in variable names. Newer plugins would use a List or Dictionary variable, but those data types weren't available when a.vim was written.
To avoid polluting the function namespace, plugin-internal functions should be script-local, i.e. have the prefix s:. To invoke these from a mapping, the special <SID> prefix has to be used instead of s:, because <SID> internally gets translated into something that keeps the script's ID, whereas the pure s:, when executed as part of the mapping, has lost its association to the script that defined it.
Some plugin authors don't fully understand this unfortunate and accidental complexity of Vim's scoping implementation either, and they put the <SID> prefix also in front of the function name (which works, too). Though it's slightly more correct and recommended to write it like this:
" Define and invoke script-local function.
function! s:AddAlternateExtensionMapping(extension, alternates)
...
call s:AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
" Only in a mapping, the special <SID> prefix is actually necessary.
nmap <Leader>a :call <SID>AddAlternateExtensionMapping('h',"c,cpp,cxx,cc,CC")
<SID> is explained in :help <SID>:
When defining a function in a script, "s:" can be prepended to the name to
make it local to the script. But when a mapping is executed from outside of
the script, it doesn't know in which script the function was defined. To
avoid this problem, use "<SID>" instead of "s:". The same translation is done
as for mappings. This makes it possible to define a call to the function in
a mapping.
When a local function is executed, it runs in the context of the script it was
defined in. This means that new functions and mappings it defines can also
use "s:" or "<SID>" and it will use the same unique number as when the
function itself was defined. Also, the "s:var" local script variables can be
used.
That number is the one you see on the left when you do :scriptnames, IIRC.