Tip: #82 - Letting variable values be overwritten in a script
Created: June 22, 2001 9:11 Complexity: basic Author: Salman Halim Version: 6.0 Karma: 65/17 Imported from: Tip#82
This is a simple function i wrote to get the value of a variable from three different places (in that order): the current buffer, the global setting or from the script itself.
This allows me to set a default value for a configuration variable inside my script and the user to change it on a global level by setting the same variable with a g: prepended. then, they can further set it on a per-buffer level by the b: mechanism. one of the examples for this might be my comments script (not uploaded). I have a variable in there that determines whether comment characters (// for java, for example) are placed the beginning of the line or just before the first-non-blanks in the text. i set up a default in my script:
let s:comments_hug_start_of_line=0 " comments should hug the text
that's fine as a default, but if i want to overwrite it for vim scripts, i just put the following in my ftplugin/vim.vim:
let b:comments_hug_start_of_line=1 " vim comments should hug the first column, always
" tries to return the buffer-specific value of a variable; if not
" found, tries to return the global value -- if that's not found
" either, returns the value set in the script itself
function! GetVar(varName)
if (exists ("b:" . a:varName))
exe "let retVal=b:" . a:varName
elseif (exists ("g:" . a:varName))
exe "let retVal=g:" . a:varName
elseif (exists ("s:" . a:varName))
exe "let retVal=s:" . a:varName
else
retVal=-1
endif
return retVal
endfunction
Personally, I never let it get to the -1 state by always having an s: set with SOME default value.
Comments
it seems as if the s: bit only works if the function is defined as part of a script (using the s:GetVar) notation (this is how i had it initially before deciding it might be useful in general).
my apologies for the premature post.
salman.
salmanhalim--AT--hotmail.com , June 22, 2001 9:19
I tweaked GetVar to no longer look for a script variable (since i couldn't get it to work anyway). instead, i have added an optional second parameter which becomes the value returned if neither a buffer or a global variable is found -- -1 is still returned if the second parameter is unspecified:
function! GetVar(...)
let varName=a:1
if (exists("a:2")) let retVal=a:2 else let retVal=-1 endif
if (exists ("b:" . varName)) exe "let retVal=b:" . varName elseif (exists ("g:" . varName)) exe "let retVal=g:" . varName endif return retVal
endfunction
so, to specify the default scope for java bean properties (used inside javabean.vim, though i chose not to put this mechanism in there to avoid the dependency on this function), i just use GetVar("javabean_scope", "protected"). if there is a buffer or global variable set, it uses that; otherwise, it defaults to protected scope.
salmanhalim--AT--hotmail.com , July 18, 2001 13:51