> One common pitfall when adding an autocmd is to forget to wrap it inside a
> self-clearing augroup.
>
> Bad:
> ```vim
> autocmd CursorHold * echomsg 'do something'
> ```
> Good:
> ```vim
> augroup MyGroup
> autocmd!
> autocmd CursorHold * echomsg 'do something'
> augroup END
> ```
> The first snippet is bad, because if for some reason the script is sourced
> multiple times, there will be a duplicate autocmd:
> ```vim
> vim9script
> var code = 'autocmd CursorHold * echomsg "do something"'
> [code]->writefile('/tmp/script.vim')
> source /tmp/script.vim
> source /tmp/script.vim
> autocmd CursorHold
> ```
> --- Autocommands ---
> CursorHold
> * echomsg "do something"
> echomsg "do something"
>
>
> Depending on the cost of the executed command and/or the frequency of the
> event, this might slow Vim down noticeably, or even cause errors.
>
> ---
>
> Now, here is how we can rewrite the good snippet with the new functions:
> ```vim
> vim9script
> if exists('#MyGroup')
> autocmd_delete([{group: 'MyGroup', event: '*'}])
> endif
> autocmd_add([{group: 'MyGroup', event: 'CursorHold', pattern: '*', cmd:
> "echomsg 'do something'"}])
> ```
> The whole `if exists()` block is cumbersome to read/write every single
> time we need to add an autocmd.
Using "silent!" helps though. Here you don't care about errors.
> Would it make sense for the dictionaries expected by `autocmd_add()`
> to support an extra `unique` boolean option (`true` by default)?
>
> When `unique` is true, the autocmd would not be added if it's inside
> an augroup which already includes the same autocmd. And since
> `unique` would be `true` by default, we could completely omit the
> previous `if exists()` block.
It's probably better to add a "replace" argument: If an autocommand for
this group and event already exists, replace it with this one. This
works better when someone edits the .vimrc to change the command,
sourcing the file again should use the new one, not keep the old one.
autocmd_add([{replace: true, group: 'MyGroup', event: 'CursorHold', pattern:
'*', cmd: "echomsg 'do something'"}])
--
There is a fine line between courage and foolishness.
Unfortunately, it's not a fence.
/// Bram Moolenaar -- [email protected] -- http://www.Moolenaar.net \\\
/// \\\
\\\ sponsor Vim, vote for features -- http://www.Vim.org/sponsor/ ///
\\\ help me help AIDS victims -- http://ICCF-Holland.org ///
--
--
You received this message from the "vim_dev" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php
---
You received this message because you are subscribed to the Google Groups
"vim_dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/vim_dev/20220523141345.C7E8C1C06D7%40moolenaar.net.