Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<SID> with foldexpr

Tags:

vim

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?

like image 354
Lerp Avatar asked Jul 14 '13 14:07

Lerp


1 Answers

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)
like image 197
Ingo Karkat Avatar answered Nov 15 '22 09:11

Ingo Karkat