1

Say that I want to define my own autocmd as it follows:

autocmd User Foo echom "Here I am!"

And then I have a function that at some point trigger that autocmd, like the following:

def Func()
  # .. do something

  var user_autocmds = execute('autocmd User')

  if stridx(user_autocmds, "Foo") != -1
      doautocmd User Foo
  endif

  # ... do something else
enddef

I am wondering if the way of "guarding" it described above is the best I can do.

My thinking is that the doautocmd User Foo shall be executed only if the autocmd Foo is defined. If not, then the doautocmd shall not be executed. This because I don't want to get the message No matching autocommand Foo every time I call Func() if Foo autocommand is not defined.

Surely I can use silent! doautocmd ... but then I would miss ALL the error message coming from the invocation of doautocmd

Can I do better?

1
  • 1
    See :help exists().
    – romainl
    Commented Apr 9 at 16:49

1 Answer 1

1

Here is the entire :help User, the reading of which is pretty much required before using that event:

Never executed automatically.  To be used for
autocommands that are only executed with
":doautocmd".
Note that when `:doautocmd User MyEvent` is
used while there are no matching autocommands,
you will get an error.  If you don't want
that, either check whether an autocommand is
defined using `exists('#User#MyEvent')` or
define a dummy autocommand yourself.
Example:
    if exists('#User#MyEvent')
        doautocmd User MyEvent
    endif

Next step: :help exists().

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.