robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
74.7 KiB2586 linesraw
1// autocmd.c: Autocommand related functions
2
3#include <assert.h>
4#include <stddef.h>
5#include <stdint.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9
10#include "nvim/api/private/converter.h"
11#include "nvim/autocmd.h"
12#include "nvim/autocmd_defs.h"
13#include "nvim/buffer.h"
14#include "nvim/charset.h"
15#include "nvim/cmdexpand_defs.h"
16#include "nvim/context.h"
17#include "nvim/cursor.h"
18#include "nvim/errors.h"
19#include "nvim/eval.h"
20#include "nvim/eval/typval.h"
21#include "nvim/eval/userfunc.h"
22#include "nvim/eval/vars.h"
23#include "nvim/event/loop.h"
24#include "nvim/event/multiqueue.h"
25#include "nvim/ex_docmd.h"
26#include "nvim/ex_eval.h"
27#include "nvim/fileio.h"
28#include "nvim/gettext_defs.h"
29#include "nvim/globals.h"
30#include "nvim/grid.h"
31#include "nvim/grid_defs.h"
32#include "nvim/hashtab.h"
33#include "nvim/highlight_defs.h"
34#include "nvim/input.h"
35#include "nvim/input_defs.h"
36#include "nvim/insexpand.h"
37#include "nvim/lua/executor.h"
38#include "nvim/main.h"
39#include "nvim/map_defs.h"
40#include "nvim/mbyte.h"
41#include "nvim/memory.h"
42#include "nvim/message.h"
43#include "nvim/option.h"
44#include "nvim/option_defs.h"
45#include "nvim/option_vars.h"
46#include "nvim/os/input.h"
47#include "nvim/os/os.h"
48#include "nvim/os/os_defs.h"
49#include "nvim/os/time.h"
50#include "nvim/os/time_defs.h"
51#include "nvim/path.h"
52#include "nvim/profile.h"
53#include "nvim/regexp.h"
54#include "nvim/runtime.h"
55#include "nvim/runtime_defs.h"
56#include "nvim/search.h"
57#include "nvim/state.h"
58#include "nvim/state_defs.h"
59#include "nvim/strings.h"
60#include "nvim/types_defs.h"
61#include "nvim/ui.h"
62#include "nvim/ui_compositor.h"
63#include "nvim/vim_defs.h"
64#include "nvim/window.h"
65#include "nvim/winfloat.h"
66
67#include "auevents_name_map.generated.h"
68#include "autocmd.c.generated.h"
69
70static const char e_autocommand_nesting_too_deep[]
71  = N_("E218: Autocommand nesting too deep");
72
73// Naming Conventions:
74//  - general autocmd behavior start with au_
75//  - AutoCmd start with aucmd_
76//  - AutoPat start with aupat_
77//  - Groups start with augroup_
78//  - Events start with event_
79
80// The autocommands are stored in a contiguous vector for each event.
81//
82// The order of AutoCmds is important, this is the order in which they
83// were defined and will have to be executed.
84//
85// To avoid having to match the pattern too often, patterns are reference
86// counted and reused for consecutive autocommands.
87
88// Code for automatic commands.
89static AutoPatCmd *active_apc_list = NULL;  // stack of active autocommands
90
91/// Window handle for `ev.win`.  Unlike autocmd_bufnr/_match this needn't be a
92/// global: only au_callback() reads it.
93static handle_T autocmd_winid = 0;
94
95// ID for associating autocmds created via nvim_create_autocmd
96// Used to delete autocmds from nvim_del_autocmd
97static int next_augroup_id = 1;
98
99// use get_deleted_augroup() to get this
100static const char *deleted_augroup = NULL;
101
102// The ID of the current group.
103static int current_augroup = AUGROUP_DEFAULT;
104
105// Whether we need to delete marked patterns.
106// While deleting autocmds, they aren't actually remover, just marked.
107static bool au_need_clean = false;
108
109static int autocmd_blocked = 0;  // block all autocmds
110
111static bool autocmd_nested = false;
112static bool autocmd_include_groups = false;
113
114static bool termresponse_changed = false;
115static uint64_t termresponse_chan_id = 0;
116
117// Map of autocmd group names and ids.
118//  name -> ID
119//  ID -> name
120static Map(String, int) map_augroup_name_to_id = MAP_INIT;
121static Map(int, String) map_augroup_id_to_name = MAP_INIT;
122
123void autocmd_init(void)
124{
125  deferred_events = multiqueue_new_child(main_loop.events);
126}
127
128#ifdef EXITFREE
129void autocmd_free_all_mem(void)
130{
131  multiqueue_free(deferred_events);
132}
133#endif
134
135static void augroup_map_del(int id, const char *name)
136{
137  if (name != NULL) {
138    String key;
139    map_del(String, int)(&map_augroup_name_to_id, cstr_as_string(name), &key);
140    api_free_string(key);
141  }
142  if (id > 0) {
143    String mapped = map_del(int, String)(&map_augroup_id_to_name, id, NULL);
144    api_free_string(mapped);
145  }
146}
147
148static inline const char *get_deleted_augroup(void) FUNC_ATTR_ALWAYS_INLINE
149{
150  if (deleted_augroup == NULL) {
151    deleted_augroup = _("--Deleted--");
152  }
153  return deleted_augroup;
154}
155
156static void au_show_for_all_events(int group, const char *pat)
157{
158  FOR_ALL_AUEVENTS(event) {
159    au_show_for_event(group, event, pat);
160  }
161}
162
163static void au_show_for_event(int group, event_T event, const char *pat)
164  FUNC_ATTR_NONNULL_ALL
165{
166  AutoCmdVec *const acs = &autocmds[(int)event];
167  // Return early if there are no autocmds for this event
168  if (kv_size(*acs) == 0) {
169    return;
170  }
171
172  // Empty pattern shows all autocommands for this event
173  int patlen = 0;
174  if (*pat != NUL) {
175    patlen = (int)aucmd_span_pattern(pat, &pat);
176    if (patlen == 0) {  // Don't show if it contains only commas
177      return;
178    }
179  }
180
181  char buflocal_pat[BUFLOCAL_PAT_LEN];  // for "<buffer=X>"
182  int last_group = AUGROUP_ERROR;
183  const char *last_group_name = NULL;
184
185  // Loop through all the specified patterns.
186  do {
187    AutoPat *last_ap = NULL;
188    const char *endpat = pat + patlen;
189
190    // detect special <buffer[=X]> buffer-local patterns
191    if (aupat_is_buflocal(pat, patlen)) {
192      // normalize pat into standard "<buffer>#N" form
193      aupat_normalize_buflocal_pat(buflocal_pat, pat, patlen, aupat_get_buflocal_nr(pat, patlen));
194      pat = buflocal_pat;
195      patlen = (int)strlen(buflocal_pat);
196    }
197
198    for (size_t i = 0; i < kv_size(*acs); i++) {
199      AutoCmd *const ac = &kv_A(*acs, i);
200
201      // Skip deleted autocommands.
202      if (ac->pat == NULL) {
203        continue;
204      }
205
206      // Accept a pattern when:
207      // - a group was specified and it's that group
208      // - the length of the pattern matches
209      // - the pattern matches.
210      // For <buffer[=X]>, this condition works because we normalize
211      // all buffer-local patterns.
212      if ((group != AUGROUP_ALL && ac->pat->group != group)
213          || (patlen
214              && (ac->pat->patlen != patlen || strncmp(pat, ac->pat->pat, (size_t)patlen) != 0))) {
215        continue;
216      }
217
218      // Show event name and group only if one of them changed.
219      if (ac->pat->group != last_group) {
220        last_group = ac->pat->group;
221        last_group_name = augroup_name(ac->pat->group);
222
223        if (got_int) {
224          return;
225        }
226
227        msg_putchar('\n');
228        if (got_int) {
229          return;
230        }
231
232        // When switching groups, we need to show the new group information.
233        // show the group name, if it's not the default group
234        if (ac->pat->group != AUGROUP_DEFAULT) {
235          if (last_group_name == NULL) {
236            msg_puts_hl(get_deleted_augroup(), HLF_E, false);
237          } else {
238            msg_puts_hl(last_group_name, HLF_T, false);
239          }
240          msg_puts("  ");
241        }
242        // show the event name
243        msg_puts_hl(event_nr2name(event), HLF_T, false);
244      }
245
246      // Show pattern only if it changed.
247      if (last_ap != ac->pat) {
248        last_ap = ac->pat;
249
250        msg_putchar('\n');
251        if (got_int) {
252          return;
253        }
254
255        msg_advance(4);
256        msg_outtrans(ac->pat->pat, 0, false);
257      }
258
259      if (got_int) {
260        return;
261      }
262
263      if (msg_col >= 14) {
264        msg_putchar('\n');
265      }
266      msg_advance(14);
267      if (got_int) {
268        return;
269      }
270
271      char *handler_str = aucmd_handler_to_string(ac);
272      if (ac->desc != NULL) {
273        size_t msglen = 100;
274        char *msg = xmallocz(msglen);
275        if (ac->handler_cmd) {
276          snprintf(msg, msglen, "%s [%s]", handler_str, ac->desc);
277        } else {
278          msg_puts_hl(handler_str, HLF_8, false);
279          snprintf(msg, msglen, " [%s]", ac->desc);
280        }
281        msg_outtrans(msg, 0, false);
282        XFREE_CLEAR(msg);
283      } else if (ac->handler_cmd) {
284        msg_outtrans(handler_str, 0, false);
285      } else {
286        msg_puts_hl(handler_str, HLF_8, false);
287      }
288      XFREE_CLEAR(handler_str);
289      if (p_verbose > 0) {
290        last_set_msg(ac->script_ctx);
291      }
292
293      if (got_int) {
294        return;
295      }
296    }
297
298    patlen = (int)aucmd_span_pattern(endpat, &pat);
299  } while (patlen);
300}
301
302// Delete autocommand.
303static void aucmd_del(AutoCmd *ac)
304{
305  if (ac->pat != NULL && --ac->pat->refcount == 0) {
306    XFREE_CLEAR(ac->pat->pat);
307    vim_regfree(ac->pat->reg_prog);
308    xfree(ac->pat);
309  }
310  ac->pat = NULL;
311  if (ac->handler_cmd) {
312    XFREE_CLEAR(ac->handler_cmd);
313  } else {
314    callback_free(&ac->handler_fn);
315  }
316  XFREE_CLEAR(ac->desc);
317
318  au_need_clean = true;
319}
320
321void aucmd_del_for_event_and_group(event_T event, int group)
322{
323  AutoCmdVec *const acs = &autocmds[(int)event];
324  for (size_t i = 0; i < kv_size(*acs); i++) {
325    AutoCmd *const ac = &kv_A(*acs, i);
326    if (ac->pat != NULL && ac->pat->group == group) {
327      aucmd_del(ac);
328    }
329  }
330
331  au_cleanup();
332}
333
334/// Cleanup autocommands that have been deleted.
335/// This is only done when not executing autocommands.
336static void au_cleanup(void)
337{
338  if (autocmd_busy || !au_need_clean) {
339    return;
340  }
341
342  // Loop over all events.
343  FOR_ALL_AUEVENTS(event) {
344    // Loop over all autocommands.
345    AutoCmdVec *const acs = &autocmds[(int)event];
346    size_t nsize = 0;
347    for (size_t i = 0; i < kv_size(*acs); i++) {
348      AutoCmd *const ac = &kv_A(*acs, i);
349      if (nsize != i) {
350        kv_A(*acs, nsize) = *ac;
351      }
352      if (ac->pat != NULL) {
353        nsize++;
354      }
355    }
356    if (nsize == 0) {
357      kv_destroy(*acs);
358    } else {
359      acs->size = nsize;
360    }
361  }
362
363  au_need_clean = false;
364}
365
366AutoCmdVec *au_get_autocmds_for_event(event_T event)
367  FUNC_ATTR_PURE
368{
369  return &autocmds[(int)event];
370}
371
372// Called when buffer is freed, to remove/invalidate related buffer-local autocmds.
373void aubuflocal_remove(buf_T *buf)
374{
375  // invalidate currently executing autocommands
376  for (AutoPatCmd *apc = active_apc_list; apc != NULL; apc = apc->next) {
377    if (buf->b_fnum == apc->arg_bufnr) {
378      apc->arg_bufnr = 0;
379    }
380  }
381
382  // invalidate buflocals looping through events
383  FOR_ALL_AUEVENTS(event) {
384    AutoCmdVec *const acs = &autocmds[(int)event];
385    for (size_t i = 0; i < kv_size(*acs); i++) {
386      AutoCmd *const ac = &kv_A(*acs, i);
387      if (ac->pat == NULL || ac->pat->buflocal_nr != buf->b_fnum) {
388        continue;
389      }
390
391      aucmd_del(ac);
392
393      if (p_verbose >= 6) {
394        verbose_enter();
395        smsg(0, _("auto-removing autocommand: %s <buffer=%d>"), event_nr2name(event), buf->b_fnum);
396        verbose_leave();
397      }
398    }
399  }
400  au_cleanup();
401}
402
403// Add an autocmd group name or return existing group matching name.
404// Return its ID.
405int augroup_add(const char *name)
406{
407  assert(STRICMP(name, "end") != 0);
408
409  int existing_id = augroup_find(name);
410  if (existing_id > 0) {
411    assert(existing_id != AUGROUP_DELETED);
412    return existing_id;
413  }
414
415  if (existing_id == AUGROUP_DELETED) {
416    augroup_map_del(existing_id, name);
417  }
418
419  int next_id = next_augroup_id++;
420  String name_key = cstr_to_string(name);
421  String name_val = cstr_to_string(name);
422  map_put(String, int)(&map_augroup_name_to_id, name_key, next_id);
423  map_put(int, String)(&map_augroup_id_to_name, next_id, name_val);
424
425  return next_id;
426}
427
428void augroup_del_by_id(int id)
429{
430  char *name = id <= 0 ? NULL : augroup_name(id);
431  if (name == NULL) {
432    semsg(_("E367: No such group id: %d"), id);
433  } else {
434    // NB: this can still error, but the error might be "semantic" like "-- Deleted --"
435    augroup_del(name, id, false);
436  }
437}
438
439/// Delete the augroup that matches name.
440/// @param stupid_legacy_mode bool: This parameter determines whether to run the augroup
441///     deletion in the same fashion as `:augroup! {name}` where if there are any remaining
442///     autocmds left in the augroup, it will change the name of the augroup to `--- DELETED ---`
443///     but leave the autocmds existing. These are _separate_ augroups, so if you do this for
444///     multiple augroups, you will have a bunch of `--- DELETED ---` augroups at the same time.
445///     There is no way, as far as I could tell, how to actually delete them at this point as a user
446///
447///     I did not consider this good behavior, so now when NOT in stupid_legacy_mode, we actually
448///     delete these groups and their commands, like you would expect (and don't leave hanging
449///     `--- DELETED ---` groups around)
450/// @param id_for_error  only to provide context for an error message:
451///                       if >= 0, we tried to look up the group by id
452///                       if < 0, only use `name` for error
453void augroup_del(char *name, int id_for_error, bool stupid_legacy_mode)
454{
455  int group = augroup_find(name);
456  if (group == AUGROUP_ERROR) {  // the group doesn't exist
457    if (id_for_error > 0) {
458      semsg(_("E367: No such group id: %d \"%s\""), id_for_error, name);
459    } else {
460      semsg(_("E367: No such group: \"%s\""), name);
461    }
462    return;
463  } else if (group == current_augroup) {
464    emsg(_("E936: Cannot delete the current group"));
465    return;
466  }
467
468  if (stupid_legacy_mode) {
469    FOR_ALL_AUEVENTS(event) {
470      AutoCmdVec *const acs = &autocmds[(int)event];
471      for (size_t i = 0; i < kv_size(*acs); i++) {
472        AutoPat *const ap = kv_A(*acs, i).pat;
473        if (ap != NULL && ap->group == group) {
474          give_warning(_("W19: Deleting augroup that is still in use"), true, true);
475          map_put(String, int)(&map_augroup_name_to_id, cstr_as_string(name), AUGROUP_DELETED);
476          augroup_map_del(ap->group, NULL);
477          return;
478        }
479      }
480    }
481  } else {
482    FOR_ALL_AUEVENTS(event) {
483      AutoCmdVec *const acs = &autocmds[(int)event];
484      for (size_t i = 0; i < kv_size(*acs); i++) {
485        AutoCmd *const ac = &kv_A(*acs, i);
486        if (ac->pat != NULL && ac->pat->group == group) {
487          aucmd_del(ac);
488        }
489      }
490    }
491  }
492
493  // Remove the group because it's not currently in use.
494  augroup_map_del(group, name);
495  au_cleanup();
496}
497
498/// Find the ID of an autocmd group name.
499///
500/// @param name augroup name
501///
502/// @return the ID or AUGROUP_ERROR (< 0) for error.
503int augroup_find(const char *name)
504  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
505{
506  int existing_id = map_get(String, int)(&map_augroup_name_to_id, cstr_as_string(name));
507  if (existing_id == AUGROUP_DELETED) {
508    return existing_id;
509  }
510
511  if (existing_id > 0) {
512    return existing_id;
513  }
514
515  return AUGROUP_ERROR;
516}
517
518/// Gets the name for a particular group.
519char *augroup_name(int group)
520{
521  assert(group != 0);
522
523  if (group == AUGROUP_DELETED) {
524    return (char *)get_deleted_augroup();
525  }
526
527  if (group == AUGROUP_ALL) {
528    group = current_augroup;
529  }
530
531  // next_augroup_id is the "source of truth" about what autocmds have existed
532  //
533  // The map_size is not the source of truth because groups can be removed from
534  // the map. When this happens, the map size is reduced. That's why this function
535  // relies on next_augroup_id instead.
536
537  // "END" is always considered the last augroup ID.
538  // Used for expand_get_event_name and expand_get_augroup_name
539  if (group == next_augroup_id) {
540    return "END";
541  }
542
543  // If it's larger than the largest group, then it doesn't have a name
544  if (group > next_augroup_id) {
545    return NULL;
546  }
547
548  String key = map_get(int, String)(&map_augroup_id_to_name, group);
549  if (key.data != NULL) {
550    return key.data;
551  }
552
553  // If it's not in the map anymore, then it must have been deleted.
554  return (char *)get_deleted_augroup();
555}
556
557/// Return true if augroup "name" exists.
558///
559/// @param name augroup name
560bool augroup_exists(const char *name)
561  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
562{
563  return augroup_find(name) > 0;
564}
565
566/// ":augroup {name}".
567void do_augroup(char *arg, bool del_group)
568{
569  if (del_group) {
570    if (*arg == NUL) {
571      emsg(_(e_argreq));
572    } else {
573      augroup_del(arg, -1, true);
574    }
575  } else if (STRICMP(arg, "end") == 0) {  // ":aug end": back to group 0
576    current_augroup = AUGROUP_DEFAULT;
577  } else if (*arg) {  // ":aug xxx": switch to group xxx
578    current_augroup = augroup_add(arg);
579  } else {  // ":aug": list the group names
580    msg_start();
581    msg_ext_set_kind("list_cmd");
582
583    String name;
584    int value;
585    map_foreach(&map_augroup_name_to_id, name, value, {
586      if (value > 0) {
587        msg_puts(name.data);
588      } else {
589        msg_puts(augroup_name(value));
590      }
591
592      msg_puts("  ");
593    });
594
595    msg_clr_eos();
596    msg_end();
597  }
598}
599
600#ifdef EXITFREE
601void free_all_autocmds(void)
602{
603  FOR_ALL_AUEVENTS(event) {
604    AutoCmdVec *const acs = &autocmds[(int)event];
605    for (size_t i = 0; i < kv_size(*acs); i++) {
606      aucmd_del(&kv_A(*acs, i));
607    }
608    kv_destroy(*acs);
609    au_need_clean = false;
610  }
611
612  // Delete the augroup_map, including free the data
613  String name;
614  map_foreach_key(&map_augroup_name_to_id, name, {
615    api_free_string(name);
616  })
617  map_destroy(String, &map_augroup_name_to_id);
618
619  map_foreach_value(&map_augroup_id_to_name, name, {
620    api_free_string(name);
621  })
622  map_destroy(int, &map_augroup_id_to_name);
623
624  // ctx_win[] is freed in win_free_all()
625}
626#endif
627
628/// Return the event number for event name "start".
629/// Return NUM_EVENTS if the event name was not found.
630/// Return a pointer to the next event name in "end".
631event_T event_name2nr(const char *start, char **end)
632{
633  const char *p;
634
635  // the event name ends with end of line, '|', a blank or a comma
636  for (p = start; *p && !ascii_iswhite(*p) && *p != ',' && *p != '|'; p++) {}
637
638  int hash_idx = event_name2nr_hash(start, (size_t)(p - start));
639  if (*p == ',') {
640    p++;
641  }
642  *end = (char *)p;
643  if (hash_idx < 0) {
644    return NUM_EVENTS;
645  }
646  return (event_T)abs(event_names[event_hash[hash_idx]].event);
647}
648
649/// Return the event number for event name "str".
650/// Return NUM_EVENTS if the event name was not found.
651event_T event_name2nr_str(String str)
652{
653  int hash_idx = event_name2nr_hash(str.data, str.size);
654  if (hash_idx < 0) {
655    return NUM_EVENTS;
656  }
657  return (event_T)abs(event_names[event_hash[hash_idx]].event);
658}
659
660/// Return the name for event
661///
662/// @param[in]  event  Event to return name for.
663///
664/// @return Event name, static string. Returns "Unknown" for unknown events.
665const char *event_nr2name(event_T event)
666  FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_CONST
667{
668  return event >= 0 && event < NUM_EVENTS ? event_names[event].name : "Unknown";
669}
670
671/// Return true if "event" is included in 'eventignore(win)'.
672///
673/// @param event event to check
674bool event_ignored(event_T event, char *ei)
675  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
676{
677  bool ignored = false;
678  while (*ei != NUL) {
679    bool unignore = *ei == '-';
680    ei += unignore;
681    if (STRNICMP(ei, "all", 3) == 0 && (ei[3] == NUL || ei[3] == ',')) {
682      ignored = ei == p_ei || event_names[event].event <= 0;
683      ei += 3 + (ei[3] == ',');
684    } else if (event_name2nr(ei, &ei) == event) {
685      if (unignore) {
686        return false;
687      }
688      ignored = true;
689    }
690  }
691
692  return ignored;
693}
694
695/// Return OK when the contents of 'eventignore' or 'eventignorewin' is valid,
696/// FAIL otherwise.
697int check_ei(char *ei, bool win)
698{
699  while (*ei) {
700    if (STRNICMP(ei, "all", 3) == 0 && (ei[3] == NUL || ei[3] == ',')) {
701      ei += 3 + (ei[3] == ',');
702    } else {
703      ei += (*ei == '-');
704      event_T event = event_name2nr(ei, &ei);
705      if (event == NUM_EVENTS || (win && event_names[event].event > 0)) {
706        return FAIL;
707      }
708    }
709  }
710
711  return OK;
712}
713
714// Add "what" to 'eventignore' to skip loading syntax highlighting for every
715// buffer loaded into the window.  "what" must start with a comma.
716// Returns the old value of 'eventignore' in allocated memory.
717char *au_event_disable(char *what)
718{
719  size_t p_ei_len = strlen(p_ei);
720  char *save_ei = xmemdupz(p_ei, p_ei_len);
721  char *new_ei = xstrnsave(p_ei, p_ei_len + strlen(what));
722  if (*what == ',' && *p_ei == NUL) {
723    STRCPY(new_ei, what + 1);
724  } else {
725    STRCPY(new_ei + p_ei_len, what);
726  }
727  set_option_direct(kOptEventignore, CSTR_AS_OBJ(new_ei), 0, SID_NONE);
728  xfree(new_ei);
729  return save_ei;
730}
731
732void au_event_restore(char *old_ei)
733{
734  if (old_ei != NULL) {
735    set_option_direct(kOptEventignore, CSTR_AS_OBJ(old_ei), 0, SID_NONE);
736    xfree(old_ei);
737  }
738}
739
740// Implements :autocmd.
741// Defines an autocmd (does not execute; cf. apply_autocmds_group).
742//
743// Can be used in the following ways:
744//
745// :autocmd <event> <pat> <cmd>     Add <cmd> to the list of commands that
746//                                  will be automatically executed for <event>
747//                                  when editing a file matching <pat>, in
748//                                  the current group.
749// :autocmd <event> <pat>           Show the autocommands associated with
750//                                  <event> and <pat>.
751// :autocmd <event>                 Show the autocommands associated with
752//                                  <event>.
753// :autocmd                         Show all autocommands.
754// :autocmd! <event> <pat> <cmd>    Remove all autocommands associated with
755//                                  <event> and <pat>, and add the command
756//                                  <cmd>, for the current group.
757// :autocmd! <event> <pat>          Remove all autocommands associated with
758//                                  <event> and <pat> for the current group.
759// :autocmd! <event>                Remove all autocommands associated with
760//                                  <event> for the current group.
761// :autocmd!                        Remove ALL autocommands for the current
762//                                  group.
763//
764//  Multiple events and patterns may be given separated by commas.  Here are
765//  some examples:
766// :autocmd bufread,bufenter *.c,*.h    set tw=0 smartindent noic
767// :autocmd bufleave         *          set tw=79 nosmartindent ic infercase
768//
769// :autocmd * *.c               show all autocommands for *.c files.
770//
771// Mostly a {group} argument can optionally appear before <event>.
772void do_autocmd(exarg_T *eap, char *arg_in, int forceit)
773{
774  char *arg = arg_in;
775  char *envpat = NULL;
776  char *cmd;
777  bool cmd_need_free = false;
778  bool nested = false;
779  bool once = false;
780  int group;
781
782  if (*arg == '|') {
783    eap->nextcmd = arg + 1;
784    arg = "";
785    group = AUGROUP_ALL;  // no argument, use all groups
786  } else {
787    // Check for a legal group name.  If not, use AUGROUP_ALL.
788    group = arg_augroup_get(&arg);
789  }
790
791  // Scan over the events.
792  // If we find an illegal name, return here, don't do anything.
793  char *pat = arg_event_skip(arg, group != AUGROUP_ALL);
794  if (pat == NULL) {
795    return;
796  }
797
798  pat = skipwhite(pat);
799  if (*pat == '|') {
800    eap->nextcmd = pat + 1;
801    pat = "";
802    cmd = "";
803  } else {
804    // Scan over the pattern.  Put a NUL at the end.
805    cmd = pat;
806    while (*cmd && (!ascii_iswhite(*cmd) || cmd[-1] == '\\')) {
807      cmd++;
808    }
809    if (*cmd) {
810      *cmd++ = NUL;
811    }
812
813    // Expand environment variables in the pattern.
814    if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL) {
815      envpat = expand_env_save(pat);
816      if (envpat != NULL) {
817        pat = envpat;
818      }
819    }
820
821    cmd = skipwhite(cmd);
822
823    bool invalid_flags = false;
824    for (size_t i = 0; i < 2; i++) {
825      if (*cmd == NUL) {
826        continue;
827      }
828
829      invalid_flags |= arg_autocmd_flag_get(&once, &cmd, "++once", 6);
830      invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "++nested", 8);
831
832      // Check the deprecated "nested" flag.
833      invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "nested", 6);
834    }
835
836    if (invalid_flags) {
837      goto err_exit;
838    }
839
840    // Find the start of the commands.
841    // Expand <sfile> in it.
842    if (*cmd != NUL) {
843      cmd = expand_sfile(cmd);
844      if (cmd == NULL) {  // some error
845        goto err_exit;
846      }
847      cmd_need_free = true;
848    }
849  }
850
851  const bool is_showing = !forceit && *cmd == NUL;
852
853  // Print header when showing autocommands.
854  if (is_showing) {
855    // Highlight title
856    msg_ext_set_kind("list_cmd");
857    msg_puts_title(_("\n--- Autocommands ---"));
858
859    if (*arg == '*' || *arg == '|' || *arg == NUL) {
860      au_show_for_all_events(group, pat);
861    } else {
862      event_T event = event_name2nr(arg, &arg);
863      assert(event < NUM_EVENTS);
864      au_show_for_event(group, event, pat);
865    }
866  } else {
867    if (*arg == '*' || *arg == NUL || *arg == '|') {
868      if (*cmd != NUL) {
869        emsg(_(e_cannot_define_autocommands_for_all_events));
870      } else {
871        do_all_autocmd_events(pat, once, nested, cmd, forceit, group);
872      }
873    } else {
874      while (*arg && *arg != '|' && !ascii_iswhite(*arg)) {
875        event_T event = event_name2nr(arg, &arg);
876        assert(event < NUM_EVENTS);
877        if (do_autocmd_event(event, pat, once, nested, cmd, forceit, group) == FAIL) {
878          break;
879        }
880      }
881    }
882  }
883
884err_exit:
885  if (cmd_need_free) {
886    xfree(cmd);
887  }
888  xfree(envpat);
889}
890
891void do_all_autocmd_events(const char *pat, bool once, int nested, char *cmd, bool del, int group)
892{
893  FOR_ALL_AUEVENTS(event) {
894    if (do_autocmd_event(event, pat, once, nested, cmd, del, group) == FAIL) {
895      return;
896    }
897  }
898}
899
900// do_autocmd() for one event.
901// Defines an autocmd (does not execute; cf. apply_autocmds_group).
902//
903// If *pat == NUL: do for all patterns.
904// If *cmd == NUL: show entries.
905// If forceit == true: delete entries.
906// If group is not AUGROUP_ALL: only use this group.
907int do_autocmd_event(event_T event, const char *pat, bool once, int nested, const char *cmd,
908                     bool del, int group)
909  FUNC_ATTR_NONNULL_ALL
910{
911  // Cannot be used to show all patterns. See au_show_for_event or au_show_for_all_events
912  assert(*pat != NUL || del);
913
914  char buflocal_pat[BUFLOCAL_PAT_LEN];  // for "<buffer=X>"
915
916  bool is_adding_cmd = *cmd != NUL;
917  const int findgroup = group == AUGROUP_ALL ? current_augroup : group;
918
919  // Delete all aupat for an event.
920  if (*pat == NUL && del) {
921    aucmd_del_for_event_and_group(event, findgroup);
922    return OK;
923  }
924
925  // Loop through all the specified patterns.
926  int patlen = (int)aucmd_span_pattern(pat, &pat);
927  while (patlen) {
928    const char *endpat = pat + patlen;
929
930    // detect special <buffer[=X]> buffer-local patterns
931    bool is_buflocal = aupat_is_buflocal(pat, patlen);
932    if (is_buflocal) {
933      const int buflocal_nr = aupat_get_buflocal_nr(pat, patlen);
934
935      if (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL) {
936        semsg(_(e_buffer_nr_invalid_buffer_number), buflocal_nr);
937        return FAIL;
938      }
939      // normalize pat into standard "<buffer>#N" form
940      aupat_normalize_buflocal_pat(buflocal_pat, pat, patlen, buflocal_nr);
941
942      pat = buflocal_pat;
943      patlen = (int)strlen(buflocal_pat);
944    }
945
946    if (del) {
947      assert(*pat != NUL);
948
949      // Find existing autocommands with this pattern.
950      AutoCmdVec *const acs = &autocmds[(int)event];
951      for (size_t i = 0; i < kv_size(*acs); i++) {
952        AutoCmd *const ac = &kv_A(*acs, i);
953        AutoPat *const ap = ac->pat;
954        // Accept a pattern when:
955        // - a group was specified and it's that group
956        // - the length of the pattern matches
957        // - the pattern matches.
958        // For <buffer[=X]>, this condition works because we normalize
959        // all buffer-local patterns.
960        if (ap != NULL && ap->group == findgroup && ap->patlen == patlen
961            && strncmp(pat, ap->pat, (size_t)patlen) == 0) {
962          // Remove existing autocommands.
963          // If adding any new autocmd's for this AutoPat, don't
964          // delete the pattern from the autopat list, append to
965          // this list.
966          aucmd_del(ac);
967        }
968      }
969    }
970
971    if (is_adding_cmd) {
972      Callback handler_fn = CALLBACK_INIT;
973      autocmd_register(0, event, pat, patlen, group, once, nested, NULL, cmd, &handler_fn);
974    }
975
976    patlen = (int)aucmd_span_pattern(endpat, &pat);
977  }
978
979  au_cleanup();  // may really delete removed patterns/commands now
980  return OK;
981}
982
983/// Registers an autocmd. The handler may be a Ex command or callback function, decided by
984/// the `handler_cmd` or `handler_fn` args.
985///
986/// @param handler_cmd Handler Ex command, or NULL if handler is a function (`handler_fn`).
987/// @param handler_fn Handler function, ignored if `handler_cmd` is not NULL.
988int autocmd_register(int64_t id, event_T event, const char *pat, int patlen, int group, bool once,
989                     bool nested, char *desc, const char *handler_cmd, Callback *handler_fn)
990{
991  // 0 is not a valid group.
992  assert(group != 0);
993
994  if (patlen > (int)strlen(pat)) {
995    return FAIL;
996  }
997
998  const int findgroup = group == AUGROUP_ALL ? current_augroup : group;
999
1000  // detect special <buffer[=X]> buffer-local patterns
1001  const bool is_buflocal = aupat_is_buflocal(pat, patlen);
1002  int buflocal_nr = 0;
1003
1004  char buflocal_pat[BUFLOCAL_PAT_LEN];  // for "<buffer=X>"
1005  if (is_buflocal) {
1006    buflocal_nr = aupat_get_buflocal_nr(pat, patlen);
1007
1008    if (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL) {
1009      semsg(_(e_buffer_nr_invalid_buffer_number), buflocal_nr);
1010      return FAIL;
1011    }
1012    // normalize pat into standard "<buffer>#N" form
1013    aupat_normalize_buflocal_pat(buflocal_pat, pat, patlen, buflocal_nr);
1014
1015    pat = buflocal_pat;
1016    patlen = (int)strlen(buflocal_pat);
1017  }
1018
1019  // Try to reuse pattern from the last existing autocommand.
1020  AutoPat *ap = NULL;
1021  AutoCmdVec *const acs = &autocmds[(int)event];
1022  for (ptrdiff_t i = (ptrdiff_t)kv_size(*acs) - 1; i >= 0; i--) {
1023    ap = kv_A(*acs, i).pat;
1024    if (ap == NULL) {
1025      continue;  // Skip deleted autocommands.
1026    }
1027    // Set result back to NULL if the last pattern doesn't match.
1028    if (ap->group != findgroup || ap->patlen != patlen
1029        || strncmp(pat, ap->pat, (size_t)patlen) != 0) {
1030      ap = NULL;
1031    }
1032    break;
1033  }
1034
1035  // No matching pattern found, allocate a new one.
1036  if (ap == NULL) {
1037    ap = xmalloc(sizeof(AutoPat));
1038
1039    if (is_buflocal) {
1040      ap->buflocal_nr = buflocal_nr;
1041      ap->reg_prog = NULL;
1042    } else {
1043      ap->buflocal_nr = 0;
1044      char *reg_pat = file_pat_to_reg_pat(pat, pat + patlen, &ap->allow_dirs, true);
1045      if (reg_pat != NULL) {
1046        // RE_NOBREAK: autocmd-pattern matching (aucmd_next()) must not os_breakcheck(). #35071
1047        ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC | RE_NOBREAK);
1048      }
1049      xfree(reg_pat);
1050      if (reg_pat == NULL || ap->reg_prog == NULL) {
1051        xfree(ap);
1052        return FAIL;
1053      }
1054    }
1055
1056    ap->refcount = 0;
1057    ap->pat = xmemdupz(pat, (size_t)patlen);
1058    ap->patlen = patlen;
1059
1060    // need to initialize last_mode for the first ModeChanged autocmd
1061    if (event == EVENT_MODECHANGED && !has_event(EVENT_MODECHANGED)) {
1062      get_mode(last_mode);
1063    }
1064
1065    // If the event is CursorMoved or CursorMovedI, update the last cursor position
1066    // position to avoid immediately triggering the autocommand
1067    if ((event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED))
1068        || (event == EVENT_CURSORMOVEDI && !has_event(EVENT_CURSORMOVEDI))) {
1069      last_cursormoved_win = curwin;
1070      last_cursormoved = curwin->w_cursor;
1071    }
1072
1073    // Initialize the fields checked by the WinScrolled and
1074    // WinResized trigger to prevent them from firing right after
1075    // the first autocmd is defined.
1076    if ((event == EVENT_WINSCROLLED || event == EVENT_WINRESIZED)
1077        && !(has_event(EVENT_WINSCROLLED) || has_event(EVENT_WINRESIZED))) {
1078      tabpage_T *save_curtab = curtab;
1079      FOR_ALL_TABS(tp) {
1080        unuse_tabpage(curtab);
1081        use_tabpage(tp);
1082        snapshot_windows_scroll_size();
1083      }
1084      unuse_tabpage(curtab);
1085      use_tabpage(save_curtab);
1086    }
1087
1088    ap->group = group == AUGROUP_ALL ? current_augroup : group;
1089  }
1090
1091  ap->refcount++;
1092
1093  // Add the autocmd at the end of the AutoCmd vector.
1094  AutoCmd *ac = kv_pushp(autocmds[(int)event]);
1095  ac->pat = ap;
1096  ac->id = id;
1097  if (handler_cmd) {
1098    ac->handler_cmd = xstrdup(handler_cmd);
1099  } else {
1100    ac->handler_cmd = NULL;
1101    callback_copy(&ac->handler_fn, handler_fn);
1102  }
1103  ac->script_ctx = current_sctx;
1104  ac->script_ctx.sc_lnum += SOURCING_LNUM;
1105  nlua_set_sctx(&ac->script_ctx);
1106  ac->once = once;
1107  ac->nested = nested;
1108  ac->desc = desc == NULL ? NULL : xstrdup(desc);
1109
1110  return OK;
1111}
1112
1113size_t aucmd_span_pattern(const char *pat, const char **start)
1114  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1115{
1116  // Skip leading commas.
1117  while (*pat == ',') {
1118    pat++;
1119  }
1120
1121  // Find end of the pattern.
1122  // Watch out for a comma in braces, like "*.\{obj,o\}".
1123  const char *p = pat;
1124  int brace_level = 0;
1125  for (; *p && (*p != ',' || brace_level || (p > pat && p[-1] == '\\')); p++) {
1126    if (*p == '{') {
1127      brace_level++;
1128    } else if (*p == '}') {
1129      brace_level--;
1130    }
1131  }
1132
1133  *start = pat;
1134  return (size_t)(p - pat);
1135}
1136
1137/// Implementation of ":doautocmd [group] event [fname]".
1138/// Return OK for success, FAIL for failure;
1139///
1140/// @param do_msg  give message for no matching autocmds?
1141int do_doautocmd(char *arg_start, bool do_msg, bool *did_something)
1142{
1143  char *arg = arg_start;
1144  int nothing_done = true;
1145
1146  if (did_something != NULL) {
1147    *did_something = false;
1148  }
1149
1150  // Check for a legal group name.  If not, use AUGROUP_ALL.
1151  int group = arg_augroup_get(&arg);
1152
1153  if (*arg == '*') {
1154    emsg(_("E217: Can't execute autocommands for ALL events"));
1155    return FAIL;
1156  }
1157
1158  // Scan over the events.
1159  // If we find an illegal name, return here, don't do anything.
1160  char *fname = arg_event_skip(arg, group != AUGROUP_ALL);
1161  if (fname == NULL) {
1162    return FAIL;
1163  }
1164
1165  fname = skipwhite(fname);
1166
1167  // Loop over the events.
1168  while (*arg && !ends_excmd(*arg) && !ascii_iswhite(*arg)) {
1169    if (apply_autocmds_group(event_name2nr(arg, &arg), fname, NULL, true, group,
1170                             curbuf, curwin, NULL, NULL, false)) {
1171      nothing_done = false;
1172    }
1173  }
1174
1175  if (nothing_done && do_msg && !aborting()) {
1176    smsg(0, _("No matching autocommands: %s"), arg_start);
1177  }
1178  if (did_something != NULL) {
1179    *did_something = !nothing_done;
1180  }
1181
1182  return aborting() ? FAIL : OK;
1183}
1184
1185// ":doautoall": execute autocommands for each loaded buffer.
1186void ex_doautoall(exarg_T *eap)
1187{
1188  int retval = OK;
1189  CtxSwitch aco = { 0 };
1190  char *arg = eap->arg;
1191  int call_do_modelines = check_nomodeline(&arg);
1192  bufref_T bufref;
1193  bool did_aucmd;
1194
1195  // This is a bit tricky: For some commands curwin->w_buffer needs to be
1196  // equal to curbuf, but for some buffers there may not be a window.
1197  // So we change the buffer for the current window for a moment.  This
1198  // gives problems when the autocommands make changes to the list of
1199  // buffers or windows...
1200  FOR_ALL_BUFFERS(buf) {
1201    // Only do loaded buffers and skip the current buffer, it's done last.
1202    if (buf->b_ml.ml_mfp == NULL || buf == curbuf) {
1203      continue;
1204    }
1205
1206    // Find a window for this buffer and save some values.
1207    ctx_switch(&aco, NULL, NULL, buf, 0);
1208    set_bufref(&bufref, buf);
1209
1210    // execute the autocommands for this buffer
1211    retval = do_doautocmd(arg, false, &did_aucmd);
1212
1213    if (call_do_modelines && did_aucmd) {
1214      // Execute the modeline settings, but don't set window-local
1215      // options if we are using the current window for another
1216      // buffer.
1217      do_modelines(is_ctx_win(curwin) ? OPT_NOWIN : 0);
1218    }
1219
1220    // restore the current window
1221    ctx_restore(&aco);
1222
1223    // Stop if there is some error or buffer was deleted.
1224    if (retval == FAIL || !bufref_valid(&bufref)) {
1225      retval = FAIL;
1226      break;
1227    }
1228  }
1229
1230  // Execute autocommands for the current buffer last.
1231  if (retval == OK) {
1232    do_doautocmd(arg, false, &did_aucmd);
1233    if (call_do_modelines && did_aucmd) {
1234      do_modelines(0);
1235    }
1236  }
1237}
1238
1239/// Check *argp for <nomodeline>.  When it is present return false, otherwise
1240/// return true and advance *argp to after it. Thus do_modelines() should be
1241/// called when true is returned.
1242///
1243/// @param[in,out] argp argument string
1244bool check_nomodeline(char **argp)
1245  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1246{
1247  if (strncmp(*argp, "<nomodeline>", 12) == 0) {
1248    *argp = skipwhite(*argp + 12);
1249    return false;
1250  }
1251  return true;
1252}
1253
1254/// Schedules an autocommand event, to be executed at the next event-loop tick.
1255///
1256/// @param event Event to schedule
1257/// @param fname Name to use as `<amatch>` (the "pattern"). NULL/empty means use actual filename.
1258/// @param fname_io Filename to use for <afile> on cmdline, NULL means use `fname`.
1259/// @param group Group ID or AUGROUP_ALL
1260/// @param buf Buffer for <abuf>
1261/// @param eap Ex command arguments
1262/// @param data Event-specific data. Will be copied, caller must free `data`.
1263/// The `data` items will also be copied to `v:event`.
1264void aucmd_defer(event_T event, char *fname, char *fname_io, int group, buf_T *buf, exarg_T *eap,
1265                 Object *data)
1266{
1267  AutoCmdEvent *evdata = xmalloc(sizeof(AutoCmdEvent));
1268  evdata->event = event;
1269  evdata->fname = fname != NULL ? xstrdup(fname) : NULL;
1270  evdata->fname_io = fname_io != NULL ? xstrdup(fname_io) : NULL;
1271  evdata->group = group;
1272  evdata->buf = buf->handle;
1273  evdata->eap = eap;
1274  if (data) {
1275    evdata->data = xmalloc(sizeof(Object));
1276    *evdata->data = copy_object(*data, NULL);
1277  } else {
1278    evdata->data = NULL;
1279  }
1280
1281  multiqueue_put(deferred_events, deferred_event, evdata);
1282}
1283
1284/// Executes a deferred autocommand event.
1285static void deferred_event(void **argv)
1286{
1287  AutoCmdEvent *e = argv[0];
1288  event_T event = e->event;
1289  char *fname = e->fname;
1290  char *fname_io = e->fname_io;
1291  int group = e->group;
1292  exarg_T *eap = e->eap;
1293  Object *data = e->data;
1294
1295  Error err = ERROR_INIT;
1296  buf_T *buf = find_buffer_by_handle(e->buf, &err);
1297  if (buf) {
1298    // Copy `data` to `v:event`.
1299    save_v_event_T save_v_event;
1300    dict_T *v_event = get_v_event(&save_v_event);
1301    if (data && data->type == kObjectTypeDict) {
1302      for (size_t i = 0; i < data->data.dict.size; i++) {
1303        KeyValuePair item = data->data.dict.items[i];
1304        typval_T tv;
1305        object_to_vim(item.value, &tv, &err);
1306        if (ERROR_SET(&err)) {
1307          api_clear_error(&err);
1308          continue;
1309        }
1310        tv_dict_add_tv(v_event, item.key.data, item.key.size, &tv);
1311        tv_clear(&tv);
1312      }
1313    }
1314    tv_dict_set_keys_readonly(v_event);
1315
1316    win_T *win = curwin;  // before ctx_switch() may make the context window current
1317
1318    CtxSwitch aco = { 0 };
1319    ctx_switch(&aco, NULL, NULL, buf, 0);
1320    apply_autocmds_group(event, fname, fname_io, false, group, buf, win, eap, data, false);
1321    ctx_restore(&aco);
1322
1323    restore_v_event(v_event, &save_v_event);
1324  }
1325
1326  xfree(fname);
1327  xfree(fname_io);
1328  if (data) {
1329    api_free_object(*data);
1330    xfree(data);
1331  }
1332  xfree(e);
1333}
1334
1335static void deferred_optionset_modified(void **argv)
1336{
1337  Error err = ERROR_INIT;
1338  buf_T *buf = find_buffer_by_handle((handle_T)(uintptr_t)argv[0], &err);
1339  api_clear_error(&err);
1340  if (buf) {
1341    bool new_val = (bool)(uintptr_t)argv[1];
1342    Object old = BOOLEAN_OBJ(!new_val);
1343    Object new = BOOLEAN_OBJ(new_val);
1344    CtxSwitch aco = { 0 };
1345    ctx_switch(&aco, NULL, NULL, buf, 0);
1346    apply_optionset_autocmd_now(kOptModified, OPT_LOCAL, old, old, old, new);
1347    ctx_restore(&aco);
1348  }
1349}
1350
1351/// Special case of aucmd_defer for `OptionSet modified`.
1352void aucmd_defer_modified(buf_T *buf, bool new_val)
1353{
1354  if (!has_event(EVENT_OPTIONSET)
1355      || (bt_nofile(buf) && !buf->b_p_bl)
1356      || *get_vim_var_str(VV_OPTION_TYPE) != NUL) {
1357    return;
1358  }
1359  multiqueue_put(deferred_events, deferred_optionset_modified,
1360                 (void *)(uintptr_t)buf->handle,
1361                 (void *)(uintptr_t)new_val);
1362}
1363
1364/// Execute autocommands for "event" and file name "fname".
1365///
1366/// `ev.win` is curwin; use apply_autocmds_win() for window-specific events.
1367///
1368/// @param event event that occurred
1369/// @param fname filename, NULL or empty means use actual file name
1370/// @param fname_io filename to use for <afile> on cmdline
1371/// @param force Ignore autocmd_busy (force "++nested" behavior)
1372/// @param buf Buffer for <abuf>
1373///
1374/// @return true if some commands were executed.
1375bool apply_autocmds(event_T event, char *fname, char *fname_io, bool force, buf_T *buf)
1376{
1377  return apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, curwin, NULL, NULL,
1378                              false);
1379}
1380
1381/// Like apply_autocmds(), but with an explicit window for `ev.win`.
1382///
1383/// @param win Window for `ev.win`, NULL for the current window.
1384///
1385/// @return true if some commands were executed.
1386bool apply_autocmds_win(event_T event, char *fname, char *fname_io, bool force, buf_T *buf,
1387                        win_T *win)
1388{
1389  return apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, win, NULL, NULL,
1390                              false);
1391}
1392
1393/// Like apply_autocmds(), but with extra "eap" argument.  This takes care of
1394/// setting v:filearg.
1395///
1396/// @param event event that occurred
1397/// @param fname NULL or empty means use actual file name
1398/// @param fname_io fname to use for <afile> on cmdline
1399/// @param force Ignore autocmd_busy (force "++nested" behavior)
1400/// @param buf Buffer for <abuf>
1401/// @param exarg Ex command arguments
1402///
1403/// @return true if some commands were executed.
1404bool apply_autocmds_exarg(event_T event, char *fname, char *fname_io, bool force, buf_T *buf,
1405                          exarg_T *eap)
1406{
1407  return apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, curwin, eap, NULL,
1408                              false);
1409}
1410
1411/// Like apply_autocmds(), but handles the caller's retval.  If the script
1412/// processing is being aborted or if retval is FAIL when inside a try
1413/// conditional, no autocommands are executed.  If otherwise the autocommands
1414/// cause the script to be aborted, retval is set to FAIL.
1415///
1416/// @param event event that occurred
1417/// @param fname NULL or empty means use actual file name
1418/// @param fname_io fname to use for <afile> on cmdline
1419/// @param force Ignore autocmd_busy (force "++nested" behavior)
1420/// @param buf Buffer for <abuf>
1421/// @param[in,out] retval caller's retval
1422///
1423/// @return true if some autocommands were executed
1424bool apply_autocmds_retval(event_T event, char *fname, char *fname_io, bool force, buf_T *buf,
1425                           int *retval)
1426{
1427  if (should_abort(*retval)) {
1428    return false;
1429  }
1430
1431  bool did_cmd = apply_autocmds_group(event, fname, fname_io, force, AUGROUP_ALL, buf, curwin, NULL,
1432                                      NULL, false);
1433  if (did_cmd && aborting()) {
1434    *retval = FAIL;
1435  }
1436  return did_cmd;
1437}
1438
1439/// Return true if "event" autocommand is defined.
1440///
1441/// @param event the autocommand to check
1442bool has_event(event_T event) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1443{
1444  return kv_size(autocmds[(int)event]) != 0;
1445}
1446
1447/// Return true when there is a CursorHold/CursorHoldI autocommand defined for
1448/// the current mode.
1449static bool has_cursorhold(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1450{
1451  return has_event((get_real_state() == MODE_NORMAL_BUSY ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI));
1452}
1453
1454/// Return true if the CursorHold/CursorHoldI event can be triggered.
1455bool trigger_cursorhold(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1456{
1457  if (!did_cursorhold && has_cursorhold() && reg_recording == 0
1458      && typebuf.tb_len == 0 && !ins_compl_active()) {
1459    int state = get_real_state();
1460    if (state == MODE_NORMAL_BUSY || (state & MODE_INSERT) != 0) {
1461      return true;
1462    }
1463  }
1464  return false;
1465}
1466
1467/// Execute autocommands for "event" and file name "fname".
1468///
1469/// @param event event that occurred
1470/// @param fname filename, NULL or empty means use actual file name
1471/// @param fname_io filename to use for <afile> on cmdline,
1472///                 NULL means use `fname`.
1473/// @param force Ignore autocmd_busy (force "++nested" behavior)
1474/// @param group autocmd group ID or AUGROUP_ALL
1475/// @param buf Buffer for <abuf>
1476/// @param win Window for `ev.win`, NULL for the current window.
1477/// @param eap Ex command arguments
1478/// @param with_buf Run callbacks with "buf" as the current buffer
1479///
1480/// @return true if some commands were executed.
1481bool apply_autocmds_group(event_T event, char *fname, char *fname_io, bool force, int group,
1482                          buf_T *buf, win_T *win, exarg_T *eap, Object *data, bool with_buf)
1483{
1484  char *sfname = NULL;  // short file name
1485  bool retval = false;
1486  static int nesting = 0;
1487  char *save_cmdarg;
1488  static bool filechangeshell_busy = false;
1489  proftime_T wait_time;
1490  bool did_save_redobuff = false;
1491  RedoState save_redo;
1492  const bool save_KeyTyped = KeyTyped;
1493  ESTACK_CHECK_DECLARATION;
1494  CtxSwitch aco = { 0 };
1495  bool save_changed = false;
1496  buf_T *old_curbuf = NULL;
1497
1498  // Quickly return if there are no autocommands for this event or
1499  // autocommands are blocked.
1500  if (event == NUM_EVENTS || kv_size(autocmds[(int)event]) == 0 || is_autocmd_blocked()) {
1501    goto BYPASS_AU;
1502  }
1503
1504  // When autocommands are busy, new autocommands are only executed when
1505  // explicitly enabled with the "nested" flag.
1506  if (autocmd_busy && !(force || autocmd_nested)) {
1507    goto BYPASS_AU;
1508  }
1509
1510  // Quickly return when immediately aborting on error, or when an interrupt
1511  // occurred or an exception was thrown but not caught.
1512  if (aborting()) {
1513    goto BYPASS_AU;
1514  }
1515
1516  // FileChangedShell never nests, because it can create an endless loop.
1517  if (filechangeshell_busy
1518      && (event == EVENT_FILECHANGEDSHELL || event == EVENT_FILECHANGEDSHELLPOST)) {
1519    goto BYPASS_AU;
1520  }
1521
1522  // Ignore events in 'eventignore'.
1523  if (event_ignored(event, p_ei)) {
1524    goto BYPASS_AU;
1525  }
1526
1527  bool win_ignore = false;
1528  // If event is allowed in 'eventignorewin', check if curwin or all windows
1529  // into "buf" are ignoring the event.
1530  if (buf == curbuf && event_names[event].event <= 0) {
1531    win_ignore = event_ignored(event, curwin->w_p_eiw);
1532  } else if (buf != NULL && event_names[event].event <= 0 && buf->b_nwindows > 0) {
1533    win_ignore = true;
1534    FOR_ALL_TAB_WINDOWS(tp, wp) {
1535      if (wp->w_buffer == buf && !event_ignored(event, wp->w_p_eiw)) {
1536        win_ignore = false;
1537        break;
1538      }
1539    }
1540  }
1541  if (win_ignore) {
1542    goto BYPASS_AU;
1543  }
1544
1545  // Allow nesting of autocommands, but restrict the depth, because it's
1546  // possible to create an endless loop.
1547  if (nesting == 10) {
1548    emsg(_(e_autocommand_nesting_too_deep));
1549    goto BYPASS_AU;
1550  }
1551
1552  // Check if these autocommands are disabled.  Used when doing ":all" or
1553  // ":ball".
1554  if ((autocmd_no_enter && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
1555      || (autocmd_no_leave && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE))) {
1556    goto BYPASS_AU;
1557  }
1558
1559  // Save the autocmd_* variables and info about the current buffer.
1560  char *save_autocmd_fname = autocmd_fname;
1561  bool save_autocmd_fname_full = autocmd_fname_full;
1562  int save_autocmd_bufnr = autocmd_bufnr;
1563  handle_T save_autocmd_winid = autocmd_winid;
1564  char *save_autocmd_match = autocmd_match;
1565  int save_autocmd_busy = autocmd_busy;
1566  int save_autocmd_nested = autocmd_nested;
1567  // Set the file name to be used for <afile>.
1568  // Make a copy to avoid that changing a buffer name or directory makes it
1569  // invalid.
1570  if (fname_io == NULL) {
1571    if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
1572        || event == EVENT_OPTIONSET || event == EVENT_MODECHANGED
1573        || event == EVENT_MARKSET) {
1574      autocmd_fname = NULL;
1575    } else if (fname != NULL && !ends_excmd(*fname)) {
1576      autocmd_fname = fname;
1577    } else if (buf != NULL) {
1578      autocmd_fname = buf->b_ffname;
1579    } else {
1580      autocmd_fname = NULL;
1581    }
1582  } else {
1583    autocmd_fname = fname_io;
1584  }
1585  char *afile_orig = NULL;  ///< Unexpanded <afile>
1586  if (autocmd_fname != NULL) {
1587    afile_orig = xstrdup(autocmd_fname);
1588    // Allocate MAXPATHL for when eval_vars() resolves the fullpath.
1589    autocmd_fname = xstrnsave(autocmd_fname, MAXPATHL);
1590  }
1591  autocmd_fname_full = false;  // call FullName_save() later
1592
1593  // Set the buffer number to be used for <abuf>.
1594  autocmd_bufnr = buf == NULL ? 0 : buf->b_fnum;
1595
1596  // When the file name is NULL or empty, use the file name of buffer "buf".
1597  // Always use the full path of the file name to match with, in case
1598  // "allow_dirs" is set.
1599  if (fname == NULL || *fname == NUL) {
1600    if (buf == NULL) {
1601      fname = NULL;
1602    } else {
1603      if (event == EVENT_SYNTAX) {
1604        fname = buf->b_p_syn;
1605      } else if (event == EVENT_FILETYPE) {
1606        fname = buf->b_p_ft;
1607      } else {
1608        if (buf->b_sfname != NULL) {
1609          sfname = xstrdup(buf->b_sfname);
1610        }
1611        fname = buf->b_ffname;
1612      }
1613    }
1614    if (fname == NULL) {
1615      fname = "";
1616    }
1617    fname = xstrdup(fname);  // make a copy, so we can change it
1618  } else {
1619    sfname = TO_SLASH_SAVE(fname);
1620    // Don't try expanding the following events.
1621    if (event == EVENT_CMDATOM
1622        || event == EVENT_CMDLINECHANGED
1623        || event == EVENT_CMDLINEENTER
1624        || event == EVENT_CMDLINELEAVEPRE
1625        || event == EVENT_CMDLINELEAVE
1626        || event == EVENT_CMDUNDEFINED
1627        || event == EVENT_CURSORMOVEDC
1628        || event == EVENT_CMDWINENTER
1629        || event == EVENT_CMDWINLEAVE
1630        || event == EVENT_COLORSCHEME
1631        || event == EVENT_COLORSCHEMEPRE
1632        || event == EVENT_DIRCHANGED
1633        || event == EVENT_DIRCHANGEDPRE
1634        || event == EVENT_FILETYPE
1635        || event == EVENT_FUNCUNDEFINED
1636        || event == EVENT_MARKSET
1637        || event == EVENT_MENUPOPUP
1638        || event == EVENT_MODECHANGED
1639        || event == EVENT_OPTIONSET
1640        || event == EVENT_PROGRESS
1641        || event == EVENT_QUICKFIXCMDPOST
1642        || event == EVENT_QUICKFIXCMDPRE
1643        || event == EVENT_REMOTEREPLY
1644        || event == EVENT_SIGNAL
1645        || event == EVENT_SPELLFILEMISSING
1646        || event == EVENT_SYNTAX
1647        || event == EVENT_TABCLOSED
1648        || event == EVENT_TABMOVED
1649        || event == EVENT_USER
1650        || event == EVENT_WINCLOSED
1651        || event == EVENT_WINRESIZED
1652        || event == EVENT_WINSCROLLED) {
1653      fname = TO_SLASH_SAVE(fname);
1654      autocmd_fname_full = true;  // don't expand it later
1655    } else {
1656      fname = FullName_save(fname, false);
1657    }
1658  }
1659  if (fname == NULL) {  // out of memory
1660    xfree(sfname);
1661    retval = false;
1662    goto BYPASS_AU;
1663  }
1664
1665  // Set the window handle for `ev.win`.  After the last "goto BYPASS_AU", which
1666  // skips the restore below, and before ctx_switch().
1667  autocmd_winid = win != NULL ? win->handle : (curwin != NULL ? curwin->handle : 0);
1668
1669  if (with_buf && buf != NULL && buf != curbuf) {
1670    ctx_switch(&aco, NULL, NULL, buf, 0);
1671  }
1672
1673  save_changed = curbuf->b_changed;
1674  old_curbuf = curbuf;
1675
1676  // Set the name to be used for <amatch>.
1677  autocmd_match = fname;
1678
1679  // Don't redraw while doing autocommands.
1680  RedrawingDisabled++;
1681
1682  // name and lnum are filled in later
1683  estack_push(ETYPE_AUCMD, NULL, 0);
1684  ESTACK_CHECK_SETUP;
1685
1686  const sctx_T save_current_sctx = current_sctx;
1687
1688  if (do_profiling == PROF_YES) {
1689    prof_child_enter(&wait_time);  // doesn't count for the caller itself
1690  }
1691
1692  // Don't use local function variables, if called from a function.
1693  funccal_entry_T funccal_entry;
1694  save_funccal(&funccal_entry);
1695
1696  // When starting to execute autocommands, save the search patterns.
1697  if (!autocmd_busy) {
1698    save_search_patterns();
1699    if (!ins_compl_active()) {
1700      save_redobuff(&save_redo);
1701      did_save_redobuff = true;
1702    }
1703    curbuf->b_did_filetype = curbuf->b_keep_filetype;
1704  }
1705
1706  // Note that we are applying autocmds.  Some commands need to know.
1707  autocmd_busy = true;
1708  filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
1709  nesting++;  // see matching decrement below
1710
1711  // Remember that FileType was triggered, if 'filetype' was actually set.  For :setf.
1712  if (event == EVENT_FILETYPE && *curbuf->b_p_ft != NUL) {
1713    curbuf->b_did_filetype = true;
1714  }
1715
1716  char *tail = path_tail(fname);
1717
1718  // Find first autocommand that matches
1719  AutoPatCmd patcmd = {
1720    // aucmd_next will set lastpat back to NULL if there are no more autocommands left to run
1721    .lastpat = NULL,
1722    // current autocommand index
1723    .auidx = 0,
1724    // save vector size, to avoid an endless loop when more patterns
1725    // are added when executing autocommands
1726    .ausize = kv_size(autocmds[(int)event]),
1727    .afile_orig = afile_orig,
1728    .fname = fname,
1729    .sfname = sfname,
1730    .tail = tail,
1731    .group = group,
1732    .event = event,
1733    .arg_bufnr = autocmd_bufnr,
1734  };
1735  aucmd_next(&patcmd);
1736
1737  // Found first autocommand, start executing them
1738  if (patcmd.lastpat != NULL) {
1739    // add to active_apc_list
1740    patcmd.next = active_apc_list;
1741    active_apc_list = &patcmd;
1742
1743    // Attach data to command
1744    patcmd.data = data;
1745
1746    // set v:cmdarg (only when there is a matching pattern)
1747    varnumber_T save_cmdbang = get_vim_var_nr(VV_CMDBANG);
1748    if (eap != NULL) {
1749      save_cmdarg = set_cmdarg(eap, NULL);
1750      set_vim_var_nr(VV_CMDBANG, eap->forceit);
1751    } else {
1752      save_cmdarg = NULL;  // avoid gcc warning
1753    }
1754    retval = true;
1755
1756    // Make sure cursor and topline are valid.  The first time the current
1757    // values are saved, restored by reset_lnums().  When nested only the
1758    // values are corrected when needed.
1759    if (nesting == 1) {
1760      check_lnums(true);
1761    } else {
1762      check_lnums_nested(true);
1763    }
1764
1765    const int save_did_emsg = did_emsg;
1766
1767    // Execute the autocmd. The `getnextac` callback handles iteration.
1768    do_cmdline(NULL, getnextac, &patcmd, DOCMD_NOWAIT | DOCMD_VERBOSE | DOCMD_REPEAT);
1769
1770    did_emsg += save_did_emsg;
1771
1772    if (nesting == 1) {
1773      // restore cursor and topline, unless they were changed
1774      reset_lnums();
1775    }
1776
1777    if (eap != NULL) {
1778      set_cmdarg(NULL, save_cmdarg);
1779      set_vim_var_nr(VV_CMDBANG, save_cmdbang);
1780    }
1781    // delete from active_apc_list
1782    if (active_apc_list == &patcmd) {  // just in case
1783      active_apc_list = patcmd.next;
1784    }
1785  }
1786
1787  RedrawingDisabled--;
1788  autocmd_busy = save_autocmd_busy;
1789  filechangeshell_busy = false;
1790  autocmd_nested = save_autocmd_nested;
1791  xfree(SOURCING_NAME);
1792  ESTACK_CHECK_NOW;
1793  estack_pop();
1794  xfree(afile_orig);
1795  xfree(autocmd_fname);
1796  autocmd_fname = save_autocmd_fname;
1797  autocmd_fname_full = save_autocmd_fname_full;
1798  autocmd_bufnr = save_autocmd_bufnr;
1799  autocmd_winid = save_autocmd_winid;
1800  autocmd_match = save_autocmd_match;
1801  current_sctx = save_current_sctx;
1802  restore_funccal();
1803  if (do_profiling == PROF_YES) {
1804    prof_child_exit(&wait_time);
1805  }
1806  KeyTyped = save_KeyTyped;
1807  xfree(fname);
1808  xfree(sfname);
1809  nesting--;  // see matching increment above
1810
1811  // When stopping to execute autocommands, restore the search patterns and
1812  // the redo buffer. Free any buffers in the au_pending_free_buf list and
1813  // free any windows in the au_pending_free_win list.
1814  if (!autocmd_busy) {
1815    restore_search_patterns();
1816    if (did_save_redobuff) {
1817      restore_redobuff(&save_redo);
1818    }
1819    curbuf->b_did_filetype = false;
1820    while (au_pending_free_buf != NULL) {
1821      buf_T *b = au_pending_free_buf->b_next;
1822
1823      xfree(au_pending_free_buf);
1824      au_pending_free_buf = b;
1825    }
1826    while (au_pending_free_win != NULL) {
1827      win_T *w = au_pending_free_win->w_next;
1828
1829      xfree(au_pending_free_win);
1830      au_pending_free_win = w;
1831    }
1832  }
1833
1834  // Some events don't set or reset the Changed flag.
1835  // Check if still in the same buffer!
1836  if (curbuf == old_curbuf
1837      && (event == EVENT_BUFREADPOST || event == EVENT_BUFWRITEPOST
1838          || event == EVENT_FILEAPPENDPOST || event == EVENT_VIMLEAVE
1839          || event == EVENT_VIMLEAVEPRE)) {
1840    if (curbuf->b_changed != save_changed) {
1841      need_maketitle = true;
1842    }
1843    curbuf->b_changed = save_changed;
1844  }
1845
1846  au_cleanup();  // may really delete removed patterns/commands now
1847
1848BYPASS_AU:
1849  // When wiping out a buffer make sure all its buffer-local autocommands
1850  // are deleted.
1851  if (event == EVENT_BUFWIPEOUT && buf != NULL) {
1852    aubuflocal_remove(buf);
1853  }
1854
1855  if (retval == OK && event == EVENT_FILETYPE) {
1856    curbuf->b_au_did_filetype = true;
1857  }
1858
1859  ctx_restore(&aco);
1860
1861  return retval;
1862}
1863
1864void do_termresponse_autocmd(const String sequence, uint64_t channel_id)
1865{
1866  MAXSIZE_TEMP_DICT(data, 2);
1867  PUT_C(data, "sequence", STRING_OBJ(sequence));
1868  PUT_C(data, "chan", INTEGER_OBJ((Integer)channel_id));
1869  apply_autocmds_group(EVENT_TERMRESPONSE, NULL, NULL, true, AUGROUP_ALL, NULL, curwin, NULL,
1870                       &DICT_OBJ(data), false);
1871  termresponse_changed = true;
1872  termresponse_chan_id = channel_id;
1873}
1874
1875// Block triggering autocommands until unblock_autocmd() is called.
1876// Can be used recursively, so long as it's symmetric.
1877void block_autocmds(void)
1878{
1879  // Detect if v:termresponse is set while blocked.
1880  if (!is_autocmd_blocked()) {
1881    termresponse_changed = false;
1882    termresponse_chan_id = 0;
1883  }
1884  autocmd_blocked++;
1885}
1886
1887void unblock_autocmds(void)
1888{
1889  autocmd_blocked--;
1890
1891  // When v:termresponse was set while autocommands were blocked, trigger
1892  // the autocommands now.  Esp. useful when executing a shell command
1893  // during startup (nvim -d).
1894  if (!is_autocmd_blocked() && termresponse_changed && has_event(EVENT_TERMRESPONSE)) {
1895    // Copied to a new allocation, as termresponse may be freed during the event.
1896    const String sequence = cstr_to_string(get_vim_var_str(VV_TERMRESPONSE));
1897    do_termresponse_autocmd(sequence, termresponse_chan_id);
1898    api_free_string(sequence);
1899  }
1900}
1901
1902bool is_autocmd_blocked(void)
1903  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1904{
1905  return autocmd_blocked != 0;
1906}
1907
1908/// Find next matching autocommand.
1909/// If next autocommand was not found, sets lastpat to NULL and cmdidx to SIZE_MAX on apc.
1910static void aucmd_next(AutoPatCmd *apc)
1911{
1912  estack_T *const entry = ((estack_T *)exestack.ga_data) + exestack.ga_len - 1;
1913
1914  AutoCmdVec *const acs = &autocmds[(int)apc->event];
1915  assert(apc->ausize <= kv_size(*acs));
1916  for (size_t i = apc->auidx; i < apc->ausize && !got_int; i++) {
1917    AutoCmd *const ac = &kv_A(*acs, i);
1918    AutoPat *const ap = ac->pat;
1919
1920    // Skip deleted autocommands.
1921    if (ap == NULL) {
1922      continue;
1923    }
1924    // Skip matching if pattern didn't change.
1925    if (ap != apc->lastpat) {
1926      // Skip autocommands that don't match the group.
1927      if (apc->group != AUGROUP_ALL && apc->group != ap->group) {
1928        continue;
1929      }
1930      // Skip autocommands that don't match the pattern or buffer number.
1931      if (ap->buflocal_nr == 0
1932          ? !match_file_pat(NULL, &ap->reg_prog, apc->fname, apc->sfname, apc->tail, ap->allow_dirs)
1933          : ap->buflocal_nr != apc->arg_bufnr) {
1934        continue;
1935      }
1936
1937      const char *const name = event_nr2name(apc->event);
1938      const char *const s = _("%s Autocommands for \"%s\"");
1939
1940      const size_t sourcing_name_len = strlen(s) + strlen(name) + (size_t)ap->patlen + 1;
1941      char *const namep = xmalloc(sourcing_name_len);
1942      snprintf(namep, sourcing_name_len, s, name, ap->pat);
1943      if (p_verbose >= 8) {
1944        verbose_enter();
1945        smsg(0, _("Executing %s"), namep);
1946        verbose_leave();
1947      }
1948
1949      // Update the exestack entry for this autocmd.
1950      XFREE_CLEAR(entry->es_name);
1951      entry->es_name = namep;
1952      entry->es_info.aucmd = apc;
1953    }
1954
1955    apc->lastpat = ap;
1956    apc->auidx = i;
1957
1958    line_breakcheck();
1959    return;
1960  }
1961
1962  // Clear the exestack entry for this ETYPE_AUCMD entry.
1963  XFREE_CLEAR(entry->es_name);
1964  entry->es_info.aucmd = NULL;
1965
1966  apc->lastpat = NULL;
1967  apc->auidx = SIZE_MAX;
1968}
1969
1970/// Executes an autocmd callback function (as opposed to an Ex command).
1971static bool au_callback(const AutoCmd *ac, const AutoPatCmd *apc)
1972{
1973  Callback callback = ac->handler_fn;
1974  if (callback.type == kCallbackLua) {
1975    MAXSIZE_TEMP_DICT(data, 8);
1976    PUT_C(data, "id", INTEGER_OBJ(ac->id));
1977    PUT_C(data, "event", CSTR_AS_OBJ(event_nr2name(apc->event)));
1978    PUT_C(data, "file", CSTR_AS_OBJ(apc->afile_orig));
1979    PUT_C(data, "match", CSTR_AS_OBJ(autocmd_match));
1980    PUT_C(data, "buf", INTEGER_OBJ(autocmd_bufnr));
1981    PUT_C(data, "win", INTEGER_OBJ(autocmd_winid));
1982
1983    if (apc->data) {
1984      PUT_C(data, "data", *apc->data);
1985    }
1986
1987    int group = ac->pat->group;
1988    switch (group) {
1989    case AUGROUP_ERROR:
1990      abort();  // unreachable
1991    case AUGROUP_DEFAULT:
1992    case AUGROUP_ALL:
1993    case AUGROUP_DELETED:
1994      // omit group in these cases
1995      break;
1996    default:
1997      PUT_C(data, "group", INTEGER_OBJ(group));
1998      break;
1999    }
2000
2001    MAXSIZE_TEMP_ARRAY(args, 1);
2002    ADD_C(args, DICT_OBJ(data));
2003
2004    Object result = nlua_call_ref(callback.data.luaref, NULL, args, kRetNilBool, NULL, NULL);
2005    return LUARET_TRUTHY(result);
2006  } else {
2007    typval_T argsin = TV_INITIAL_VALUE;
2008    typval_T rettv = TV_INITIAL_VALUE;
2009    callback_call(&callback, 0, &argsin, &rettv);
2010    return false;
2011  }
2012}
2013
2014/// Get next autocommand command.
2015/// Called by do_cmdline() to get the next line for ":if".
2016/// @return allocated string, or NULL for end of autocommands.
2017char *getnextac(int c, void *cookie, int indent, bool do_concat)
2018{
2019  // These arguments are required for do_cmdline.
2020  (void)c;
2021  (void)indent;
2022  (void)do_concat;
2023
2024  AutoPatCmd *const apc = (AutoPatCmd *)cookie;
2025  AutoCmdVec *const acs = &autocmds[(int)apc->event];
2026
2027  aucmd_next(apc);
2028  if (apc->lastpat == NULL) {
2029    return NULL;
2030  }
2031
2032  assert(apc->auidx < kv_size(*acs));
2033  AutoCmd *const ac = &kv_A(*acs, apc->auidx);
2034  assert(ac->pat != NULL);
2035  bool oneshot = ac->once;
2036
2037  if (p_verbose >= 9) {
2038    verbose_enter_scroll();
2039    char *handler_str = aucmd_handler_to_string(ac);
2040    smsg(0, _("autocommand %s"), handler_str);
2041    msg_puts("\n");  // don't overwrite this either
2042    XFREE_CLEAR(handler_str);
2043    verbose_leave_scroll();
2044  }
2045
2046  // Make sure to set autocmd_nested before executing
2047  // lua code, so that it works properly
2048  autocmd_nested = ac->nested;
2049  current_sctx = ac->script_ctx;
2050  apc->script_ctx = current_sctx;
2051
2052  char *retval;
2053  if (ac->handler_cmd) {
2054    retval = xstrdup(ac->handler_cmd);
2055  } else {
2056    AutoCmd ac_copy = *ac;
2057    // Mark oneshot handler as "removed" now, to prevent recursion by e.g. `:doautocmd`. #25526
2058    ac->pat = oneshot ? NULL : ac->pat;
2059    // May reallocate `acs` kvec_t data and invalidate the `ac` pointer.
2060    bool rv = au_callback(&ac_copy, apc);
2061    if (oneshot) {
2062      // Restore `pat`. Use `acs` because `ac` may have been invalidated by the callback.
2063      kv_A(*acs, apc->auidx).pat = ac_copy.pat;
2064    }
2065    // If an autocommand callback returns true, delete the autocommand
2066    oneshot = oneshot || rv;
2067
2068    // HACK(tjdevries):
2069    //  We just return "not-null" and continue going.
2070    //  This would be a good candidate for a refactor. You would need to refactor:
2071    //      1. do_cmdline to accept something besides a string
2072    //      OR
2073    //      2. make where we call do_cmdline for autocmds not have to return anything,
2074    //      and instead we loop over all the matches and just execute one-by-one.
2075    //          However, my expectation would be that could be expensive.
2076    retval = xcalloc(1, 1);
2077  }
2078
2079  // Remove one-shot ("once") autocmd in anticipation of its execution.
2080  if (oneshot) {
2081    aucmd_del(&kv_A(*acs, apc->auidx));
2082  }
2083
2084  if (apc->auidx < apc->ausize) {
2085    apc->auidx++;
2086  } else {
2087    apc->auidx = SIZE_MAX;
2088  }
2089
2090  return retval;
2091}
2092
2093/// Return true if there is a matching autocommand for "fname".
2094/// To account for buffer-local autocommands, function needs to know
2095/// in which buffer the file will be opened.
2096///
2097/// @param event event that occurred.
2098/// @param sfname filename the event occurred in.
2099/// @param buf buffer the file is open in
2100bool has_autocmd(event_T event, char *sfname, buf_T *buf)
2101  FUNC_ATTR_WARN_UNUSED_RESULT
2102{
2103  char *tail = path_tail(sfname);
2104  bool retval = false;
2105
2106  char *fname = FullName_save(sfname, false);
2107  if (fname == NULL) {
2108    return false;
2109  }
2110
2111  AutoCmdVec *const acs = &autocmds[(int)event];
2112  for (size_t i = 0; i < kv_size(*acs); i++) {
2113    AutoPat *const ap = kv_A(*acs, i).pat;
2114    if (ap != NULL
2115        && (ap->buflocal_nr == 0
2116            ? match_file_pat(NULL, &ap->reg_prog, fname, sfname, tail, ap->allow_dirs)
2117            : buf != NULL && ap->buflocal_nr == buf->b_fnum)) {
2118      retval = true;
2119      break;
2120    }
2121  }
2122
2123  xfree(fname);
2124
2125  return retval;
2126}
2127
2128// Function given to ExpandGeneric() to obtain the list of autocommand group names.
2129char *expand_get_augroup_name(expand_T *xp, int idx)
2130{
2131  (void)xp;  // Required for ExpandGeneric
2132  return augroup_name(idx + 1);
2133}
2134
2135/// @param doautocmd  true for :doauto*, false for :autocmd
2136char *aucmd_set_expand_context(expand_T *xp, char *arg, bool doautocmd)
2137{
2138  // check for a group name, skip it if present
2139  autocmd_include_groups = false;
2140  char *p = arg;
2141  int group = arg_augroup_get(&arg);
2142
2143  // If there only is a group name that's what we expand.
2144  if (*arg == NUL && group != AUGROUP_ALL && !ascii_iswhite(arg[-1])) {
2145    arg = p;
2146    group = AUGROUP_ALL;
2147  }
2148
2149  // skip over event name
2150  for (p = arg; *p != NUL && !ascii_iswhite(*p); p++) {
2151    if (*p == ',') {
2152      arg = p + 1;
2153    }
2154  }
2155  if (*p == NUL) {
2156    if (group == AUGROUP_ALL) {
2157      autocmd_include_groups = true;
2158    }
2159    xp->xp_context = EXPAND_EVENTS;  // expand event name
2160    xp->xp_pattern = arg;
2161    return NULL;
2162  }
2163
2164  // skip over pattern
2165  arg = skipwhite(p);
2166  while (*arg && (!ascii_iswhite(*arg) || arg[-1] == '\\')) {
2167    arg++;
2168  }
2169  if (*arg) {
2170    return arg;  // expand (next) command
2171  }
2172
2173  if (doautocmd) {
2174    xp->xp_context = EXPAND_FILES;  // expand file names
2175  } else {
2176    xp->xp_context = EXPAND_NOTHING;  // pattern is not expanded
2177  }
2178  return NULL;
2179}
2180
2181/// Function given to ExpandGeneric() to obtain the list of event names.
2182char *expand_get_event_name(expand_T *xp, int idx)
2183{
2184  (void)xp;  // xp is a required parameter to be used with ExpandGeneric
2185
2186  // List group names
2187  char *name = augroup_name(idx + 1);
2188  if (name != NULL) {
2189    // skip when not including groups or skip deleted entries
2190    if (!autocmd_include_groups || name == get_deleted_augroup()) {
2191      return "";
2192    }
2193
2194    return name;
2195  }
2196
2197  int i = idx - next_augroup_id;
2198  if (i < 0 || i >= NUM_EVENTS) {
2199    return NULL;
2200  }
2201
2202  // List event names
2203  return event_names[i].name;
2204}
2205
2206/// Function given to ExpandGeneric() to obtain the list of event names. Don't
2207/// include groups.
2208char *get_event_name_no_group(expand_T *xp FUNC_ATTR_UNUSED, int idx, bool win)
2209{
2210  if (idx < 0 || idx >= NUM_EVENTS) {
2211    return NULL;
2212  }
2213
2214  if (!win) {
2215    return event_names[idx].name;
2216  }
2217
2218  // Need to check subset of allowed values for 'eventignorewin'.
2219  int j = 0;
2220  for (int i = 0; i < NUM_EVENTS; i++) {
2221    j += event_names[i].event <= 0;
2222    if (j == idx + 1) {
2223      return event_names[i].name;
2224    }
2225  }
2226  return NULL;
2227}
2228
2229/// Check whether given autocommand is supported
2230///
2231/// @param[in]  event  Event to check.
2232///
2233/// @return True if it is, false otherwise.
2234bool autocmd_supported(const char *const event)
2235  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2236{
2237  char *p;
2238  return event_name2nr(event, &p) != NUM_EVENTS;
2239}
2240
2241/// Return true if an autocommand is defined for a group, event and
2242/// pattern:  The group can be omitted to accept any group.
2243/// `event` and `pattern` can be omitted to accept any event and pattern.
2244/// Buffer-local patterns <buffer> or <buffer=N> are accepted.
2245/// Used for:
2246///   exists("#Group") or
2247///   exists("#Group#Event") or
2248///   exists("#Group#Event#pat") or
2249///   exists("#Event") or
2250///   exists("#Event#pat")
2251///
2252/// @param arg autocommand string
2253bool au_exists(const char *const arg)
2254  FUNC_ATTR_WARN_UNUSED_RESULT
2255{
2256  buf_T *buflocal_buf = NULL;
2257  bool retval = false;
2258
2259  // Make a copy so that we can change the '#' chars to a NUL.
2260  char *const arg_save = xstrdup(arg);
2261  char *p = strchr(arg_save, '#');
2262  if (p != NULL) {
2263    *p++ = NUL;
2264  }
2265
2266  // First, look for an autocmd group name.
2267  int group = augroup_find(arg_save);
2268  char *event_name;
2269  if (group == AUGROUP_ERROR) {
2270    // Didn't match a group name, assume the first argument is an event.
2271    group = AUGROUP_ALL;
2272    event_name = arg_save;
2273  } else {
2274    if (p == NULL) {
2275      // "Group": group name is present and it's recognized
2276      retval = true;
2277      goto theend;
2278    }
2279
2280    // Must be "Group#Event" or "Group#Event#pat".
2281    event_name = p;
2282    p = strchr(event_name, '#');
2283    if (p != NULL) {
2284      *p++ = NUL;  // "Group#Event#pat"
2285    }
2286  }
2287
2288  char *pattern = p;  // "pattern" is NULL when there is no pattern.
2289
2290  // Find the index (enum) for the event name.
2291  event_T event = event_name2nr(event_name, &p);
2292
2293  // return false if the event name is not recognized
2294  if (event == NUM_EVENTS) {
2295    goto theend;
2296  }
2297
2298  // Find the first autocommand for this event.
2299  // If there isn't any, return false;
2300  // If there is one and no pattern given, return true;
2301  AutoCmdVec *const acs = &autocmds[(int)event];
2302  if (kv_size(*acs) == 0) {
2303    goto theend;
2304  }
2305
2306  // if pattern is "<buffer>", special handling is needed which uses curbuf
2307  // for pattern "<buffer=N>, mb_strcmp_ic() will work fine
2308  if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0) {
2309    buflocal_buf = curbuf;
2310  }
2311
2312  // Check if there is an autocommand with the given pattern.
2313  for (size_t i = 0; i < kv_size(*acs); i++) {
2314    AutoPat *const ap = kv_A(*acs, i).pat;
2315    // Only use a pattern when it has not been removed.
2316    // Patterns are matched verbatim (like do_autocmd): mb_strcmp_ic instead of path_equal.
2317    if (ap != NULL
2318        && (group == AUGROUP_ALL || ap->group == group)
2319        && (pattern == NULL
2320            || (buflocal_buf == NULL
2321                ? mb_strcmp_ic(p_fic, ap->pat, pattern) == 0
2322                : ap->buflocal_nr == buflocal_buf->b_fnum))) {
2323      retval = true;
2324      break;
2325    }
2326  }
2327
2328theend:
2329  xfree(arg_save);
2330  return retval;
2331}
2332
2333// Checks if a pattern is buflocal
2334bool aupat_is_buflocal(const char *pat, int patlen)
2335  FUNC_ATTR_PURE
2336{
2337  return patlen >= 8 && strncmp(pat, "<buffer", 7) == 0 && pat[patlen - 1] == '>';
2338}
2339
2340int aupat_get_buflocal_nr(const char *pat, int patlen)
2341{
2342  assert(aupat_is_buflocal(pat, patlen));
2343
2344  // "<buffer>"
2345  if (patlen == 8) {
2346    return curbuf->b_fnum;
2347  }
2348
2349  if (patlen > 9 && pat[7] == '=') {
2350    // "<buffer=abuf>"
2351    if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0) {
2352      return autocmd_bufnr;
2353    }
2354
2355    // "<buffer=123>"
2356    if (skipdigits(pat + 8) == pat + patlen - 1) {
2357      char *p = (char *)pat + 8;
2358      return getdigits_int(&p, false, 0);
2359    }
2360  }
2361
2362  return 0;
2363}
2364
2365// normalize buffer pattern
2366void aupat_normalize_buflocal_pat(char *dest, const char *pat, int patlen, int buflocal_nr)
2367{
2368  assert(aupat_is_buflocal(pat, patlen));
2369
2370  if (buflocal_nr == 0) {
2371    buflocal_nr = curbuf->handle;
2372  }
2373
2374  // normalize pat into standard "<buffer>#N" form
2375  snprintf(dest, BUFLOCAL_PAT_LEN, "<buffer=%d>", buflocal_nr);
2376}
2377
2378int autocmd_delete_event(int group, event_T event, const char *pat)
2379  FUNC_ATTR_NONNULL_ALL
2380{
2381  return do_autocmd_event(event, pat, false, false, "", true, group);
2382}
2383
2384/// Deletes an autocmd by ID.
2385/// Only autocmds created via the API have IDs associated with them. There
2386/// is no way to delete a specific autocmd created via :autocmd
2387bool autocmd_delete_id(int64_t id)
2388{
2389  assert(id > 0);
2390  bool success = false;
2391
2392  // Note that since multiple AutoCmd objects can have the same ID, we need to do a full scan.
2393  FOR_ALL_AUEVENTS(event) {
2394    AutoCmdVec *const acs = &autocmds[(int)event];
2395    for (size_t i = 0; i < kv_size(*acs); i++) {
2396      AutoCmd *const ac = &kv_A(*acs, i);
2397      if (ac->id == id) {
2398        aucmd_del(ac);
2399        success = true;
2400      }
2401    }
2402  }
2403  return success;
2404}
2405
2406/// Gets an (allocated) string representation of an autocmd command/callback.
2407char *aucmd_handler_to_string(AutoCmd *ac)
2408  FUNC_ATTR_PURE
2409{
2410  if (ac->handler_cmd) {
2411    return xstrdup(ac->handler_cmd);
2412  }
2413  return callback_to_string(&ac->handler_fn, NULL);
2414}
2415
2416// Arg Parsing Functions
2417
2418/// Scan over the events.  "*" stands for all events.
2419/// true when group name was found
2420static char *arg_event_skip(char *arg, bool have_group)
2421{
2422  char *pat;
2423  char *p;
2424
2425  if (*arg == '*') {
2426    if (arg[1] && !ascii_iswhite(arg[1])) {
2427      semsg(_("E215: Illegal character after *: %s"), arg);
2428      return NULL;
2429    }
2430    pat = arg + 1;
2431  } else {
2432    for (pat = arg; *pat && *pat != '|' && !ascii_iswhite(*pat); pat = p) {
2433      if ((int)event_name2nr(pat, &p) >= NUM_EVENTS) {
2434        if (have_group) {
2435          semsg(_("E216: No such event: %s"), pat);
2436        } else {
2437          semsg(_("E216: No such group or event: %s"), pat);
2438        }
2439        return NULL;
2440      }
2441    }
2442  }
2443  return pat;
2444}
2445
2446// Find the group ID in a ":autocmd" or ":doautocmd" argument.
2447// The "argp" argument is advanced to the following argument.
2448//
2449// Returns the group ID or AUGROUP_ALL.
2450static int arg_augroup_get(char **argp)
2451{
2452  char *p;
2453  char *arg = *argp;
2454
2455  for (p = arg; *p && !ascii_iswhite(*p) && *p != '|'; p++) {}
2456  if (p <= arg) {
2457    return AUGROUP_ALL;
2458  }
2459
2460  char *group_name = xmemdupz(arg, (size_t)(p - arg));
2461  int group = augroup_find(group_name);
2462  if (group == AUGROUP_ERROR) {
2463    group = AUGROUP_ALL;  // no match, use all groups
2464  } else {
2465    *argp = skipwhite(p);  // match, skip over group name
2466  }
2467  xfree(group_name);
2468  return group;
2469}
2470
2471/// Handles grabbing arguments from `:autocmd` such as ++once and ++nested
2472static bool arg_autocmd_flag_get(bool *flag, char **cmd_ptr, char *pattern, int len)
2473{
2474  if (strncmp(*cmd_ptr, pattern, (size_t)len) == 0 && ascii_iswhite((*cmd_ptr)[len])) {
2475    if (*flag) {
2476      semsg(_(e_duparg2), pattern);
2477      return true;
2478    }
2479
2480    *flag = true;
2481    *cmd_ptr = skipwhite(*cmd_ptr + len);
2482  }
2483
2484  return false;
2485}
2486
2487/// When kFalse: VimSuspend should be triggered next.
2488/// When kTrue: VimResume should be triggered next.
2489/// When kNone: Currently triggering VimSuspend or VimResume.
2490static TriState pending_vimresume = kFalse;
2491
2492static void vimresume_event(void **argv)
2493{
2494  apply_autocmds(EVENT_VIMRESUME, NULL, NULL, false, NULL);
2495  pending_vimresume = kFalse;
2496}
2497
2498/// Trigger VimSuspend or VimResume autocommand.
2499void may_trigger_vim_suspend_resume(bool suspend)
2500{
2501  if (suspend && pending_vimresume == kFalse) {
2502    pending_vimresume = kNone;
2503    apply_autocmds(EVENT_VIMSUSPEND, NULL, NULL, false, NULL);
2504    pending_vimresume = kTrue;
2505  } else if (!suspend && pending_vimresume == kTrue) {
2506    pending_vimresume = kNone;
2507    multiqueue_put(main_loop.events, vimresume_event, NULL);
2508  }
2509}
2510
2511// UI Enter
2512void do_autocmd_uienter(uint64_t chanid, bool attached)
2513{
2514  static bool recursive = false;
2515
2516  if (starting == NO_SCREEN) {
2517    return;  // user config hasn't been sourced yet
2518  }
2519  if (recursive) {
2520    return;  // disallow recursion
2521  }
2522  recursive = true;
2523
2524  save_v_event_T save_v_event;
2525  dict_T *dict = get_v_event(&save_v_event);
2526  assert(chanid < VARNUMBER_MAX);
2527  tv_dict_add_nr(dict, S_LEN("chan"), (varnumber_T)chanid);
2528  tv_dict_set_keys_readonly(dict);
2529  apply_autocmds(attached ? EVENT_UIENTER : EVENT_UILEAVE, NULL, NULL, false, curbuf);
2530  restore_v_event(dict, &save_v_event);
2531
2532  recursive = false;
2533}
2534
2535// FocusGained
2536
2537void do_autocmd_focusgained(bool gained)
2538{
2539  static bool recursive = false;
2540  static Timestamp last_time = 0;
2541
2542  if (recursive) {
2543    return;  // disallow recursion
2544  }
2545  recursive = true;
2546  apply_autocmds((gained ? EVENT_FOCUSGAINED : EVENT_FOCUSLOST), NULL, NULL, false, curbuf);
2547
2548  // When activated: Check if any file was modified outside of Vim.
2549  // Only do this when not done within the last two seconds as:
2550  // 1. Some filesystems have modification time granularity in seconds. Fat32
2551  //    has a granularity of 2 seconds.
2552  // 2. We could get multiple notifications in a row.
2553  if (gained && last_time + (Timestamp)2000 < os_now()) {
2554    check_timestamps(true);
2555    last_time = os_now();
2556  }
2557
2558  recursive = false;
2559}
2560
2561/// @return Whether any FileType autocommands were executed.
2562bool do_filetype_autocmd(buf_T *buf, bool force)
2563{
2564  static int ft_recursive = 0;
2565
2566  if (ft_recursive > 0 && !force) {
2567    return false;  // disallow recursion
2568  }
2569
2570  int secure_save = secure;
2571
2572  // Reset the secure flag, since the value of 'filetype' has
2573  // been checked to be safe.
2574  secure = 0;
2575
2576  ft_recursive++;
2577  buf->b_did_filetype = true;
2578  // Only pass true for "force" when it is true or
2579  // used recursively, to avoid endless recurrence.
2580  bool ret
2581    = apply_autocmds(EVENT_FILETYPE, buf->b_p_ft, buf->b_fname, force || ft_recursive == 1, buf);
2582  ft_recursive--;
2583
2584  secure = secure_save;
2585  return ret;
2586}