How to use options when writing vimscript?

Go To StackoverFlow.com

4

[SOLVED] It seems the solution is this:

if exists('g:nameOfMyOption') && g:nameOfMyOption
     ...
endif

It's very straightforward, but I can't find the answer online. I want to do something like this in a plugin file:

" MyChecker.vim
"
" Uncomment the following line to set the autochecker option
"set autochecker=1

if ISSET(autochecker)
   autocmd InsertChange * :call MyAutoCheckerFunction()
endif

How do I do the ISSET line? I'd rather not have to explicitly set autochecker=0, I'd like it to just check if autochecker exists.

Edit: When I try the following:

if &autochecker == 1
    ...
endif

I get this error message:

Error detected while processing MyChecker.vim:
line   32:
E113: Unknown option: autochecker
E15: Invalid expression: &autochecker == 1
2012-04-04 17:11
by usul


6

You can't create custom options in vim. You need to create a global variable instead like:

let g:AutoChecker = 1

....

if g:AutoChecker == 1
   " ...
endif
2012-04-04 17:34
by Tom Whittock
Ah, ok. So if I want a user to change the "option", they have to put "let g:AutoChecker = 0" in their .vimrc - usul 2012-04-04 17:45
If you're not explicitly setting the var, you're going to want to test for it's existence with exists() as well. See this: https://github.com/rson/vimscript-snippets/blob/master/idiomaticpluginmapping.vim#L1 - Randy Morris 2012-04-04 17:48
OK, I see how to do it! The example was very helpful as well. Thank you both - usul 2012-04-04 17:52


1

For general options, I use the following function: lh#option#get(). It first searches if b:{varname} exists to return its value, then g:{varname}. Otherwise the default value provided is returned if none of the variables exist.

For programming related options (i.e. options can can be overridden for specific filetypes), I use another function: lh#dev#option#get().

The C++ Options section of lh-cpp documentation indirectly explains the rationale behind these two functions.

2012-04-05 11:30
by Luc Hermitte
This is really nice - I'm using some of your other scripts to do syntax aware text objects. Seems you've got a real treasure trove of extensions there - Tom Whittock 2012-04-08 13:26
Ads