0

Say that I have defined two files

python.vim

let b:foo="py"
let b:bar="thon"

cobol.vim

let b:foo="co"
let b:bar="bol"

and that I placed both of them in ~/.vim/ftplugin folder.

Now assume that in my .vimrc I have the following

func! Myfun(foo,bar)
     " do something
endfunc

command MyCommand :call MyFun(b:foo, b:bar)

When I open a Python or Cobol file everything works fine, but when I open any other file with different filetype and try to run :MyCommand, then I get the E121: Undefined variable: b:foo for very good reasons.

A trivial solution would be to copy command MyCommand :call MyFun(b:foo, b:bar) in both python.vim and cobol.vim and remove it from .vimrc but to be honest I really don't like that solution.

I am wondering if there a way to define some default values and if so how to deal with that, or, if you have any other more elegant solution, feel free to share.

1 Answer 1

3

You can use get() to fill in default values:

command MyCommand :call MyFun(get(b:, 'foo', 'def'), get(b:, 'bar', 'ault'))

In this way b: is acting as a sort of "pseudo-dict" which has keys foo and bar. If these variables are not defined, the defaults are substituted according to the normal get() behavior.

1
  • ‘Gr’ . ‘eat! ‘ . ‘Thanks!’
    – Barzi2001
    Dec 12, 2022 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.