blob: b1c74cb853ac401bffc4e9ee799106e343d8861d [file] [log] [blame]
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * autocmd.c: Autocommand related functions
12 */
13
14#include "vim.h"
15
16/*
17 * The autocommands are stored in a list for each event.
18 * Autocommands for the same pattern, that are consecutive, are joined
19 * together, to avoid having to match the pattern too often.
20 * The result is an array of Autopat lists, which point to AutoCmd lists:
21 *
22 * last_autopat[0] -----------------------------+
23 * V
24 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
25 * Autopat.cmds Autopat.cmds
26 * | |
27 * V V
28 * AutoCmd.next AutoCmd.next
29 * | |
30 * V V
31 * AutoCmd.next NULL
32 * |
33 * V
34 * NULL
35 *
36 * last_autopat[1] --------+
37 * V
38 * first_autopat[1] --> Autopat.next --> NULL
39 * Autopat.cmds
40 * |
41 * V
42 * AutoCmd.next
43 * |
44 * V
45 * NULL
46 * etc.
47 *
48 * The order of AutoCmds is important, this is the order in which they were
49 * defined and will have to be executed.
50 */
51typedef struct AutoCmd
52{
53 char_u *cmd; // The command to be executed (NULL
54 // when command has been removed).
Bram Moolenaareb93f3f2019-04-04 15:04:56 +020055 char once; // "One shot": removed after execution
Bram Moolenaar3e460fd2019-01-26 16:21:07 +010056 char nested; // If autocommands nest here.
57 char last; // last command in list
LemonBoyeca7c602022-04-14 15:39:43 +010058 sctx_T script_ctx; // script context where it is defined
Bram Moolenaar3e460fd2019-01-26 16:21:07 +010059 struct AutoCmd *next; // next AutoCmd in list
60} AutoCmd;
61
62typedef struct AutoPat
63{
64 struct AutoPat *next; // Next AutoPat in AutoPat list; MUST
65 // be the first entry.
66 char_u *pat; // pattern as typed (NULL when pattern
67 // has been removed)
68 regprog_T *reg_prog; // compiled regprog for pattern
69 AutoCmd *cmds; // list of commands to do
70 int group; // group ID
71 int patlen; // strlen() of pat
72 int buflocal_nr; // !=0 for buffer-local AutoPat
73 char allow_dirs; // Pattern may match whole path
74 char last; // last pattern for apply_autocmds()
75} AutoPat;
76
John Marriott78d742a2024-04-02 20:26:01 +020077//
78// special cases:
79// BufNewFile and BufRead are searched for ALOT (especially at startup)
80// so we pre-determine their index into the event_tab[] table for fast access.
81// Keep these values in sync with event_tab[]!
82#define BUFNEWFILE_INDEX 9
83#define BUFREAD_INDEX 10
84
85// must be sorted by the 'value' field because it is used by bsearch()!
86static keyvalue_T event_tab[] = {
87 KEYVALUE_ENTRY(EVENT_BUFADD, "BufAdd"),
88 KEYVALUE_ENTRY(EVENT_BUFADD, "BufCreate"),
89 KEYVALUE_ENTRY(EVENT_BUFDELETE, "BufDelete"),
90 KEYVALUE_ENTRY(EVENT_BUFENTER, "BufEnter"),
91 KEYVALUE_ENTRY(EVENT_BUFFILEPOST, "BufFilePost"),
92 KEYVALUE_ENTRY(EVENT_BUFFILEPRE, "BufFilePre"),
93 KEYVALUE_ENTRY(EVENT_BUFHIDDEN, "BufHidden"),
94 KEYVALUE_ENTRY(EVENT_BUFLEAVE, "BufLeave"),
95 KEYVALUE_ENTRY(EVENT_BUFNEW, "BufNew"),
96 KEYVALUE_ENTRY(EVENT_BUFNEWFILE, "BufNewFile"), // BUFNEWFILE_INDEX
97 KEYVALUE_ENTRY(EVENT_BUFREADPOST, "BufRead"), // BUFREAD_INDEX
98 KEYVALUE_ENTRY(EVENT_BUFREADCMD, "BufReadCmd"),
99 KEYVALUE_ENTRY(EVENT_BUFREADPOST, "BufReadPost"),
100 KEYVALUE_ENTRY(EVENT_BUFREADPRE, "BufReadPre"),
101 KEYVALUE_ENTRY(EVENT_BUFUNLOAD, "BufUnload"),
102 KEYVALUE_ENTRY(EVENT_BUFWINENTER, "BufWinEnter"),
103 KEYVALUE_ENTRY(EVENT_BUFWINLEAVE, "BufWinLeave"),
104 KEYVALUE_ENTRY(EVENT_BUFWIPEOUT, "BufWipeout"),
105 KEYVALUE_ENTRY(EVENT_BUFWRITEPRE, "BufWrite"),
106 KEYVALUE_ENTRY(EVENT_BUFWRITECMD, "BufWriteCmd"),
107 KEYVALUE_ENTRY(EVENT_BUFWRITEPOST, "BufWritePost"),
108 KEYVALUE_ENTRY(EVENT_BUFWRITEPRE, "BufWritePre"),
109 KEYVALUE_ENTRY(EVENT_CMDLINECHANGED, "CmdlineChanged"),
110 KEYVALUE_ENTRY(EVENT_CMDLINEENTER, "CmdlineEnter"),
111 KEYVALUE_ENTRY(EVENT_CMDLINELEAVE, "CmdlineLeave"),
112 KEYVALUE_ENTRY(EVENT_CMDUNDEFINED, "CmdUndefined"),
113 KEYVALUE_ENTRY(EVENT_CMDWINENTER, "CmdwinEnter"),
114 KEYVALUE_ENTRY(EVENT_CMDWINLEAVE, "CmdwinLeave"),
115 KEYVALUE_ENTRY(EVENT_COLORSCHEME, "ColorScheme"),
116 KEYVALUE_ENTRY(EVENT_COLORSCHEMEPRE, "ColorSchemePre"),
117 KEYVALUE_ENTRY(EVENT_COMPLETECHANGED, "CompleteChanged"),
118 KEYVALUE_ENTRY(EVENT_COMPLETEDONE, "CompleteDone"),
119 KEYVALUE_ENTRY(EVENT_COMPLETEDONEPRE, "CompleteDonePre"),
120 KEYVALUE_ENTRY(EVENT_CURSORHOLD, "CursorHold"),
121 KEYVALUE_ENTRY(EVENT_CURSORHOLDI, "CursorHoldI"),
122 KEYVALUE_ENTRY(EVENT_CURSORMOVED, "CursorMoved"),
123 KEYVALUE_ENTRY(EVENT_CURSORMOVEDI, "CursorMovedI"),
124 KEYVALUE_ENTRY(EVENT_DIFFUPDATED, "DiffUpdated"),
125 KEYVALUE_ENTRY(EVENT_DIRCHANGED, "DirChanged"),
126 KEYVALUE_ENTRY(EVENT_DIRCHANGEDPRE, "DirChangedPre"),
127 KEYVALUE_ENTRY(EVENT_ENCODINGCHANGED, "EncodingChanged"),
128 KEYVALUE_ENTRY(EVENT_EXITPRE, "ExitPre"),
129 KEYVALUE_ENTRY(EVENT_FILEAPPENDCMD, "FileAppendCmd"),
130 KEYVALUE_ENTRY(EVENT_FILEAPPENDPOST, "FileAppendPost"),
131 KEYVALUE_ENTRY(EVENT_FILEAPPENDPRE, "FileAppendPre"),
132 KEYVALUE_ENTRY(EVENT_FILECHANGEDRO, "FileChangedRO"),
133 KEYVALUE_ENTRY(EVENT_FILECHANGEDSHELL, "FileChangedShell"),
134 KEYVALUE_ENTRY(EVENT_FILECHANGEDSHELLPOST, "FileChangedShellPost"),
135 KEYVALUE_ENTRY(EVENT_ENCODINGCHANGED, "FileEncoding"),
136 KEYVALUE_ENTRY(EVENT_FILEREADCMD, "FileReadCmd"),
137 KEYVALUE_ENTRY(EVENT_FILEREADPOST, "FileReadPost"),
138 KEYVALUE_ENTRY(EVENT_FILEREADPRE, "FileReadPre"),
139 KEYVALUE_ENTRY(EVENT_FILETYPE, "FileType"),
140 KEYVALUE_ENTRY(EVENT_FILEWRITECMD, "FileWriteCmd"),
141 KEYVALUE_ENTRY(EVENT_FILEWRITEPOST, "FileWritePost"),
142 KEYVALUE_ENTRY(EVENT_FILEWRITEPRE, "FileWritePre"),
143 KEYVALUE_ENTRY(EVENT_FILTERREADPOST, "FilterReadPost"),
144 KEYVALUE_ENTRY(EVENT_FILTERREADPRE, "FilterReadPre"),
145 KEYVALUE_ENTRY(EVENT_FILTERWRITEPOST, "FilterWritePost"),
146 KEYVALUE_ENTRY(EVENT_FILTERWRITEPRE, "FilterWritePre"),
147 KEYVALUE_ENTRY(EVENT_FOCUSGAINED, "FocusGained"),
148 KEYVALUE_ENTRY(EVENT_FOCUSLOST, "FocusLost"),
149 KEYVALUE_ENTRY(EVENT_FUNCUNDEFINED, "FuncUndefined"),
150 KEYVALUE_ENTRY(EVENT_GUIENTER, "GUIEnter"),
151 KEYVALUE_ENTRY(EVENT_GUIFAILED, "GUIFailed"),
152 KEYVALUE_ENTRY(EVENT_INSERTCHANGE, "InsertChange"),
153 KEYVALUE_ENTRY(EVENT_INSERTCHARPRE, "InsertCharPre"),
154 KEYVALUE_ENTRY(EVENT_INSERTENTER, "InsertEnter"),
155 KEYVALUE_ENTRY(EVENT_INSERTLEAVE, "InsertLeave"),
156 KEYVALUE_ENTRY(EVENT_INSERTLEAVEPRE, "InsertLeavePre"),
157 KEYVALUE_ENTRY(EVENT_MENUPOPUP, "MenuPopup"),
158 KEYVALUE_ENTRY(EVENT_MODECHANGED, "ModeChanged"),
159 KEYVALUE_ENTRY(EVENT_OPTIONSET, "OptionSet"),
160 KEYVALUE_ENTRY(EVENT_QUICKFIXCMDPOST, "QuickFixCmdPost"),
161 KEYVALUE_ENTRY(EVENT_QUICKFIXCMDPRE, "QuickFixCmdPre"),
162 KEYVALUE_ENTRY(EVENT_QUITPRE, "QuitPre"),
163 KEYVALUE_ENTRY(EVENT_REMOTEREPLY, "RemoteReply"),
164 KEYVALUE_ENTRY(EVENT_SAFESTATE, "SafeState"),
165 KEYVALUE_ENTRY(EVENT_SAFESTATEAGAIN, "SafeStateAgain"),
166 KEYVALUE_ENTRY(EVENT_SESSIONLOADPOST, "SessionLoadPost"),
167 KEYVALUE_ENTRY(EVENT_SESSIONWRITEPOST, "SessionWritePost"),
168 KEYVALUE_ENTRY(EVENT_SHELLCMDPOST, "ShellCmdPost"),
169 KEYVALUE_ENTRY(EVENT_SHELLFILTERPOST, "ShellFilterPost"),
170 KEYVALUE_ENTRY(EVENT_SIGUSR1, "SigUSR1"),
171 KEYVALUE_ENTRY(EVENT_SOURCECMD, "SourceCmd"),
172 KEYVALUE_ENTRY(EVENT_SOURCEPOST, "SourcePost"),
173 KEYVALUE_ENTRY(EVENT_SOURCEPRE, "SourcePre"),
174 KEYVALUE_ENTRY(EVENT_SPELLFILEMISSING, "SpellFileMissing"),
175 KEYVALUE_ENTRY(EVENT_STDINREADPOST, "StdinReadPost"),
176 KEYVALUE_ENTRY(EVENT_STDINREADPRE, "StdinReadPre"),
177 KEYVALUE_ENTRY(EVENT_SWAPEXISTS, "SwapExists"),
178 KEYVALUE_ENTRY(EVENT_SYNTAX, "Syntax"),
179 KEYVALUE_ENTRY(EVENT_TABCLOSED, "TabClosed"),
180 KEYVALUE_ENTRY(EVENT_TABENTER, "TabEnter"),
181 KEYVALUE_ENTRY(EVENT_TABLEAVE, "TabLeave"),
182 KEYVALUE_ENTRY(EVENT_TABNEW, "TabNew"),
183 KEYVALUE_ENTRY(EVENT_TERMCHANGED, "TermChanged"),
184 KEYVALUE_ENTRY(EVENT_TERMINALOPEN, "TerminalOpen"),
185 KEYVALUE_ENTRY(EVENT_TERMINALWINOPEN, "TerminalWinOpen"),
186 KEYVALUE_ENTRY(EVENT_TERMRESPONSE, "TermResponse"),
187 KEYVALUE_ENTRY(EVENT_TERMRESPONSEALL, "TermResponseAll"),
188 KEYVALUE_ENTRY(EVENT_TEXTCHANGED, "TextChanged"),
189 KEYVALUE_ENTRY(EVENT_TEXTCHANGEDI, "TextChangedI"),
190 KEYVALUE_ENTRY(EVENT_TEXTCHANGEDP, "TextChangedP"),
191 KEYVALUE_ENTRY(EVENT_TEXTCHANGEDT, "TextChangedT"),
192 KEYVALUE_ENTRY(EVENT_TEXTYANKPOST, "TextYankPost"),
193 KEYVALUE_ENTRY(EVENT_USER, "User"),
194 KEYVALUE_ENTRY(EVENT_VIMENTER, "VimEnter"),
195 KEYVALUE_ENTRY(EVENT_VIMLEAVE, "VimLeave"),
196 KEYVALUE_ENTRY(EVENT_VIMLEAVEPRE, "VimLeavePre"),
197 KEYVALUE_ENTRY(EVENT_VIMRESIZED, "VimResized"),
198 KEYVALUE_ENTRY(EVENT_VIMRESUME, "VimResume"),
199 KEYVALUE_ENTRY(EVENT_VIMSUSPEND, "VimSuspend"),
200 KEYVALUE_ENTRY(EVENT_WINCLOSED, "WinClosed"),
201 KEYVALUE_ENTRY(EVENT_WINENTER, "WinEnter"),
202 KEYVALUE_ENTRY(EVENT_WINLEAVE, "WinLeave"),
203 KEYVALUE_ENTRY(EVENT_WINNEW, "WinNew"),
204 KEYVALUE_ENTRY(EVENT_WINNEWPRE, "WinNewPre"),
205 KEYVALUE_ENTRY(EVENT_WINRESIZED, "WinResized"),
206 KEYVALUE_ENTRY(EVENT_WINSCROLLED, "WinScrolled")
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100207};
208
John Marriott78d742a2024-04-02 20:26:01 +0200209static AutoPat *first_autopat[NUM_EVENTS] = {
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100210 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
211 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
212 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
213 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
214 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
John Marriott78d742a2024-04-02 20:26:01 +0200215 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
216 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
217 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
218 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
219 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
220 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
221 NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100222};
223
John Marriott78d742a2024-04-02 20:26:01 +0200224static AutoPat *last_autopat[NUM_EVENTS] = {
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100225 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
226 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
227 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
228 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
229 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
John Marriott78d742a2024-04-02 20:26:01 +0200230 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
231 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
232 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
233 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
234 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
235 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
236 NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100237};
238
kylo252ae6f1d82022-02-16 19:24:07 +0000239#define AUGROUP_DEFAULT (-1) // default autocmd group
240#define AUGROUP_ERROR (-2) // erroneous autocmd group
241#define AUGROUP_ALL (-3) // all autocmd groups
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100242
243/*
244 * struct used to keep status while executing autocommands for an event.
245 */
Bram Moolenaar1a47ae32019-12-29 23:04:25 +0100246struct AutoPatCmd_S
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100247{
248 AutoPat *curpat; // next AutoPat to examine
249 AutoCmd *nextcmd; // next AutoCmd to execute
250 int group; // group being used
251 char_u *fname; // fname to match with
252 char_u *sfname; // sfname to match with
253 char_u *tail; // tail of fname
254 event_T event; // current event
LemonBoyeca7c602022-04-14 15:39:43 +0100255 sctx_T script_ctx; // script context where it is defined
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100256 int arg_bufnr; // Initially equal to <abuf>, set to zero when
257 // buf is deleted.
LemonBoyeca7c602022-04-14 15:39:43 +0100258 AutoPatCmd_T *next; // chain of active apc-s for auto-invalidation
Bram Moolenaar1a47ae32019-12-29 23:04:25 +0100259};
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100260
LemonBoyeca7c602022-04-14 15:39:43 +0100261static AutoPatCmd_T *active_apc_list = NULL; // stack of active autocommands
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100262
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200263// Macro to loop over all the patterns for an autocmd event
264#define FOR_ALL_AUTOCMD_PATTERNS(event, ap) \
265 for ((ap) = first_autopat[(int)(event)]; (ap) != NULL; (ap) = (ap)->next)
266
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100267/*
268 * augroups stores a list of autocmd group names.
269 */
270static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
271#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
Bram Moolenaarc667da52019-11-30 20:52:27 +0100272// use get_deleted_augroup() to get this
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100273static char_u *deleted_augroup = NULL;
274
275/*
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100276 * The ID of the current group. Group 0 is the default one.
277 */
278static int current_augroup = AUGROUP_DEFAULT;
279
Bram Moolenaarc667da52019-11-30 20:52:27 +0100280static int au_need_clean = FALSE; // need to delete marked patterns
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100281
John Marriott78d742a2024-04-02 20:26:01 +0200282static event_T event_name2nr(char_u *start, char_u **end);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100283static char_u *event_nr2name(event_T event);
284static int au_get_grouparg(char_u **argp);
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200285static int do_autocmd_event(event_T event, char_u *pat, int once, int nested, char_u *cmd, int forceit, int group, int flags);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100286static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
LemonBoyeca7c602022-04-14 15:39:43 +0100287static void auto_next_pat(AutoPatCmd_T *apc, int stop_at_last);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100288static int au_find_group(char_u *name);
289
290static event_T last_event;
291static int last_group;
Bram Moolenaarc667da52019-11-30 20:52:27 +0100292static int autocmd_blocked = 0; // block all autocmds
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100293
294 static char_u *
295get_deleted_augroup(void)
296{
297 if (deleted_augroup == NULL)
298 deleted_augroup = (char_u *)_("--Deleted--");
299 return deleted_augroup;
300}
301
302/*
303 * Show the autocommands for one AutoPat.
304 */
305 static void
306show_autocmd(AutoPat *ap, event_T event)
307{
308 AutoCmd *ac;
309
310 // Check for "got_int" (here and at various places below), which is set
311 // when "q" has been hit for the "--more--" prompt
312 if (got_int)
313 return;
314 if (ap->pat == NULL) // pattern has been removed
315 return;
316
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000317 // Make sure no info referenced by "ap" is cleared, e.g. when a timer
318 // clears an augroup. Jump to "theend" after this!
319 // "ap->pat" may be cleared anyway.
320 ++autocmd_busy;
321
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100322 msg_putchar('\n');
323 if (got_int)
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000324 goto theend;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100325 if (event != last_event || ap->group != last_group)
326 {
327 if (ap->group != AUGROUP_DEFAULT)
328 {
329 if (AUGROUP_NAME(ap->group) == NULL)
330 msg_puts_attr((char *)get_deleted_augroup(), HL_ATTR(HLF_E));
331 else
332 msg_puts_attr((char *)AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
333 msg_puts(" ");
334 }
335 msg_puts_attr((char *)event_nr2name(event), HL_ATTR(HLF_T));
336 last_event = event;
337 last_group = ap->group;
338 msg_putchar('\n');
339 if (got_int)
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000340 goto theend;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100341 }
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000342
343 if (ap->pat == NULL)
344 goto theend; // timer might have cleared the pattern or group
345
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100346 msg_col = 4;
347 msg_outtrans(ap->pat);
348
349 for (ac = ap->cmds; ac != NULL; ac = ac->next)
350 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100351 if (ac->cmd == NULL) // skip removed commands
352 continue;
353
354 if (msg_col >= 14)
355 msg_putchar('\n');
356 msg_col = 14;
357 if (got_int)
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000358 goto theend;
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100359 msg_outtrans(ac->cmd);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100360#ifdef FEAT_EVAL
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100361 if (p_verbose > 0)
362 last_set_msg(ac->script_ctx);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100363#endif
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100364 if (got_int)
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000365 goto theend;
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100366 if (ac->next != NULL)
367 {
368 msg_putchar('\n');
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100369 if (got_int)
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000370 goto theend;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100371 }
372 }
Bram Moolenaar3b014be2022-11-13 17:53:46 +0000373
374theend:
375 --autocmd_busy;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100376}
377
378/*
379 * Mark an autocommand pattern for deletion.
380 */
381 static void
382au_remove_pat(AutoPat *ap)
383{
384 VIM_CLEAR(ap->pat);
385 ap->buflocal_nr = -1;
386 au_need_clean = TRUE;
387}
388
389/*
390 * Mark all commands for a pattern for deletion.
391 */
392 static void
393au_remove_cmds(AutoPat *ap)
394{
395 AutoCmd *ac;
396
397 for (ac = ap->cmds; ac != NULL; ac = ac->next)
398 VIM_CLEAR(ac->cmd);
399 au_need_clean = TRUE;
400}
401
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200402// Delete one command from an autocmd pattern.
403static void au_del_cmd(AutoCmd *ac)
404{
405 VIM_CLEAR(ac->cmd);
406 au_need_clean = TRUE;
407}
408
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100409/*
410 * Cleanup autocommands and patterns that have been deleted.
411 * This is only done when not executing autocommands.
412 */
413 static void
414au_cleanup(void)
415{
416 AutoPat *ap, **prev_ap;
417 AutoCmd *ac, **prev_ac;
418 event_T event;
419
420 if (autocmd_busy || !au_need_clean)
421 return;
422
423 // loop over all events
=?UTF-8?q?Dundar=20G=C3=B6c?=dfa5e462021-10-02 11:26:51 +0100424 for (event = (event_T)0; (int)event < NUM_EVENTS;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100425 event = (event_T)((int)event + 1))
426 {
427 // loop over all autocommand patterns
428 prev_ap = &(first_autopat[(int)event]);
429 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
430 {
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200431 int has_cmd = FALSE;
432
Bram Moolenaar8f4aeb52019-04-04 15:40:56 +0200433 // loop over all commands for this pattern
434 prev_ac = &(ap->cmds);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100435 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
436 {
437 // remove the command if the pattern is to be deleted or when
438 // the command has been marked for deletion
439 if (ap->pat == NULL || ac->cmd == NULL)
440 {
441 *prev_ac = ac->next;
442 vim_free(ac->cmd);
443 vim_free(ac);
444 }
Bram Moolenaar8f4aeb52019-04-04 15:40:56 +0200445 else
446 {
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200447 has_cmd = TRUE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100448 prev_ac = &(ac->next);
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200449 }
450 }
451
Bram Moolenaar8f4aeb52019-04-04 15:40:56 +0200452 if (ap->pat != NULL && !has_cmd)
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200453 // Pattern was not marked for deletion, but all of its
454 // commands were. So mark the pattern for deletion.
455 au_remove_pat(ap);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100456
457 // remove the pattern if it has been marked for deletion
458 if (ap->pat == NULL)
459 {
460 if (ap->next == NULL)
461 {
462 if (prev_ap == &(first_autopat[(int)event]))
463 last_autopat[(int)event] = NULL;
464 else
465 // this depends on the "next" field being the first in
466 // the struct
467 last_autopat[(int)event] = (AutoPat *)prev_ap;
468 }
469 *prev_ap = ap->next;
470 vim_regfree(ap->reg_prog);
471 vim_free(ap);
472 }
473 else
474 prev_ap = &(ap->next);
475 }
476 }
477
478 au_need_clean = FALSE;
479}
480
481/*
482 * Called when buffer is freed, to remove/invalidate related buffer-local
483 * autocmds.
484 */
485 void
486aubuflocal_remove(buf_T *buf)
487{
LemonBoyeca7c602022-04-14 15:39:43 +0100488 AutoPat *ap;
489 event_T event;
490 AutoPatCmd_T *apc;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100491
492 // invalidate currently executing autocommands
493 for (apc = active_apc_list; apc; apc = apc->next)
494 if (buf->b_fnum == apc->arg_bufnr)
495 apc->arg_bufnr = 0;
496
497 // invalidate buflocals looping through events
=?UTF-8?q?Dundar=20G=C3=B6c?=dfa5e462021-10-02 11:26:51 +0100498 for (event = (event_T)0; (int)event < NUM_EVENTS;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100499 event = (event_T)((int)event + 1))
500 // loop over all autocommand patterns
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200501 FOR_ALL_AUTOCMD_PATTERNS(event, ap)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100502 if (ap->buflocal_nr == buf->b_fnum)
503 {
504 au_remove_pat(ap);
505 if (p_verbose >= 6)
506 {
507 verbose_enter();
508 smsg(_("auto-removing autocommand: %s <buffer=%d>"),
509 event_nr2name(event), buf->b_fnum);
510 verbose_leave();
511 }
512 }
513 au_cleanup();
514}
515
516/*
517 * Add an autocmd group name.
518 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
519 */
520 static int
521au_new_group(char_u *name)
522{
523 int i;
524
525 i = au_find_group(name);
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100526 if (i != AUGROUP_ERROR)
527 return i;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100528
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100529 // the group doesn't exist yet, add it. First try using a free entry.
530 for (i = 0; i < augroups.ga_len; ++i)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100531 if (AUGROUP_NAME(i) == NULL)
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100532 break;
533 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
534 return AUGROUP_ERROR;
535
536 AUGROUP_NAME(i) = vim_strsave(name);
537 if (AUGROUP_NAME(i) == NULL)
538 return AUGROUP_ERROR;
539 if (i == augroups.ga_len)
540 ++augroups.ga_len;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100541
542 return i;
543}
544
545 static void
546au_del_group(char_u *name)
547{
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100548 int i;
549 event_T event;
550 AutoPat *ap;
551 int in_use = FALSE;
552
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100553
554 i = au_find_group(name);
555 if (i == AUGROUP_ERROR) // the group doesn't exist
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100556 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100557 semsg(_(e_no_such_group_str), name);
558 return;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100559 }
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100560 if (i == current_augroup)
561 {
562 emsg(_(e_cannot_delete_current_group));
563 return;
564 }
565
566 for (event = (event_T)0; (int)event < NUM_EVENTS;
567 event = (event_T)((int)event + 1))
568 {
569 FOR_ALL_AUTOCMD_PATTERNS(event, ap)
570 if (ap->group == i && ap->pat != NULL)
571 {
572 give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
573 in_use = TRUE;
574 event = NUM_EVENTS;
575 break;
576 }
577 }
578 vim_free(AUGROUP_NAME(i));
579 if (in_use)
580 AUGROUP_NAME(i) = get_deleted_augroup();
581 else
582 AUGROUP_NAME(i) = NULL;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100583}
584
585/*
586 * Find the ID of an autocmd group name.
587 * Return its ID. Returns AUGROUP_ERROR (< 0) for error.
588 */
589 static int
590au_find_group(char_u *name)
591{
592 int i;
593
594 for (i = 0; i < augroups.ga_len; ++i)
595 if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
596 && STRCMP(AUGROUP_NAME(i), name) == 0)
597 return i;
598 return AUGROUP_ERROR;
599}
600
601/*
602 * Return TRUE if augroup "name" exists.
603 */
604 int
605au_has_group(char_u *name)
606{
607 return au_find_group(name) != AUGROUP_ERROR;
608}
609
610/*
611 * ":augroup {name}".
612 */
613 void
614do_augroup(char_u *arg, int del_group)
615{
616 int i;
617
618 if (del_group)
619 {
620 if (*arg == NUL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000621 emsg(_(e_argument_required));
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100622 else
623 au_del_group(arg);
624 }
625 else if (STRICMP(arg, "end") == 0) // ":aug end": back to group 0
626 current_augroup = AUGROUP_DEFAULT;
627 else if (*arg) // ":aug xxx": switch to group xxx
628 {
629 i = au_new_group(arg);
630 if (i != AUGROUP_ERROR)
631 current_augroup = i;
632 }
633 else // ":aug": list the group names
634 {
635 msg_start();
636 for (i = 0; i < augroups.ga_len; ++i)
637 {
638 if (AUGROUP_NAME(i) != NULL)
639 {
640 msg_puts((char *)AUGROUP_NAME(i));
641 msg_puts(" ");
642 }
643 }
644 msg_clr_eos();
645 msg_end();
646 }
647}
648
Bram Moolenaare76062c2022-11-28 18:51:43 +0000649 void
650autocmd_init(void)
651{
652 CLEAR_FIELD(aucmd_win);
653}
654
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100655#if defined(EXITFREE) || defined(PROTO)
656 void
657free_all_autocmds(void)
658{
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100659 char_u *s;
660
661 for (current_augroup = -1; current_augroup < augroups.ga_len;
662 ++current_augroup)
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200663 do_autocmd(NULL, (char_u *)"", TRUE);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100664
Bram Moolenaare76062c2022-11-28 18:51:43 +0000665 for (int i = 0; i < augroups.ga_len; ++i)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100666 {
667 s = ((char_u **)(augroups.ga_data))[i];
668 if (s != get_deleted_augroup())
669 vim_free(s);
670 }
671 ga_clear(&augroups);
Bram Moolenaare76062c2022-11-28 18:51:43 +0000672
Bram Moolenaar84497cd2022-11-28 20:34:52 +0000673 // aucmd_win[] is freed in win_free_all()
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100674}
675#endif
676
677/*
Bram Moolenaare76062c2022-11-28 18:51:43 +0000678 * Return TRUE if "win" is an active entry in aucmd_win[].
679 */
680 int
681is_aucmd_win(win_T *win)
682{
683 for (int i = 0; i < AUCMD_WIN_COUNT; ++i)
684 if (aucmd_win[i].auc_win_used && aucmd_win[i].auc_win == win)
685 return TRUE;
686 return FALSE;
687}
688
689/*
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100690 * Return the event number for event name "start".
691 * Return NUM_EVENTS if the event name was not found.
692 * Return a pointer to the next event name in "end".
693 */
694 static event_T
695event_name2nr(char_u *start, char_u **end)
696{
697 char_u *p;
John Marriott78d742a2024-04-02 20:26:01 +0200698 keyvalue_T target;
699 keyvalue_T *entry;
700 static keyvalue_T *bufnewfile = &event_tab[BUFNEWFILE_INDEX];
701 static keyvalue_T *bufread = &event_tab[BUFREAD_INDEX];
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100702
703 // the event name ends with end of line, '|', a blank or a comma
704 for (p = start; *p && !VIM_ISWHITE(*p) && *p != ',' && *p != '|'; ++p)
705 ;
John Marriott78d742a2024-04-02 20:26:01 +0200706
707 target.key = 0;
708 target.value = (char *)start;
709 target.length = (size_t)(p - start);
710
711 // special cases:
712 // BufNewFile and BufRead are searched for ALOT (especially at startup)
713 // so we check for them first.
714 if (cmp_keyvalue_value_ni(&target, bufnewfile) == 0)
715 entry = bufnewfile;
716 else
717 if (cmp_keyvalue_value_ni(&target, bufread) == 0)
718 entry = bufread;
719 else
720 entry = (keyvalue_T *)bsearch(&target, &event_tab, ARRAY_LENGTH(event_tab), sizeof(event_tab[0]), cmp_keyvalue_value_ni);
721
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100722 if (*p == ',')
723 ++p;
724 *end = p;
John Marriott78d742a2024-04-02 20:26:01 +0200725
726 return (entry == NULL) ? NUM_EVENTS : (event_T)entry->key;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100727}
728
729/*
730 * Return the name for event "event".
731 */
732 static char_u *
733event_nr2name(event_T event)
734{
735 int i;
John Marriott78d742a2024-04-02 20:26:01 +0200736#define CACHE_SIZE 12
737 static int cache_tab[CACHE_SIZE];
738 static int cache_last_index = -1;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100739
John Marriott78d742a2024-04-02 20:26:01 +0200740 if (cache_last_index < 0)
741 {
742 for (i = 0; i < (int)ARRAY_LENGTH(cache_tab); ++i)
743 cache_tab[i] = -1;
744 cache_last_index = ARRAY_LENGTH(cache_tab) - 1;
745 }
746
747 // first look in the cache
748 // the cache is circular. to search it we start at the most recent entry
749 // and go backwards wrapping around when we get to index 0.
750 for (i = cache_last_index; cache_tab[i] >= 0; )
751 {
752 if ((event_T)event_tab[cache_tab[i]].key == event)
753 return (char_u *)event_tab[cache_tab[i]].value;
754
755 if (i == 0)
756 i = ARRAY_LENGTH(cache_tab) - 1;
757 else
758 --i;
759
760 // are we back at the start?
761 if (i == cache_last_index)
762 break;
763 }
764
765 // look in the event table itself
766 for (i = 0; i < (int)ARRAY_LENGTH(event_tab); ++i)
767 {
768 if ((event_T)event_tab[i].key == event)
769 {
770 // store the found entry in the next position in the cache,
771 // wrapping around when we get to the maximum index.
772 if (cache_last_index == ARRAY_LENGTH(cache_tab) - 1)
773 cache_last_index = 0;
774 else
775 ++cache_last_index;
776 cache_tab[cache_last_index] = i;
777 break;
778 }
779 }
780
781 return (i == (int)ARRAY_LENGTH(event_tab)) ? (char_u *)"Unknown" : (char_u *)event_tab[i].value;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100782}
783
784/*
785 * Scan over the events. "*" stands for all events.
786 */
787 static char_u *
788find_end_event(
789 char_u *arg,
790 int have_group) // TRUE when group name was found
791{
792 char_u *pat;
793 char_u *p;
794
795 if (*arg == '*')
796 {
797 if (arg[1] && !VIM_ISWHITE(arg[1]))
798 {
Bram Moolenaar6d057012021-12-31 18:49:43 +0000799 semsg(_(e_illegal_character_after_star_str), arg);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100800 return NULL;
801 }
802 pat = arg + 1;
803 }
804 else
805 {
806 for (pat = arg; *pat && *pat != '|' && !VIM_ISWHITE(*pat); pat = p)
807 {
=?UTF-8?q?Dundar=20G=C3=B6c?=dfa5e462021-10-02 11:26:51 +0100808 if ((int)event_name2nr(pat, &p) >= NUM_EVENTS)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100809 {
810 if (have_group)
Bram Moolenaar6d057012021-12-31 18:49:43 +0000811 semsg(_(e_no_such_event_str), pat);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100812 else
Bram Moolenaar6d057012021-12-31 18:49:43 +0000813 semsg(_(e_no_such_group_or_event_str), pat);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100814 return NULL;
815 }
816 }
817 }
818 return pat;
819}
820
821/*
822 * Return TRUE if "event" is included in 'eventignore'.
823 */
824 static int
825event_ignored(event_T event)
826{
827 char_u *p = p_ei;
828
829 while (*p != NUL)
830 {
831 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
832 return TRUE;
833 if (event_name2nr(p, &p) == event)
834 return TRUE;
835 }
836
837 return FALSE;
838}
839
840/*
841 * Return OK when the contents of p_ei is valid, FAIL otherwise.
842 */
843 int
844check_ei(void)
845{
846 char_u *p = p_ei;
847
848 while (*p)
849 {
850 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
851 {
852 p += 3;
853 if (*p == ',')
854 ++p;
855 }
856 else if (event_name2nr(p, &p) == NUM_EVENTS)
857 return FAIL;
858 }
859
860 return OK;
861}
862
863# if defined(FEAT_SYN_HL) || defined(PROTO)
864
865/*
866 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
867 * buffer loaded into the window. "what" must start with a comma.
868 * Returns the old value of 'eventignore' in allocated memory.
869 */
870 char_u *
871au_event_disable(char *what)
872{
873 char_u *new_ei;
874 char_u *save_ei;
John Marriott78d742a2024-04-02 20:26:01 +0200875 size_t p_ei_len;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100876
John Marriott78d742a2024-04-02 20:26:01 +0200877 p_ei_len = STRLEN(p_ei);
878 save_ei = vim_strnsave(p_ei, p_ei_len);
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100879 if (save_ei == NULL)
880 return NULL;
881
John Marriott78d742a2024-04-02 20:26:01 +0200882 new_ei = vim_strnsave(p_ei, p_ei_len + STRLEN(what));
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100883 if (new_ei == NULL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100884 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100885 vim_free(save_ei);
886 return NULL;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100887 }
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +0100888
889 if (*what == ',' && *p_ei == NUL)
890 STRCPY(new_ei, what + 1);
891 else
892 STRCAT(new_ei, what);
893 set_string_option_direct((char_u *)"ei", -1, new_ei,
894 OPT_FREE, SID_NONE);
895 vim_free(new_ei);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100896 return save_ei;
897}
898
899 void
900au_event_restore(char_u *old_ei)
901{
902 if (old_ei != NULL)
903 {
904 set_string_option_direct((char_u *)"ei", -1, old_ei,
905 OPT_FREE, SID_NONE);
906 vim_free(old_ei);
907 }
908}
Bram Moolenaarc667da52019-11-30 20:52:27 +0100909# endif // FEAT_SYN_HL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100910
911/*
912 * do_autocmd() -- implements the :autocmd command. Can be used in the
913 * following ways:
914 *
915 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
916 * will be automatically executed for <event>
917 * when editing a file matching <pat>, in
918 * the current group.
919 * :autocmd <event> <pat> Show the autocommands associated with
920 * <event> and <pat>.
921 * :autocmd <event> Show the autocommands associated with
922 * <event>.
923 * :autocmd Show all autocommands.
924 * :autocmd! <event> <pat> <cmd> Remove all autocommands associated with
925 * <event> and <pat>, and add the command
926 * <cmd>, for the current group.
927 * :autocmd! <event> <pat> Remove all autocommands associated with
928 * <event> and <pat> for the current group.
929 * :autocmd! <event> Remove all autocommands associated with
930 * <event> for the current group.
931 * :autocmd! Remove ALL autocommands for the current
932 * group.
933 *
934 * Multiple events and patterns may be given separated by commas. Here are
935 * some examples:
936 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
937 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
938 *
939 * :autocmd * *.c show all autocommands for *.c files.
940 *
941 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200942 * "eap" can be NULL.
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100943 */
944 void
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200945do_autocmd(exarg_T *eap, char_u *arg_in, int forceit)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100946{
947 char_u *arg = arg_in;
948 char_u *pat;
949 char_u *envpat = NULL;
950 char_u *cmd;
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200951 int cmd_need_free = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100952 event_T event;
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200953 char_u *tofree = NULL;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100954 int nested = FALSE;
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200955 int once = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100956 int group;
Bram Moolenaareb93f3f2019-04-04 15:04:56 +0200957 int i;
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +0200958 int flags = 0;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100959
960 if (*arg == '|')
961 {
Bram Moolenaarb8e642f2021-11-20 10:38:25 +0000962 eap->nextcmd = arg + 1;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100963 arg = (char_u *)"";
964 group = AUGROUP_ALL; // no argument, use all groups
965 }
966 else
967 {
968 /*
969 * Check for a legal group name. If not, use AUGROUP_ALL.
970 */
971 group = au_get_grouparg(&arg);
972 if (arg == NULL) // out of memory
973 return;
974 }
975
976 /*
977 * Scan over the events.
978 * If we find an illegal name, return here, don't do anything.
979 */
980 pat = find_end_event(arg, group != AUGROUP_ALL);
981 if (pat == NULL)
982 return;
983
984 pat = skipwhite(pat);
985 if (*pat == '|')
986 {
Bram Moolenaarb8e642f2021-11-20 10:38:25 +0000987 eap->nextcmd = pat + 1;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +0100988 pat = (char_u *)"";
989 cmd = (char_u *)"";
990 }
991 else
992 {
993 /*
994 * Scan over the pattern. Put a NUL at the end.
995 */
996 cmd = pat;
997 while (*cmd && (!VIM_ISWHITE(*cmd) || cmd[-1] == '\\'))
998 cmd++;
999 if (*cmd)
1000 *cmd++ = NUL;
1001
1002 // Expand environment variables in the pattern. Set 'shellslash', we
1003 // want forward slashes here.
1004 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
1005 {
1006#ifdef BACKSLASH_IN_FILENAME
1007 int p_ssl_save = p_ssl;
1008
1009 p_ssl = TRUE;
1010#endif
1011 envpat = expand_env_save(pat);
1012#ifdef BACKSLASH_IN_FILENAME
1013 p_ssl = p_ssl_save;
1014#endif
1015 if (envpat != NULL)
1016 pat = envpat;
1017 }
1018
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001019 cmd = skipwhite(cmd);
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001020 for (i = 0; i < 2; i++)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001021 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001022 if (*cmd == NUL)
1023 continue;
1024
1025 // Check for "++once" flag.
1026 if (STRNCMP(cmd, "++once", 6) == 0 && VIM_ISWHITE(cmd[6]))
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001027 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001028 if (once)
1029 semsg(_(e_duplicate_argument_str), "++once");
1030 once = TRUE;
1031 cmd = skipwhite(cmd + 6);
1032 }
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001033
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001034 // Check for "++nested" flag.
1035 if ((STRNCMP(cmd, "++nested", 8) == 0 && VIM_ISWHITE(cmd[8])))
1036 {
1037 if (nested)
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001038 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001039 semsg(_(e_duplicate_argument_str), "++nested");
1040 return;
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001041 }
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001042 nested = TRUE;
1043 cmd = skipwhite(cmd + 8);
1044 }
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001045
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001046 // Check for the old "nested" flag in legacy script.
1047 if (STRNCMP(cmd, "nested", 6) == 0 && VIM_ISWHITE(cmd[6]))
1048 {
1049 if (in_vim9script())
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001050 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001051 // If there ever is a :nested command this error should
1052 // be removed and "nested" accepted as the start of the
1053 // command.
1054 emsg(_(e_invalid_command_nested_did_you_mean_plusplus_nested));
1055 return;
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001056 }
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001057 if (nested)
1058 {
1059 semsg(_(e_duplicate_argument_str), "nested");
1060 return;
1061 }
1062 nested = TRUE;
1063 cmd = skipwhite(cmd + 6);
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001064 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001065 }
1066
1067 /*
1068 * Find the start of the commands.
1069 * Expand <sfile> in it.
1070 */
1071 if (*cmd != NUL)
1072 {
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001073 if (eap != NULL)
1074 // Read a {} block if it follows.
1075 cmd = may_get_cmd_block(eap, cmd, &tofree, &flags);
1076
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001077 cmd = expand_sfile(cmd);
1078 if (cmd == NULL) // some error
1079 return;
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001080 cmd_need_free = TRUE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001081 }
1082 }
1083
1084 /*
1085 * Print header when showing autocommands.
1086 */
1087 if (!forceit && *cmd == NUL)
1088 // Highlight title
1089 msg_puts_title(_("\n--- Autocommands ---"));
1090
1091 /*
1092 * Loop over the events.
1093 */
1094 last_event = (event_T)-1; // for listing the event name
1095 last_group = AUGROUP_ERROR; // for listing the group name
1096 if (*arg == '*' || *arg == NUL || *arg == '|')
1097 {
Bram Moolenaarb6db1462021-12-24 19:24:47 +00001098 if (*cmd != NUL)
Bram Moolenaar9a046fd2021-01-28 13:47:59 +01001099 emsg(_(e_cannot_define_autocommands_for_all_events));
1100 else
=?UTF-8?q?Dundar=20G=C3=B6c?=dfa5e462021-10-02 11:26:51 +01001101 for (event = (event_T)0; (int)event < NUM_EVENTS;
Bram Moolenaar9a046fd2021-01-28 13:47:59 +01001102 event = (event_T)((int)event + 1))
1103 if (do_autocmd_event(event, pat,
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001104 once, nested, cmd, forceit, group, flags) == FAIL)
Bram Moolenaar9a046fd2021-01-28 13:47:59 +01001105 break;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001106 }
1107 else
1108 {
1109 while (*arg && *arg != '|' && !VIM_ISWHITE(*arg))
1110 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001111 once, nested, cmd, forceit, group, flags) == FAIL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001112 break;
1113 }
1114
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001115 if (cmd_need_free)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001116 vim_free(cmd);
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001117 vim_free(tofree);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001118 vim_free(envpat);
1119}
1120
1121/*
1122 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
1123 * The "argp" argument is advanced to the following argument.
1124 *
1125 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
1126 */
1127 static int
1128au_get_grouparg(char_u **argp)
1129{
1130 char_u *group_name;
1131 char_u *p;
1132 char_u *arg = *argp;
1133 int group = AUGROUP_ALL;
1134
1135 for (p = arg; *p && !VIM_ISWHITE(*p) && *p != '|'; ++p)
1136 ;
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00001137 if (p <= arg)
1138 return AUGROUP_ALL;
1139
1140 group_name = vim_strnsave(arg, p - arg);
1141 if (group_name == NULL) // out of memory
1142 return AUGROUP_ERROR;
1143 group = au_find_group(group_name);
1144 if (group == AUGROUP_ERROR)
1145 group = AUGROUP_ALL; // no match, use all groups
1146 else
1147 *argp = skipwhite(p); // match, skip over group name
1148 vim_free(group_name);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001149 return group;
1150}
1151
1152/*
1153 * do_autocmd() for one event.
1154 * If *pat == NUL do for all patterns.
1155 * If *cmd == NUL show entries.
1156 * If forceit == TRUE delete entries.
1157 * If group is not AUGROUP_ALL, only use this group.
1158 */
1159 static int
1160do_autocmd_event(
1161 event_T event,
1162 char_u *pat,
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001163 int once,
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001164 int nested,
1165 char_u *cmd,
1166 int forceit,
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001167 int group,
1168 int flags)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001169{
1170 AutoPat *ap;
1171 AutoPat **prev_ap;
1172 AutoCmd *ac;
1173 AutoCmd **prev_ac;
1174 int brace_level;
1175 char_u *endpat;
1176 int findgroup;
1177 int allgroups;
1178 int patlen;
1179 int is_buflocal;
1180 int buflocal_nr;
Bram Moolenaarc667da52019-11-30 20:52:27 +01001181 char_u buflocal_pat[25]; // for "<buffer=X>"
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001182
1183 if (group == AUGROUP_ALL)
1184 findgroup = current_augroup;
1185 else
1186 findgroup = group;
1187 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
1188
1189 /*
1190 * Show or delete all patterns for an event.
1191 */
1192 if (*pat == NUL)
1193 {
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001194 FOR_ALL_AUTOCMD_PATTERNS(event, ap)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001195 {
1196 if (forceit) // delete the AutoPat, if it's in the current group
1197 {
1198 if (ap->group == findgroup)
1199 au_remove_pat(ap);
1200 }
1201 else if (group == AUGROUP_ALL || ap->group == group)
1202 show_autocmd(ap, event);
1203 }
1204 }
1205
1206 /*
1207 * Loop through all the specified patterns.
1208 */
1209 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
1210 {
1211 /*
1212 * Find end of the pattern.
1213 * Watch out for a comma in braces, like "*.\{obj,o\}".
1214 */
1215 brace_level = 0;
1216 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
1217 || (endpat > pat && endpat[-1] == '\\')); ++endpat)
1218 {
1219 if (*endpat == '{')
1220 brace_level++;
1221 else if (*endpat == '}')
1222 brace_level--;
1223 }
1224 if (pat == endpat) // ignore single comma
1225 continue;
1226 patlen = (int)(endpat - pat);
1227
1228 /*
1229 * detect special <buflocal[=X]> buffer-local patterns
1230 */
1231 is_buflocal = FALSE;
1232 buflocal_nr = 0;
1233
1234 if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
1235 && pat[patlen - 1] == '>')
1236 {
1237 // "<buffer...>": Error will be printed only for addition.
1238 // printing and removing will proceed silently.
1239 is_buflocal = TRUE;
1240 if (patlen == 8)
1241 // "<buffer>"
1242 buflocal_nr = curbuf->b_fnum;
1243 else if (patlen > 9 && pat[7] == '=')
1244 {
1245 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
1246 // "<buffer=abuf>"
1247 buflocal_nr = autocmd_bufnr;
1248 else if (skipdigits(pat + 8) == pat + patlen - 1)
1249 // "<buffer=123>"
1250 buflocal_nr = atoi((char *)pat + 8);
1251 }
1252 }
1253
1254 if (is_buflocal)
1255 {
1256 // normalize pat into standard "<buffer>#N" form
1257 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
1258 pat = buflocal_pat; // can modify pat and patlen
1259 patlen = (int)STRLEN(buflocal_pat); // but not endpat
1260 }
1261
1262 /*
1263 * Find AutoPat entries with this pattern. When adding a command it
1264 * always goes at or after the last one, so start at the end.
1265 */
1266 if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL)
1267 prev_ap = &last_autopat[(int)event];
1268 else
1269 prev_ap = &first_autopat[(int)event];
1270 while ((ap = *prev_ap) != NULL)
1271 {
1272 if (ap->pat != NULL)
1273 {
Bram Moolenaarc667da52019-11-30 20:52:27 +01001274 /*
1275 * Accept a pattern when:
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001276 * - a group was specified and it's that group, or a group was
1277 * not specified and it's the current group, or a group was
1278 * not specified and we are listing
1279 * - the length of the pattern matches
1280 * - the pattern matches.
1281 * For <buffer[=X]>, this condition works because we normalize
1282 * all buffer-local patterns.
1283 */
1284 if ((allgroups || ap->group == findgroup)
1285 && ap->patlen == patlen
1286 && STRNCMP(pat, ap->pat, patlen) == 0)
1287 {
1288 /*
1289 * Remove existing autocommands.
1290 * If adding any new autocmd's for this AutoPat, don't
1291 * delete the pattern from the autopat list, append to
1292 * this list.
1293 */
1294 if (forceit)
1295 {
1296 if (*cmd != NUL && ap->next == NULL)
1297 {
1298 au_remove_cmds(ap);
1299 break;
1300 }
1301 au_remove_pat(ap);
1302 }
1303
1304 /*
1305 * Show autocmd's for this autopat, or buflocals <buffer=X>
1306 */
1307 else if (*cmd == NUL)
1308 show_autocmd(ap, event);
1309
1310 /*
1311 * Add autocmd to this autopat, if it's the last one.
1312 */
1313 else if (ap->next == NULL)
1314 break;
1315 }
1316 }
1317 prev_ap = &ap->next;
1318 }
1319
1320 /*
1321 * Add a new command.
1322 */
1323 if (*cmd != NUL)
1324 {
1325 /*
1326 * If the pattern we want to add a command to does appear at the
1327 * end of the list (or not is not in the list at all), add the
1328 * pattern at the end of the list.
1329 */
1330 if (ap == NULL)
1331 {
Bram Moolenaarc667da52019-11-30 20:52:27 +01001332 // refuse to add buffer-local ap if buffer number is invalid
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001333 if (is_buflocal && (buflocal_nr == 0
1334 || buflist_findnr(buflocal_nr) == NULL))
1335 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001336 semsg(_(e_buffer_nr_invalid_buffer_number), buflocal_nr);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001337 return FAIL;
1338 }
1339
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001340 ap = ALLOC_ONE(AutoPat);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001341 if (ap == NULL)
1342 return FAIL;
1343 ap->pat = vim_strnsave(pat, patlen);
1344 ap->patlen = patlen;
1345 if (ap->pat == NULL)
1346 {
1347 vim_free(ap);
1348 return FAIL;
1349 }
1350
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01001351#ifdef FEAT_EVAL
1352 // need to initialize last_mode for the first ModeChanged
1353 // autocmd
1354 if (event == EVENT_MODECHANGED && !has_modechanged())
LemonBoy2bf52dd2022-04-09 18:17:34 +01001355 get_mode(last_mode);
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01001356#endif
Bram Moolenaar35fc61c2022-11-22 12:40:50 +00001357 // Initialize the fields checked by the WinScrolled and
1358 // WinResized trigger to prevent them from firing right after
1359 // the first autocmd is defined.
1360 if ((event == EVENT_WINSCROLLED || event == EVENT_WINRESIZED)
1361 && !(has_winscrolled() || has_winresized()))
LemonBoy09371822022-04-08 15:18:45 +01001362 {
Bram Moolenaar29967732022-11-20 12:11:45 +00001363 tabpage_T *save_curtab = curtab;
1364 tabpage_T *tp;
1365 FOR_ALL_TABPAGES(tp)
1366 {
1367 unuse_tabpage(curtab);
1368 use_tabpage(tp);
1369 snapshot_windows_scroll_size();
1370 }
1371 unuse_tabpage(curtab);
1372 use_tabpage(save_curtab);
LemonBoy09371822022-04-08 15:18:45 +01001373 }
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01001374
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001375 if (is_buflocal)
1376 {
1377 ap->buflocal_nr = buflocal_nr;
1378 ap->reg_prog = NULL;
1379 }
1380 else
1381 {
1382 char_u *reg_pat;
1383
1384 ap->buflocal_nr = 0;
1385 reg_pat = file_pat_to_reg_pat(pat, endpat,
1386 &ap->allow_dirs, TRUE);
1387 if (reg_pat != NULL)
1388 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
1389 vim_free(reg_pat);
1390 if (reg_pat == NULL || ap->reg_prog == NULL)
1391 {
1392 vim_free(ap->pat);
1393 vim_free(ap);
1394 return FAIL;
1395 }
1396 }
1397 ap->cmds = NULL;
1398 *prev_ap = ap;
1399 last_autopat[(int)event] = ap;
1400 ap->next = NULL;
1401 if (group == AUGROUP_ALL)
1402 ap->group = current_augroup;
1403 else
1404 ap->group = group;
1405 }
1406
1407 /*
1408 * Add the autocmd at the end of the AutoCmd list.
1409 */
1410 prev_ac = &(ap->cmds);
1411 while ((ac = *prev_ac) != NULL)
1412 prev_ac = &ac->next;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001413 ac = ALLOC_ONE(AutoCmd);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001414 if (ac == NULL)
1415 return FAIL;
1416 ac->cmd = vim_strsave(cmd);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001417 ac->script_ctx = current_sctx;
Bram Moolenaar73b8b0a2021-08-01 14:52:32 +02001418 if (flags & UC_VIM9)
1419 ac->script_ctx.sc_version = SCRIPT_VERSION_VIM9;
Bram Moolenaar9b8d6222020-12-28 18:26:00 +01001420#ifdef FEAT_EVAL
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01001421 ac->script_ctx.sc_lnum += SOURCING_LNUM;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001422#endif
1423 if (ac->cmd == NULL)
1424 {
1425 vim_free(ac);
1426 return FAIL;
1427 }
1428 ac->next = NULL;
1429 *prev_ac = ac;
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02001430 ac->once = once;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001431 ac->nested = nested;
1432 }
1433 }
1434
1435 au_cleanup(); // may really delete removed patterns/commands now
1436 return OK;
1437}
1438
1439/*
1440 * Implementation of ":doautocmd [group] event [fname]".
1441 * Return OK for success, FAIL for failure;
1442 */
1443 int
1444do_doautocmd(
Bram Moolenaar1b154ea2021-08-07 13:59:43 +02001445 char_u *arg_start,
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001446 int do_msg, // give message for no matching autocmds?
1447 int *did_something)
1448{
Bram Moolenaar1b154ea2021-08-07 13:59:43 +02001449 char_u *arg = arg_start;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001450 char_u *fname;
1451 int nothing_done = TRUE;
1452 int group;
1453
1454 if (did_something != NULL)
1455 *did_something = FALSE;
1456
1457 /*
1458 * Check for a legal group name. If not, use AUGROUP_ALL.
1459 */
1460 group = au_get_grouparg(&arg);
1461 if (arg == NULL) // out of memory
1462 return FAIL;
1463
1464 if (*arg == '*')
1465 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001466 emsg(_(e_cant_execute_autocommands_for_all_events));
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001467 return FAIL;
1468 }
1469
1470 /*
1471 * Scan over the events.
1472 * If we find an illegal name, return here, don't do anything.
1473 */
1474 fname = find_end_event(arg, group != AUGROUP_ALL);
1475 if (fname == NULL)
1476 return FAIL;
1477
1478 fname = skipwhite(fname);
1479
1480 /*
1481 * Loop over the events.
1482 */
1483 while (*arg && !ends_excmd(*arg) && !VIM_ISWHITE(*arg))
1484 if (apply_autocmds_group(event_name2nr(arg, &arg),
1485 fname, NULL, TRUE, group, curbuf, NULL))
1486 nothing_done = FALSE;
1487
Bram Moolenaar1b154ea2021-08-07 13:59:43 +02001488 if (nothing_done && do_msg
1489#ifdef FEAT_EVAL
1490 && !aborting()
1491#endif
1492 )
1493 smsg(_("No matching autocommands: %s"), arg_start);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001494 if (did_something != NULL)
1495 *did_something = !nothing_done;
1496
1497#ifdef FEAT_EVAL
1498 return aborting() ? FAIL : OK;
1499#else
1500 return OK;
1501#endif
1502}
1503
1504/*
1505 * ":doautoall": execute autocommands for each loaded buffer.
1506 */
1507 void
1508ex_doautoall(exarg_T *eap)
1509{
Bram Moolenaar41cd8032021-03-13 15:47:56 +01001510 int retval = OK;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001511 aco_save_T aco;
1512 buf_T *buf;
1513 bufref_T bufref;
1514 char_u *arg = eap->arg;
1515 int call_do_modelines = check_nomodeline(&arg);
1516 int did_aucmd;
1517
1518 /*
1519 * This is a bit tricky: For some commands curwin->w_buffer needs to be
1520 * equal to curbuf, but for some buffers there may not be a window.
1521 * So we change the buffer for the current window for a moment. This
1522 * gives problems when the autocommands make changes to the list of
1523 * buffers or windows...
1524 */
1525 FOR_ALL_BUFFERS(buf)
1526 {
Bram Moolenaar41cd8032021-03-13 15:47:56 +01001527 // Only do loaded buffers and skip the current buffer, it's done last.
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001528 if (buf->b_ml.ml_mfp == NULL || buf == curbuf)
1529 continue;
1530
Bram Moolenaare76062c2022-11-28 18:51:43 +00001531 // Find a window for this buffer and save some values.
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001532 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00001533 if (curbuf != buf)
1534 {
1535 // Failed to find a window for this buffer. Better not execute
1536 // autocommands then.
1537 retval = FAIL;
1538 break;
1539 }
1540
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001541 set_bufref(&bufref, buf);
1542
1543 // execute the autocommands for this buffer
1544 retval = do_doautocmd(arg, FALSE, &did_aucmd);
1545
1546 if (call_do_modelines && did_aucmd)
1547 // Execute the modeline settings, but don't set window-local
1548 // options if we are using the current window for another
1549 // buffer.
Bram Moolenaare76062c2022-11-28 18:51:43 +00001550 do_modelines(is_aucmd_win(curwin) ? OPT_NOWIN : 0);
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001551
1552 // restore the current window
1553 aucmd_restbuf(&aco);
1554
1555 // stop if there is some error or buffer was deleted
1556 if (retval == FAIL || !bufref_valid(&bufref))
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001557 {
Yegappan Lakshmanane9dcf132022-09-24 11:30:41 +01001558 retval = FAIL;
1559 break;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001560 }
1561 }
1562
Bram Moolenaar41cd8032021-03-13 15:47:56 +01001563 // Execute autocommands for the current buffer last.
1564 if (retval == OK)
1565 {
1566 do_doautocmd(arg, FALSE, &did_aucmd);
1567 if (call_do_modelines && did_aucmd)
1568 do_modelines(0);
1569 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001570}
1571
1572/*
1573 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
1574 * return TRUE and advance *argp to after it.
1575 * Thus return TRUE when do_modelines() should be called.
1576 */
1577 int
1578check_nomodeline(char_u **argp)
1579{
1580 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
1581 {
1582 *argp = skipwhite(*argp + 12);
1583 return FALSE;
1584 }
1585 return TRUE;
1586}
1587
1588/*
1589 * Prepare for executing autocommands for (hidden) buffer "buf".
1590 * Search for a visible window containing the current buffer. If there isn't
Bram Moolenaare76062c2022-11-28 18:51:43 +00001591 * one then use an entry in "aucmd_win[]".
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001592 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaare76062c2022-11-28 18:51:43 +00001593 * When this fails "curbuf" is not equal "buf".
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001594 */
1595 void
1596aucmd_prepbuf(
1597 aco_save_T *aco, // structure to save values in
1598 buf_T *buf) // new curbuf
1599{
1600 win_T *win;
1601 int save_ea;
1602#ifdef FEAT_AUTOCHDIR
1603 int save_acd;
1604#endif
1605
1606 // Find a window that is for the new buffer
1607 if (buf == curbuf) // be quick when buf is curbuf
1608 win = curwin;
1609 else
1610 FOR_ALL_WINDOWS(win)
1611 if (win->w_buffer == buf)
1612 break;
1613
Bram Moolenaare76062c2022-11-28 18:51:43 +00001614 // Allocate a window when needed.
1615 win_T *auc_win = NULL;
1616 int auc_idx = AUCMD_WIN_COUNT;
1617 if (win == NULL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001618 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00001619 for (auc_idx = 0; auc_idx < AUCMD_WIN_COUNT; ++auc_idx)
1620 if (!aucmd_win[auc_idx].auc_win_used)
1621 {
Bram Moolenaar84497cd2022-11-28 20:34:52 +00001622 if (aucmd_win[auc_idx].auc_win == NULL)
1623 aucmd_win[auc_idx].auc_win = win_alloc_popup_win();
1624 auc_win = aucmd_win[auc_idx].auc_win;
Bram Moolenaare76062c2022-11-28 18:51:43 +00001625 if (auc_win != NULL)
Bram Moolenaare76062c2022-11-28 18:51:43 +00001626 aucmd_win[auc_idx].auc_win_used = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00001627 break;
1628 }
1629
1630 // If this fails (out of memory or using all AUCMD_WIN_COUNT
1631 // entries) then we can't reliable execute the autocmd, return with
1632 // "curbuf" unequal "buf".
1633 if (auc_win == NULL)
1634 return;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001635 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001636
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001637 aco->save_curwin_id = curwin->w_id;
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001638 aco->save_prevwin_id = prevwin == NULL ? 0 : prevwin->w_id;
Bram Moolenaar05a627c2023-04-09 22:01:31 +01001639 aco->save_State = State;
zeertzjqf2678472024-01-17 21:22:59 +01001640#ifdef FEAT_JOB_CHANNEL
1641 if (bt_prompt(curbuf))
1642 aco->save_prompt_insert = curbuf->b_prompt_insert;
1643#endif
Bram Moolenaar05a627c2023-04-09 22:01:31 +01001644
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001645 if (win != NULL)
1646 {
1647 // There is a window for "buf" in the current tab page, make it the
1648 // curwin. This is preferred, it has the least side effects (esp. if
1649 // "buf" is curbuf).
Bram Moolenaare76062c2022-11-28 18:51:43 +00001650 aco->use_aucmd_win_idx = -1;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001651 curwin = win;
1652 }
1653 else
1654 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00001655 // There is no window for "buf", use "auc_win". To minimize the side
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001656 // effects, insert it in the current tab page.
1657 // Anything related to a window (e.g., setting folds) may have
1658 // unexpected results.
Bram Moolenaare76062c2022-11-28 18:51:43 +00001659 aco->use_aucmd_win_idx = auc_idx;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001660
Bram Moolenaare76062c2022-11-28 18:51:43 +00001661 win_init_popup_win(auc_win, buf);
Bram Moolenaar4d784b22019-05-25 19:51:39 +02001662
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001663 aco->globaldir = globaldir;
1664 globaldir = NULL;
1665
Bram Moolenaare76062c2022-11-28 18:51:43 +00001666 // Split the current window, put the auc_win in the upper half.
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001667 // We don't want the BufEnter or WinEnter autocommands.
1668 block_autocmds();
1669 make_snapshot(SNAP_AUCMD_IDX);
1670 save_ea = p_ea;
1671 p_ea = FALSE;
1672
1673#ifdef FEAT_AUTOCHDIR
1674 // Prevent chdir() call in win_enter_ext(), through do_autochdir().
1675 save_acd = p_acd;
1676 p_acd = FALSE;
1677#endif
1678
Sean Dewar704966c2024-02-20 22:00:33 +01001679 (void)win_split_ins(0, WSP_TOP | WSP_FORCE_ROOM, auc_win, 0, NULL);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001680 (void)win_comp_pos(); // recompute window positions
1681 p_ea = save_ea;
1682#ifdef FEAT_AUTOCHDIR
1683 p_acd = save_acd;
1684#endif
1685 unblock_autocmds();
Bram Moolenaare76062c2022-11-28 18:51:43 +00001686 curwin = auc_win;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001687 }
1688 curbuf = buf;
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001689 aco->new_curwin_id = curwin->w_id;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001690 set_bufref(&aco->new_curbuf, curbuf);
Bram Moolenaarcb1956d2022-01-07 15:45:18 +00001691
1692 // disable the Visual area, the position may be invalid in another buffer
1693 aco->save_VIsual_active = VIsual_active;
1694 VIsual_active = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001695}
1696
1697/*
1698 * Cleanup after executing autocommands for a (hidden) buffer.
1699 * Restore the window as it was (if possible).
1700 */
1701 void
1702aucmd_restbuf(
1703 aco_save_T *aco) // structure holding saved values
1704{
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001705 int dummy;
1706 win_T *save_curwin;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001707
Bram Moolenaare76062c2022-11-28 18:51:43 +00001708 if (aco->use_aucmd_win_idx >= 0)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001709 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00001710 win_T *awp = aucmd_win[aco->use_aucmd_win_idx].auc_win;
1711
Bram Moolenaare76062c2022-11-28 18:51:43 +00001712 // Find "awp", it can't be closed, but it may be in another tab
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001713 // page. Do not trigger autocommands here.
1714 block_autocmds();
Bram Moolenaare76062c2022-11-28 18:51:43 +00001715 if (curwin != awp)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001716 {
1717 tabpage_T *tp;
1718 win_T *wp;
1719
1720 FOR_ALL_TAB_WINDOWS(tp, wp)
1721 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00001722 if (wp == awp)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001723 {
1724 if (tp != curtab)
1725 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaare76062c2022-11-28 18:51:43 +00001726 win_goto(awp);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001727 goto win_found;
1728 }
1729 }
1730 }
1731win_found:
zeertzjq46bdae02023-09-24 23:16:08 +02001732 --curbuf->b_nwindows;
orbitalcde8de02023-04-02 22:05:13 +01001733#ifdef FEAT_JOB_CHANNEL
zeertzjqa40c0bc2023-05-27 14:10:08 +01001734 int save_stop_insert_mode = stop_insert_mode;
orbitalcde8de02023-04-02 22:05:13 +01001735 // May need to stop Insert mode if we were in a prompt buffer.
1736 leaving_window(curwin);
Bram Moolenaar05a627c2023-04-09 22:01:31 +01001737 // Do not stop Insert mode when already in Insert mode before.
1738 if (aco->save_State & MODE_INSERT)
zeertzjqa40c0bc2023-05-27 14:10:08 +01001739 stop_insert_mode = save_stop_insert_mode;
orbitalcde8de02023-04-02 22:05:13 +01001740#endif
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001741 // Remove the window and frame from the tree of frames.
Sean Dewar704966c2024-02-20 22:00:33 +01001742 (void)winframe_remove(curwin, &dummy, NULL, NULL);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001743 win_remove(curwin, NULL);
Bram Moolenaar84497cd2022-11-28 20:34:52 +00001744
1745 // The window is marked as not used, but it is not freed, it can be
1746 // used again.
Bram Moolenaare76062c2022-11-28 18:51:43 +00001747 aucmd_win[aco->use_aucmd_win_idx].auc_win_used = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001748 last_status(FALSE); // may need to remove last status line
1749
1750 if (!valid_tabpage_win(curtab))
1751 // no valid window in current tabpage
1752 close_tabpage(curtab);
1753
1754 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
1755 (void)win_comp_pos(); // recompute window positions
1756 unblock_autocmds();
1757
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001758 save_curwin = win_find_by_id(aco->save_curwin_id);
1759 if (save_curwin != NULL)
1760 curwin = save_curwin;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001761 else
1762 // Hmm, original window disappeared. Just use the first one.
1763 curwin = firstwin;
Bram Moolenaarbdf931c2020-10-01 22:37:40 +02001764 curbuf = curwin->w_buffer;
1765#ifdef FEAT_JOB_CHANNEL
1766 // May need to restore insert mode for a prompt buffer.
1767 entering_window(curwin);
zeertzjqf2678472024-01-17 21:22:59 +01001768 if (bt_prompt(curbuf))
1769 curbuf->b_prompt_insert = aco->save_prompt_insert;
Bram Moolenaarbdf931c2020-10-01 22:37:40 +02001770#endif
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001771 prevwin = win_find_by_id(aco->save_prevwin_id);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001772#ifdef FEAT_EVAL
Bram Moolenaare76062c2022-11-28 18:51:43 +00001773 vars_clear(&awp->w_vars->dv_hashtab); // free all w: variables
1774 hash_init(&awp->w_vars->dv_hashtab); // re-use the hashtab
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001775#endif
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001776 vim_free(globaldir);
1777 globaldir = aco->globaldir;
1778
1779 // the buffer contents may have changed
zeertzjq49f05242023-02-04 10:58:34 +00001780 VIsual_active = aco->save_VIsual_active;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001781 check_cursor();
1782 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
1783 {
1784 curwin->w_topline = curbuf->b_ml.ml_line_count;
1785#ifdef FEAT_DIFF
1786 curwin->w_topfill = 0;
1787#endif
1788 }
1789#if defined(FEAT_GUI)
Bram Moolenaard2ff7052021-12-17 16:00:04 +00001790 if (gui.in_use)
1791 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00001792 // Hide the scrollbars from the "awp" and update.
1793 gui_mch_enable_scrollbar(&awp->w_scrollbars[SBAR_LEFT], FALSE);
1794 gui_mch_enable_scrollbar(&awp->w_scrollbars[SBAR_RIGHT], FALSE);
Bram Moolenaard2ff7052021-12-17 16:00:04 +00001795 gui_may_update_scrollbars();
1796 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001797#endif
1798 }
1799 else
1800 {
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001801 // Restore curwin. Use the window ID, a window may have been closed
1802 // and the memory re-used for another one.
1803 save_curwin = win_find_by_id(aco->save_curwin_id);
1804 if (save_curwin != NULL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001805 {
1806 // Restore the buffer which was previously edited by curwin, if
1807 // it was changed, we are still the same window and the buffer is
1808 // valid.
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001809 if (curwin->w_id == aco->new_curwin_id
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001810 && curbuf != aco->new_curbuf.br_buf
1811 && bufref_valid(&aco->new_curbuf)
1812 && aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
1813 {
1814# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
1815 if (curwin->w_s == &curbuf->b_s)
1816 curwin->w_s = &aco->new_curbuf.br_buf->b_s;
1817# endif
1818 --curbuf->b_nwindows;
1819 curbuf = aco->new_curbuf.br_buf;
1820 curwin->w_buffer = curbuf;
1821 ++curbuf->b_nwindows;
1822 }
1823
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001824 curwin = save_curwin;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001825 curbuf = curwin->w_buffer;
Bram Moolenaarcbcd9cb2020-11-07 16:58:59 +01001826 prevwin = win_find_by_id(aco->save_prevwin_id);
zeertzjq49f05242023-02-04 10:58:34 +00001827
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001828 // In case the autocommand moves the cursor to a position that
1829 // does not exist in curbuf.
zeertzjq49f05242023-02-04 10:58:34 +00001830 VIsual_active = aco->save_VIsual_active;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001831 check_cursor();
1832 }
1833 }
Bram Moolenaarcb1956d2022-01-07 15:45:18 +00001834
Bram Moolenaarcb1956d2022-01-07 15:45:18 +00001835 VIsual_active = aco->save_VIsual_active;
zeertzjq49f05242023-02-04 10:58:34 +00001836 check_cursor(); // just in case lines got deleted
Bram Moolenaarcb1956d2022-01-07 15:45:18 +00001837 if (VIsual_active)
1838 check_pos(curbuf, &VIsual);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001839}
1840
1841static int autocmd_nested = FALSE;
1842
1843/*
1844 * Execute autocommands for "event" and file name "fname".
1845 * Return TRUE if some commands were executed.
1846 */
1847 int
1848apply_autocmds(
1849 event_T event,
1850 char_u *fname, // NULL or empty means use actual file name
1851 char_u *fname_io, // fname to use for <afile> on cmdline
1852 int force, // when TRUE, ignore autocmd_busy
1853 buf_T *buf) // buffer for <abuf>
1854{
1855 return apply_autocmds_group(event, fname, fname_io, force,
1856 AUGROUP_ALL, buf, NULL);
1857}
1858
1859/*
1860 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
1861 * setting v:filearg.
1862 */
1863 int
1864apply_autocmds_exarg(
1865 event_T event,
1866 char_u *fname,
1867 char_u *fname_io,
1868 int force,
1869 buf_T *buf,
1870 exarg_T *eap)
1871{
1872 return apply_autocmds_group(event, fname, fname_io, force,
1873 AUGROUP_ALL, buf, eap);
1874}
1875
1876/*
1877 * Like apply_autocmds(), but handles the caller's retval. If the script
1878 * processing is being aborted or if retval is FAIL when inside a try
1879 * conditional, no autocommands are executed. If otherwise the autocommands
1880 * cause the script to be aborted, retval is set to FAIL.
1881 */
1882 int
1883apply_autocmds_retval(
1884 event_T event,
1885 char_u *fname, // NULL or empty means use actual file name
1886 char_u *fname_io, // fname to use for <afile> on cmdline
1887 int force, // when TRUE, ignore autocmd_busy
1888 buf_T *buf, // buffer for <abuf>
1889 int *retval) // pointer to caller's retval
1890{
1891 int did_cmd;
1892
1893#ifdef FEAT_EVAL
1894 if (should_abort(*retval))
1895 return FALSE;
1896#endif
1897
1898 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
1899 AUGROUP_ALL, buf, NULL);
1900 if (did_cmd
1901#ifdef FEAT_EVAL
1902 && aborting()
1903#endif
1904 )
1905 *retval = FAIL;
1906 return did_cmd;
1907}
1908
1909/*
1910 * Return TRUE when there is a CursorHold autocommand defined.
1911 */
Bram Moolenaar5843f5f2019-08-20 20:13:45 +02001912 static int
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001913has_cursorhold(void)
1914{
Bram Moolenaar24959102022-05-07 20:01:16 +01001915 return (first_autopat[(int)(get_real_state() == MODE_NORMAL_BUSY
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001916 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
1917}
1918
1919/*
1920 * Return TRUE if the CursorHold event can be triggered.
1921 */
1922 int
1923trigger_cursorhold(void)
1924{
1925 int state;
1926
1927 if (!did_cursorhold
1928 && has_cursorhold()
1929 && reg_recording == 0
1930 && typebuf.tb_len == 0
Bram Moolenaare2c453d2019-08-21 14:37:09 +02001931 && !ins_compl_active())
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001932 {
1933 state = get_real_state();
Bram Moolenaar24959102022-05-07 20:01:16 +01001934 if (state == MODE_NORMAL_BUSY || (state & MODE_INSERT) != 0)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001935 return TRUE;
1936 }
1937 return FALSE;
1938}
1939
1940/*
Bram Moolenaar35fc61c2022-11-22 12:40:50 +00001941 * Return TRUE when there is a WinResized autocommand defined.
1942 */
1943 int
1944has_winresized(void)
1945{
1946 return (first_autopat[(int)EVENT_WINRESIZED] != NULL);
1947}
1948
1949/*
LemonBoy09371822022-04-08 15:18:45 +01001950 * Return TRUE when there is a WinScrolled autocommand defined.
1951 */
1952 int
1953has_winscrolled(void)
1954{
1955 return (first_autopat[(int)EVENT_WINSCROLLED] != NULL);
1956}
1957
1958/*
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001959 * Return TRUE when there is a CursorMoved autocommand defined.
1960 */
1961 int
1962has_cursormoved(void)
1963{
1964 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
1965}
1966
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001967/*
1968 * Return TRUE when there is a CursorMovedI autocommand defined.
1969 */
1970 int
1971has_cursormovedI(void)
1972{
1973 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
1974}
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001975
1976/*
1977 * Return TRUE when there is a TextChanged autocommand defined.
1978 */
1979 int
1980has_textchanged(void)
1981{
1982 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
1983}
1984
1985/*
1986 * Return TRUE when there is a TextChangedI autocommand defined.
1987 */
1988 int
1989has_textchangedI(void)
1990{
1991 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
1992}
1993
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01001994/*
1995 * Return TRUE when there is a TextChangedP autocommand defined.
1996 */
1997 int
1998has_textchangedP(void)
1999{
2000 return (first_autopat[(int)EVENT_TEXTCHANGEDP] != NULL);
2001}
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002002
2003/*
2004 * Return TRUE when there is an InsertCharPre autocommand defined.
2005 */
2006 int
2007has_insertcharpre(void)
2008{
2009 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
2010}
2011
2012/*
2013 * Return TRUE when there is an CmdUndefined autocommand defined.
2014 */
2015 int
2016has_cmdundefined(void)
2017{
2018 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
2019}
2020
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002021#if defined(FEAT_EVAL) || defined(PROTO)
2022/*
2023 * Return TRUE when there is a TextYankPost autocommand defined.
2024 */
2025 int
2026has_textyankpost(void)
2027{
2028 return (first_autopat[(int)EVENT_TEXTYANKPOST] != NULL);
2029}
2030#endif
2031
Bram Moolenaard7f246c2019-04-08 18:15:41 +02002032#if defined(FEAT_EVAL) || defined(PROTO)
2033/*
2034 * Return TRUE when there is a CompleteChanged autocommand defined.
2035 */
2036 int
2037has_completechanged(void)
2038{
2039 return (first_autopat[(int)EVENT_COMPLETECHANGED] != NULL);
2040}
2041#endif
2042
=?UTF-8?q?Magnus=20Gro=C3=9F?=f1e88762021-09-12 13:39:55 +02002043#if defined(FEAT_EVAL) || defined(PROTO)
2044/*
2045 * Return TRUE when there is a ModeChanged autocommand defined.
2046 */
2047 int
2048has_modechanged(void)
2049{
2050 return (first_autopat[(int)EVENT_MODECHANGED] != NULL);
2051}
2052#endif
2053
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002054/*
2055 * Execute autocommands for "event" and file name "fname".
2056 * Return TRUE if some commands were executed.
2057 */
2058 static int
2059apply_autocmds_group(
2060 event_T event,
2061 char_u *fname, // NULL or empty means use actual file name
2062 char_u *fname_io, // fname to use for <afile> on cmdline, NULL means
2063 // use fname
2064 int force, // when TRUE, ignore autocmd_busy
2065 int group, // group ID, or AUGROUP_ALL
2066 buf_T *buf, // buffer for <abuf>
2067 exarg_T *eap UNUSED) // command arguments
2068{
2069 char_u *sfname = NULL; // short file name
2070 char_u *tail;
2071 int save_changed;
2072 buf_T *old_curbuf;
2073 int retval = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002074 char_u *save_autocmd_fname;
2075 int save_autocmd_fname_full;
2076 int save_autocmd_bufnr;
2077 char_u *save_autocmd_match;
2078 int save_autocmd_busy;
2079 int save_autocmd_nested;
2080 static int nesting = 0;
LemonBoyeca7c602022-04-14 15:39:43 +01002081 AutoPatCmd_T patcmd;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002082 AutoPat *ap;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002083 sctx_T save_current_sctx;
Bram Moolenaar9b8d6222020-12-28 18:26:00 +01002084#ifdef FEAT_EVAL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002085 funccal_entry_T funccal_entry;
2086 char_u *save_cmdarg;
2087 long save_cmdbang;
2088#endif
2089 static int filechangeshell_busy = FALSE;
2090#ifdef FEAT_PROFILE
2091 proftime_T wait_time;
2092#endif
2093 int did_save_redobuff = FALSE;
2094 save_redo_T save_redo;
2095 int save_KeyTyped = KeyTyped;
ichizok7e5fe382023-04-15 13:17:50 +01002096 ESTACK_CHECK_DECLARATION;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002097
2098 /*
2099 * Quickly return if there are no autocommands for this event or
2100 * autocommands are blocked.
2101 */
2102 if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
2103 || autocmd_blocked > 0)
2104 goto BYPASS_AU;
2105
2106 /*
2107 * When autocommands are busy, new autocommands are only executed when
2108 * explicitly enabled with the "nested" flag.
2109 */
2110 if (autocmd_busy && !(force || autocmd_nested))
2111 goto BYPASS_AU;
2112
2113#ifdef FEAT_EVAL
2114 /*
2115 * Quickly return when immediately aborting on error, or when an interrupt
2116 * occurred or an exception was thrown but not caught.
2117 */
2118 if (aborting())
2119 goto BYPASS_AU;
2120#endif
2121
2122 /*
2123 * FileChangedShell never nests, because it can create an endless loop.
2124 */
2125 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
2126 || event == EVENT_FILECHANGEDSHELLPOST))
2127 goto BYPASS_AU;
2128
2129 /*
2130 * Ignore events in 'eventignore'.
2131 */
2132 if (event_ignored(event))
2133 goto BYPASS_AU;
2134
2135 /*
2136 * Allow nesting of autocommands, but restrict the depth, because it's
2137 * possible to create an endless loop.
2138 */
2139 if (nesting == 10)
2140 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00002141 emsg(_(e_autocommand_nesting_too_deep));
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002142 goto BYPASS_AU;
2143 }
2144
2145 /*
2146 * Check if these autocommands are disabled. Used when doing ":all" or
2147 * ":ball".
2148 */
2149 if ( (autocmd_no_enter
2150 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
2151 || (autocmd_no_leave
2152 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
2153 goto BYPASS_AU;
2154
Bram Moolenaarbb393d82022-12-09 12:21:50 +00002155 if (event == EVENT_CMDLINECHANGED)
2156 ++aucmd_cmdline_changed_count;
2157
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002158 /*
2159 * Save the autocmd_* variables and info about the current buffer.
2160 */
2161 save_autocmd_fname = autocmd_fname;
2162 save_autocmd_fname_full = autocmd_fname_full;
2163 save_autocmd_bufnr = autocmd_bufnr;
2164 save_autocmd_match = autocmd_match;
2165 save_autocmd_busy = autocmd_busy;
2166 save_autocmd_nested = autocmd_nested;
2167 save_changed = curbuf->b_changed;
2168 old_curbuf = curbuf;
2169
2170 /*
2171 * Set the file name to be used for <afile>.
2172 * Make a copy to avoid that changing a buffer name or directory makes it
2173 * invalid.
2174 */
2175 if (fname_io == NULL)
2176 {
2177 if (event == EVENT_COLORSCHEME || event == EVENT_COLORSCHEMEPRE
Bram Moolenaarbb393d82022-12-09 12:21:50 +00002178 || event == EVENT_OPTIONSET
Danek Duvalld7d56032024-01-14 20:19:59 +01002179 || event == EVENT_MODECHANGED
2180 || event == EVENT_TERMRESPONSEALL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002181 autocmd_fname = NULL;
2182 else if (fname != NULL && !ends_excmd(*fname))
2183 autocmd_fname = fname;
2184 else if (buf != NULL)
2185 autocmd_fname = buf->b_ffname;
2186 else
2187 autocmd_fname = NULL;
2188 }
2189 else
2190 autocmd_fname = fname_io;
2191 if (autocmd_fname != NULL)
2192 autocmd_fname = vim_strsave(autocmd_fname);
2193 autocmd_fname_full = FALSE; // call FullName_save() later
2194
2195 /*
2196 * Set the buffer number to be used for <abuf>.
2197 */
2198 if (buf == NULL)
2199 autocmd_bufnr = 0;
2200 else
2201 autocmd_bufnr = buf->b_fnum;
2202
2203 /*
2204 * When the file name is NULL or empty, use the file name of buffer "buf".
2205 * Always use the full path of the file name to match with, in case
2206 * "allow_dirs" is set.
2207 */
2208 if (fname == NULL || *fname == NUL)
2209 {
2210 if (buf == NULL)
2211 fname = NULL;
2212 else
2213 {
2214#ifdef FEAT_SYN_HL
2215 if (event == EVENT_SYNTAX)
2216 fname = buf->b_p_syn;
2217 else
2218#endif
2219 if (event == EVENT_FILETYPE)
2220 fname = buf->b_p_ft;
2221 else
2222 {
2223 if (buf->b_sfname != NULL)
2224 sfname = vim_strsave(buf->b_sfname);
2225 fname = buf->b_ffname;
2226 }
2227 }
2228 if (fname == NULL)
2229 fname = (char_u *)"";
2230 fname = vim_strsave(fname); // make a copy, so we can change it
2231 }
2232 else
2233 {
2234 sfname = vim_strsave(fname);
2235 // Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
Bram Moolenaarf6246f52022-02-11 16:30:12 +00002236 // ColorScheme, QuickFixCmd*, DirChanged and similar.
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002237 if (event == EVENT_FILETYPE
2238 || event == EVENT_SYNTAX
2239 || event == EVENT_CMDLINECHANGED
2240 || event == EVENT_CMDLINEENTER
2241 || event == EVENT_CMDLINELEAVE
2242 || event == EVENT_CMDWINENTER
2243 || event == EVENT_CMDWINLEAVE
2244 || event == EVENT_CMDUNDEFINED
2245 || event == EVENT_FUNCUNDEFINED
2246 || event == EVENT_REMOTEREPLY
2247 || event == EVENT_SPELLFILEMISSING
2248 || event == EVENT_QUICKFIXCMDPRE
2249 || event == EVENT_COLORSCHEME
2250 || event == EVENT_COLORSCHEMEPRE
2251 || event == EVENT_OPTIONSET
2252 || event == EVENT_QUICKFIXCMDPOST
=?UTF-8?q?Magnus=20Gro=C3=9F?=f1e88762021-09-12 13:39:55 +02002253 || event == EVENT_DIRCHANGED
Bram Moolenaarf6246f52022-02-11 16:30:12 +00002254 || event == EVENT_DIRCHANGEDPRE
naohiro ono23beefe2021-11-13 12:38:49 +00002255 || event == EVENT_MODECHANGED
zeertzjqc601d982022-10-10 13:46:15 +01002256 || event == EVENT_MENUPOPUP
Bram Moolenaarf6246f52022-02-11 16:30:12 +00002257 || event == EVENT_USER
LemonBoy09371822022-04-08 15:18:45 +01002258 || event == EVENT_WINCLOSED
Bram Moolenaar35fc61c2022-11-22 12:40:50 +00002259 || event == EVENT_WINRESIZED
Danek Duvalld7d56032024-01-14 20:19:59 +01002260 || event == EVENT_WINSCROLLED
2261 || event == EVENT_TERMRESPONSEALL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002262 {
2263 fname = vim_strsave(fname);
2264 autocmd_fname_full = TRUE; // don't expand it later
2265 }
2266 else
2267 fname = FullName_save(fname, FALSE);
2268 }
2269 if (fname == NULL) // out of memory
2270 {
2271 vim_free(sfname);
2272 retval = FALSE;
2273 goto BYPASS_AU;
2274 }
2275
2276#ifdef BACKSLASH_IN_FILENAME
2277 /*
2278 * Replace all backslashes with forward slashes. This makes the
2279 * autocommand patterns portable between Unix and MS-DOS.
2280 */
2281 if (sfname != NULL)
2282 forward_slash(sfname);
2283 forward_slash(fname);
2284#endif
2285
2286#ifdef VMS
2287 // remove version for correct match
2288 if (sfname != NULL)
2289 vms_remove_version(sfname);
2290 vms_remove_version(fname);
2291#endif
2292
2293 /*
2294 * Set the name to be used for <amatch>.
2295 */
2296 autocmd_match = fname;
2297
2298
2299 // Don't redraw while doing autocommands.
2300 ++RedrawingDisabled;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002301
2302 // name and lnum are filled in later
2303 estack_push(ETYPE_AUCMD, NULL, 0);
ichizok7e5fe382023-04-15 13:17:50 +01002304 ESTACK_CHECK_SETUP;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002305
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002306 save_current_sctx = current_sctx;
2307
Bram Moolenaar9b8d6222020-12-28 18:26:00 +01002308#ifdef FEAT_EVAL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002309# ifdef FEAT_PROFILE
2310 if (do_profiling == PROF_YES)
2311 prof_child_enter(&wait_time); // doesn't count for the caller itself
2312# endif
2313
2314 // Don't use local function variables, if called from a function.
2315 save_funccal(&funccal_entry);
2316#endif
2317
2318 /*
2319 * When starting to execute autocommands, save the search patterns.
2320 */
2321 if (!autocmd_busy)
2322 {
2323 save_search_patterns();
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002324 if (!ins_compl_active())
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002325 {
2326 saveRedobuff(&save_redo);
2327 did_save_redobuff = TRUE;
2328 }
zeertzjq5bf6c212024-03-31 18:41:27 +02002329 curbuf->b_did_filetype = curbuf->b_keep_filetype;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002330 }
2331
2332 /*
2333 * Note that we are applying autocmds. Some commands need to know.
2334 */
2335 autocmd_busy = TRUE;
2336 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
2337 ++nesting; // see matching decrement below
2338
2339 // Remember that FileType was triggered. Used for did_filetype().
2340 if (event == EVENT_FILETYPE)
zeertzjq5bf6c212024-03-31 18:41:27 +02002341 curbuf->b_did_filetype = TRUE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002342
2343 tail = gettail(fname);
2344
2345 // Find first autocommand that matches
LemonBoyeca7c602022-04-14 15:39:43 +01002346 CLEAR_FIELD(patcmd);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002347 patcmd.curpat = first_autopat[(int)event];
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002348 patcmd.group = group;
2349 patcmd.fname = fname;
2350 patcmd.sfname = sfname;
2351 patcmd.tail = tail;
2352 patcmd.event = event;
2353 patcmd.arg_bufnr = autocmd_bufnr;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002354 auto_next_pat(&patcmd, FALSE);
2355
2356 // found one, start executing the autocommands
2357 if (patcmd.curpat != NULL)
2358 {
2359 // add to active_apc_list
2360 patcmd.next = active_apc_list;
2361 active_apc_list = &patcmd;
2362
2363#ifdef FEAT_EVAL
2364 // set v:cmdarg (only when there is a matching pattern)
2365 save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
2366 if (eap != NULL)
2367 {
2368 save_cmdarg = set_cmdarg(eap, NULL);
2369 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
2370 }
2371 else
2372 save_cmdarg = NULL; // avoid gcc warning
2373#endif
2374 retval = TRUE;
2375 // mark the last pattern, to avoid an endless loop when more patterns
2376 // are added when executing autocommands
2377 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
2378 ap->last = FALSE;
2379 ap->last = TRUE;
Bram Moolenaara68e5952019-04-25 22:22:01 +02002380
Bram Moolenaar5fa9f232022-07-23 09:06:48 +01002381 // Make sure cursor and topline are valid. The first time the current
2382 // values are saved, restored by reset_lnums(). When nested only the
2383 // values are corrected when needed.
Bram Moolenaar1e6bbfb2021-04-03 13:19:26 +02002384 if (nesting == 1)
Bram Moolenaar1e6bbfb2021-04-03 13:19:26 +02002385 check_lnums(TRUE);
Bram Moolenaar5fa9f232022-07-23 09:06:48 +01002386 else
2387 check_lnums_nested(TRUE);
Bram Moolenaara68e5952019-04-25 22:22:01 +02002388
Christian Brabandt590aae32023-06-25 22:34:22 +01002389 int save_did_emsg = did_emsg;
2390 int save_ex_pressedreturn = get_pressedreturn();
ichizokc3f91c02021-12-17 09:44:33 +00002391
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002392 do_cmdline(NULL, getnextac, (void *)&patcmd,
2393 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
Bram Moolenaara68e5952019-04-25 22:22:01 +02002394
ichizokc3f91c02021-12-17 09:44:33 +00002395 did_emsg += save_did_emsg;
Christian Brabandt590aae32023-06-25 22:34:22 +01002396 set_pressedreturn(save_ex_pressedreturn);
ichizokc3f91c02021-12-17 09:44:33 +00002397
Bram Moolenaar1e6bbfb2021-04-03 13:19:26 +02002398 if (nesting == 1)
2399 // restore cursor and topline, unless they were changed
2400 reset_lnums();
Bram Moolenaara68e5952019-04-25 22:22:01 +02002401
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002402#ifdef FEAT_EVAL
2403 if (eap != NULL)
2404 {
2405 (void)set_cmdarg(NULL, save_cmdarg);
2406 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
2407 }
2408#endif
2409 // delete from active_apc_list
2410 if (active_apc_list == &patcmd) // just in case
2411 active_apc_list = patcmd.next;
2412 }
2413
Bram Moolenaar79cdf022023-05-20 14:07:00 +01002414 if (RedrawingDisabled > 0)
2415 --RedrawingDisabled;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002416 autocmd_busy = save_autocmd_busy;
2417 filechangeshell_busy = FALSE;
2418 autocmd_nested = save_autocmd_nested;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002419 vim_free(SOURCING_NAME);
ichizok7e5fe382023-04-15 13:17:50 +01002420 ESTACK_CHECK_NOW;
Bram Moolenaar1a47ae32019-12-29 23:04:25 +01002421 estack_pop();
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002422 vim_free(autocmd_fname);
2423 autocmd_fname = save_autocmd_fname;
2424 autocmd_fname_full = save_autocmd_fname_full;
2425 autocmd_bufnr = save_autocmd_bufnr;
2426 autocmd_match = save_autocmd_match;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002427 current_sctx = save_current_sctx;
Bram Moolenaar9b8d6222020-12-28 18:26:00 +01002428#ifdef FEAT_EVAL
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002429 restore_funccal();
2430# ifdef FEAT_PROFILE
2431 if (do_profiling == PROF_YES)
2432 prof_child_exit(&wait_time);
2433# endif
2434#endif
2435 KeyTyped = save_KeyTyped;
2436 vim_free(fname);
2437 vim_free(sfname);
2438 --nesting; // see matching increment above
2439
2440 /*
2441 * When stopping to execute autocommands, restore the search patterns and
2442 * the redo buffer. Free any buffers in the au_pending_free_buf list and
2443 * free any windows in the au_pending_free_win list.
2444 */
2445 if (!autocmd_busy)
2446 {
2447 restore_search_patterns();
2448 if (did_save_redobuff)
2449 restoreRedobuff(&save_redo);
zeertzjq5bf6c212024-03-31 18:41:27 +02002450 curbuf->b_did_filetype = FALSE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002451 while (au_pending_free_buf != NULL)
2452 {
2453 buf_T *b = au_pending_free_buf->b_next;
Bram Moolenaar41cd8032021-03-13 15:47:56 +01002454
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002455 vim_free(au_pending_free_buf);
2456 au_pending_free_buf = b;
2457 }
2458 while (au_pending_free_win != NULL)
2459 {
2460 win_T *w = au_pending_free_win->w_next;
Bram Moolenaar41cd8032021-03-13 15:47:56 +01002461
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002462 vim_free(au_pending_free_win);
2463 au_pending_free_win = w;
2464 }
2465 }
2466
2467 /*
2468 * Some events don't set or reset the Changed flag.
2469 * Check if still in the same buffer!
2470 */
2471 if (curbuf == old_curbuf
2472 && (event == EVENT_BUFREADPOST
2473 || event == EVENT_BUFWRITEPOST
2474 || event == EVENT_FILEAPPENDPOST
2475 || event == EVENT_VIMLEAVE
2476 || event == EVENT_VIMLEAVEPRE))
2477 {
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002478 if (curbuf->b_changed != save_changed)
2479 need_maketitle = TRUE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002480 curbuf->b_changed = save_changed;
2481 }
2482
2483 au_cleanup(); // may really delete removed patterns/commands now
2484
2485BYPASS_AU:
2486 // When wiping out a buffer make sure all its buffer-local autocommands
2487 // are deleted.
2488 if (event == EVENT_BUFWIPEOUT && buf != NULL)
2489 aubuflocal_remove(buf);
2490
2491 if (retval == OK && event == EVENT_FILETYPE)
zeertzjq5bf6c212024-03-31 18:41:27 +02002492 curbuf->b_au_did_filetype = TRUE;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002493
2494 return retval;
2495}
2496
2497# ifdef FEAT_EVAL
2498static char_u *old_termresponse = NULL;
Danek Duvalld7d56032024-01-14 20:19:59 +01002499static char_u *old_termu7resp = NULL;
2500static char_u *old_termblinkresp = NULL;
2501static char_u *old_termrbgresp = NULL;
2502static char_u *old_termrfgresp = NULL;
2503static char_u *old_termstyleresp = NULL;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002504# endif
2505
2506/*
2507 * Block triggering autocommands until unblock_autocmd() is called.
2508 * Can be used recursively, so long as it's symmetric.
2509 */
2510 void
2511block_autocmds(void)
2512{
2513# ifdef FEAT_EVAL
2514 // Remember the value of v:termresponse.
2515 if (autocmd_blocked == 0)
Danek Duvalld7d56032024-01-14 20:19:59 +01002516 {
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002517 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
Danek Duvalld7d56032024-01-14 20:19:59 +01002518 old_termu7resp = get_vim_var_str(VV_TERMU7RESP);
2519 old_termblinkresp = get_vim_var_str(VV_TERMBLINKRESP);
2520 old_termrbgresp = get_vim_var_str(VV_TERMRBGRESP);
2521 old_termrfgresp = get_vim_var_str(VV_TERMRFGRESP);
2522 old_termstyleresp = get_vim_var_str(VV_TERMSTYLERESP);
2523 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002524# endif
2525 ++autocmd_blocked;
2526}
2527
2528 void
2529unblock_autocmds(void)
2530{
2531 --autocmd_blocked;
2532
2533# ifdef FEAT_EVAL
Danek Duvalld7d56032024-01-14 20:19:59 +01002534 // When v:termresponse, etc, were set while autocommands were blocked,
2535 // trigger the autocommands now. Esp. useful when executing a shell
2536 // command during startup (vimdiff).
2537 if (autocmd_blocked == 0)
2538 {
2539 if (get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
2540 {
2541 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
2542 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"version", NULL, FALSE, curbuf);
2543 }
2544 if (get_vim_var_str(VV_TERMU7RESP) != old_termu7resp)
2545 {
2546 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"ambiguouswidth", NULL, FALSE, curbuf);
2547 }
2548 if (get_vim_var_str(VV_TERMBLINKRESP) != old_termblinkresp)
2549 {
2550 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"cursorblink", NULL, FALSE, curbuf);
2551 }
2552 if (get_vim_var_str(VV_TERMRBGRESP) != old_termrbgresp)
2553 {
2554 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"background", NULL, FALSE, curbuf);
2555 }
2556 if (get_vim_var_str(VV_TERMRFGRESP) != old_termrfgresp)
2557 {
2558 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"foreground", NULL, FALSE, curbuf);
2559 }
2560 if (get_vim_var_str(VV_TERMSTYLERESP) != old_termstyleresp)
2561 {
2562 apply_autocmds(EVENT_TERMRESPONSEALL, (char_u *)"cursorshape", NULL, FALSE, curbuf);
2563 }
2564 }
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002565# endif
2566}
2567
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002568 int
2569is_autocmd_blocked(void)
2570{
2571 return autocmd_blocked != 0;
2572}
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002573
2574/*
2575 * Find next autocommand pattern that matches.
2576 */
2577 static void
2578auto_next_pat(
LemonBoyeca7c602022-04-14 15:39:43 +01002579 AutoPatCmd_T *apc,
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002580 int stop_at_last) // stop when 'last' flag is set
2581{
2582 AutoPat *ap;
2583 AutoCmd *cp;
2584 char_u *name;
2585 char *s;
LemonBoyeca7c602022-04-14 15:39:43 +01002586 estack_T *entry;
2587 char_u *namep;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002588
LemonBoyeca7c602022-04-14 15:39:43 +01002589 entry = ((estack_T *)exestack.ga_data) + exestack.ga_len - 1;
2590
2591 // Clear the exestack entry for this ETYPE_AUCMD entry.
2592 VIM_CLEAR(entry->es_name);
2593 entry->es_info.aucmd = NULL;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002594
2595 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
2596 {
2597 apc->curpat = NULL;
2598
2599 // Only use a pattern when it has not been removed, has commands and
2600 // the group matches. For buffer-local autocommands only check the
2601 // buffer number.
2602 if (ap->pat != NULL && ap->cmds != NULL
2603 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
2604 {
2605 // execution-condition
2606 if (ap->buflocal_nr == 0
2607 ? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
2608 apc->sfname, apc->tail, ap->allow_dirs))
2609 : ap->buflocal_nr == apc->arg_bufnr)
2610 {
2611 name = event_nr2name(apc->event);
2612 s = _("%s Autocommands for \"%s\"");
LemonBoyeca7c602022-04-14 15:39:43 +01002613 namep = alloc(STRLEN(s) + STRLEN(name) + ap->patlen + 1);
2614 if (namep != NULL)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002615 {
LemonBoyeca7c602022-04-14 15:39:43 +01002616 sprintf((char *)namep, s, (char *)name, (char *)ap->pat);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002617 if (p_verbose >= 8)
2618 {
2619 verbose_enter();
LemonBoyeca7c602022-04-14 15:39:43 +01002620 smsg(_("Executing %s"), namep);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002621 verbose_leave();
2622 }
2623 }
2624
LemonBoyeca7c602022-04-14 15:39:43 +01002625 // Update the exestack entry for this autocmd.
2626 entry->es_name = namep;
2627 entry->es_info.aucmd = apc;
2628
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002629 apc->curpat = ap;
2630 apc->nextcmd = ap->cmds;
2631 // mark last command
2632 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
2633 cp->last = FALSE;
2634 cp->last = TRUE;
2635 }
2636 line_breakcheck();
2637 if (apc->curpat != NULL) // found a match
2638 break;
2639 }
2640 if (stop_at_last && ap->last)
2641 break;
2642 }
2643}
2644
Dominique Pellee764d1b2023-03-12 21:20:59 +00002645#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002646/*
LemonBoyeca7c602022-04-14 15:39:43 +01002647 * Get the script context where autocommand "acp" is defined.
2648 */
2649 sctx_T *
2650acp_script_ctx(AutoPatCmd_T *acp)
2651{
2652 return &acp->script_ctx;
2653}
Dominique Pellee764d1b2023-03-12 21:20:59 +00002654#endif
LemonBoyeca7c602022-04-14 15:39:43 +01002655
2656/*
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002657 * Get next autocommand command.
2658 * Called by do_cmdline() to get the next line for ":if".
2659 * Returns allocated string, or NULL for end of autocommands.
2660 */
2661 char_u *
Bram Moolenaar66250c92020-08-20 15:02:42 +02002662getnextac(
2663 int c UNUSED,
2664 void *cookie,
2665 int indent UNUSED,
2666 getline_opt_T options UNUSED)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002667{
LemonBoyeca7c602022-04-14 15:39:43 +01002668 AutoPatCmd_T *acp = (AutoPatCmd_T *)cookie;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002669 char_u *retval;
2670 AutoCmd *ac;
2671
2672 // Can be called again after returning the last line.
2673 if (acp->curpat == NULL)
2674 return NULL;
2675
2676 // repeat until we find an autocommand to execute
2677 for (;;)
2678 {
2679 // skip removed commands
2680 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
2681 if (acp->nextcmd->last)
2682 acp->nextcmd = NULL;
2683 else
2684 acp->nextcmd = acp->nextcmd->next;
2685
2686 if (acp->nextcmd != NULL)
2687 break;
2688
2689 // at end of commands, find next pattern that matches
2690 if (acp->curpat->last)
2691 acp->curpat = NULL;
2692 else
2693 acp->curpat = acp->curpat->next;
2694 if (acp->curpat != NULL)
2695 auto_next_pat(acp, TRUE);
2696 if (acp->curpat == NULL)
2697 return NULL;
2698 }
2699
2700 ac = acp->nextcmd;
2701
2702 if (p_verbose >= 9)
2703 {
2704 verbose_enter_scroll();
2705 smsg(_("autocommand %s"), ac->cmd);
2706 msg_puts("\n"); // don't overwrite this either
2707 verbose_leave_scroll();
2708 }
2709 retval = vim_strsave(ac->cmd);
Bram Moolenaareb93f3f2019-04-04 15:04:56 +02002710 // Remove one-shot ("once") autocmd in anticipation of its execution.
2711 if (ac->once)
2712 au_del_cmd(ac);
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002713 autocmd_nested = ac->nested;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002714 current_sctx = ac->script_ctx;
LemonBoyeca7c602022-04-14 15:39:43 +01002715 acp->script_ctx = current_sctx;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002716 if (ac->last)
2717 acp->nextcmd = NULL;
2718 else
2719 acp->nextcmd = ac->next;
2720 return retval;
2721}
2722
2723/*
2724 * Return TRUE if there is a matching autocommand for "fname".
2725 * To account for buffer-local autocommands, function needs to know
2726 * in which buffer the file will be opened.
2727 */
2728 int
2729has_autocmd(event_T event, char_u *sfname, buf_T *buf)
2730{
2731 AutoPat *ap;
2732 char_u *fname;
2733 char_u *tail = gettail(sfname);
2734 int retval = FALSE;
2735
2736 fname = FullName_save(sfname, FALSE);
2737 if (fname == NULL)
2738 return FALSE;
2739
2740#ifdef BACKSLASH_IN_FILENAME
2741 /*
2742 * Replace all backslashes with forward slashes. This makes the
2743 * autocommand patterns portable between Unix and MS-DOS.
2744 */
2745 sfname = vim_strsave(sfname);
2746 if (sfname != NULL)
2747 forward_slash(sfname);
2748 forward_slash(fname);
2749#endif
2750
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002751 FOR_ALL_AUTOCMD_PATTERNS(event, ap)
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002752 if (ap->pat != NULL && ap->cmds != NULL
2753 && (ap->buflocal_nr == 0
2754 ? match_file_pat(NULL, &ap->reg_prog,
2755 fname, sfname, tail, ap->allow_dirs)
2756 : buf != NULL && ap->buflocal_nr == buf->b_fnum
2757 ))
2758 {
2759 retval = TRUE;
2760 break;
2761 }
2762
2763 vim_free(fname);
2764#ifdef BACKSLASH_IN_FILENAME
2765 vim_free(sfname);
2766#endif
2767
2768 return retval;
2769}
2770
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002771/*
2772 * Function given to ExpandGeneric() to obtain the list of autocommand group
2773 * names.
2774 */
2775 char_u *
2776get_augroup_name(expand_T *xp UNUSED, int idx)
2777{
2778 if (idx == augroups.ga_len) // add "END" add the end
2779 return (char_u *)"END";
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01002780 if (idx < 0 || idx >= augroups.ga_len) // end of list
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002781 return NULL;
2782 if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
2783 // skip deleted entries
2784 return (char_u *)"";
2785 return AUGROUP_NAME(idx); // return a name
2786}
2787
2788static int include_groups = FALSE;
2789
2790 char_u *
2791set_context_in_autocmd(
2792 expand_T *xp,
2793 char_u *arg,
2794 int doautocmd) // TRUE for :doauto*, FALSE for :autocmd
2795{
2796 char_u *p;
2797 int group;
2798
2799 // check for a group name, skip it if present
2800 include_groups = FALSE;
2801 p = arg;
2802 group = au_get_grouparg(&arg);
2803 if (group == AUGROUP_ERROR)
2804 return NULL;
2805 // If there only is a group name that's what we expand.
2806 if (*arg == NUL && group != AUGROUP_ALL && !VIM_ISWHITE(arg[-1]))
2807 {
2808 arg = p;
2809 group = AUGROUP_ALL;
2810 }
2811
2812 // skip over event name
2813 for (p = arg; *p != NUL && !VIM_ISWHITE(*p); ++p)
2814 if (*p == ',')
2815 arg = p + 1;
2816 if (*p == NUL)
2817 {
2818 if (group == AUGROUP_ALL)
2819 include_groups = TRUE;
2820 xp->xp_context = EXPAND_EVENTS; // expand event name
2821 xp->xp_pattern = arg;
2822 return NULL;
2823 }
2824
2825 // skip over pattern
2826 arg = skipwhite(p);
2827 while (*arg && (!VIM_ISWHITE(*arg) || arg[-1] == '\\'))
2828 arg++;
2829 if (*arg)
2830 return arg; // expand (next) command
2831
2832 if (doautocmd)
2833 xp->xp_context = EXPAND_FILES; // expand file names
2834 else
2835 xp->xp_context = EXPAND_NOTHING; // pattern is not expanded
2836 return NULL;
2837}
2838
2839/*
2840 * Function given to ExpandGeneric() to obtain the list of event names.
2841 */
2842 char_u *
2843get_event_name(expand_T *xp UNUSED, int idx)
2844{
John Marriott78d742a2024-04-02 20:26:01 +02002845 int i;
2846
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002847 if (idx < augroups.ga_len) // First list group names, if wanted
2848 {
2849 if (!include_groups || AUGROUP_NAME(idx) == NULL
2850 || AUGROUP_NAME(idx) == get_deleted_augroup())
2851 return (char_u *)""; // skip deleted entries
2852 return AUGROUP_NAME(idx); // return a name
2853 }
John Marriott78d742a2024-04-02 20:26:01 +02002854
2855 i = idx - augroups.ga_len;
2856 if (i < 0 || i >= (int)ARRAY_LENGTH(event_tab))
2857 return NULL;
2858
2859 return (char_u *)event_tab[i].value;
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002860}
2861
Yee Cheng Chin900894b2023-09-29 20:42:32 +02002862/*
2863 * Function given to ExpandGeneric() to obtain the list of event names. Don't
2864 * include groups.
2865 */
2866 char_u *
2867get_event_name_no_group(expand_T *xp UNUSED, int idx)
2868{
John Marriott78d742a2024-04-02 20:26:01 +02002869 if (idx < 0 || idx >= (int)ARRAY_LENGTH(event_tab))
2870 return NULL;
2871
2872 return (char_u *)event_tab[idx].value;
Yee Cheng Chin900894b2023-09-29 20:42:32 +02002873}
2874
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01002875
2876#if defined(FEAT_EVAL) || defined(PROTO)
2877/*
2878 * Return TRUE if autocmd is supported.
2879 */
2880 int
2881autocmd_supported(char_u *name)
2882{
2883 char_u *p;
2884
2885 return (event_name2nr(name, &p) != NUM_EVENTS);
2886}
2887
2888/*
2889 * Return TRUE if an autocommand is defined for a group, event and
2890 * pattern: The group can be omitted to accept any group. "event" and "pattern"
2891 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
2892 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
2893 * Used for:
2894 * exists("#Group") or
2895 * exists("#Group#Event") or
2896 * exists("#Group#Event#pat") or
2897 * exists("#Event") or
2898 * exists("#Event#pat")
2899 */
2900 int
2901au_exists(char_u *arg)
2902{
2903 char_u *arg_save;
2904 char_u *pattern = NULL;
2905 char_u *event_name;
2906 char_u *p;
2907 event_T event;
2908 AutoPat *ap;
2909 buf_T *buflocal_buf = NULL;
2910 int group;
2911 int retval = FALSE;
2912
2913 // Make a copy so that we can change the '#' chars to a NUL.
2914 arg_save = vim_strsave(arg);
2915 if (arg_save == NULL)
2916 return FALSE;
2917 p = vim_strchr(arg_save, '#');
2918 if (p != NULL)
2919 *p++ = NUL;
2920
2921 // First, look for an autocmd group name
2922 group = au_find_group(arg_save);
2923 if (group == AUGROUP_ERROR)
2924 {
2925 // Didn't match a group name, assume the first argument is an event.
2926 group = AUGROUP_ALL;
2927 event_name = arg_save;
2928 }
2929 else
2930 {
2931 if (p == NULL)
2932 {
2933 // "Group": group name is present and it's recognized
2934 retval = TRUE;
2935 goto theend;
2936 }
2937
2938 // Must be "Group#Event" or "Group#Event#pat".
2939 event_name = p;
2940 p = vim_strchr(event_name, '#');
2941 if (p != NULL)
2942 *p++ = NUL; // "Group#Event#pat"
2943 }
2944
2945 pattern = p; // "pattern" is NULL when there is no pattern
2946
2947 // find the index (enum) for the event name
2948 event = event_name2nr(event_name, &p);
2949
2950 // return FALSE if the event name is not recognized
2951 if (event == NUM_EVENTS)
2952 goto theend;
2953
2954 // Find the first autocommand for this event.
2955 // If there isn't any, return FALSE;
2956 // If there is one and no pattern given, return TRUE;
2957 ap = first_autopat[(int)event];
2958 if (ap == NULL)
2959 goto theend;
2960
2961 // if pattern is "<buffer>", special handling is needed which uses curbuf
2962 // for pattern "<buffer=N>, fnamecmp() will work fine
2963 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
2964 buflocal_buf = curbuf;
2965
2966 // Check if there is an autocommand with the given pattern.
2967 for ( ; ap != NULL; ap = ap->next)
2968 // only use a pattern when it has not been removed and has commands.
2969 // For buffer-local autocommands, fnamecmp() works fine.
2970 if (ap->pat != NULL && ap->cmds != NULL
2971 && (group == AUGROUP_ALL || ap->group == group)
2972 && (pattern == NULL
2973 || (buflocal_buf == NULL
2974 ? fnamecmp(ap->pat, pattern) == 0
2975 : ap->buflocal_nr == buflocal_buf->b_fnum)))
2976 {
2977 retval = TRUE;
2978 break;
2979 }
2980
2981theend:
2982 vim_free(arg_save);
2983 return retval;
2984}
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01002985
2986/*
2987 * autocmd_add() and autocmd_delete() functions
2988 */
2989 static void
2990autocmd_add_or_delete(typval_T *argvars, typval_T *rettv, int delete)
2991{
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01002992 list_T *aucmd_list;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01002993 listitem_T *li;
2994 dict_T *event_dict;
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01002995 dictitem_T *di;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01002996 char_u *event_name = NULL;
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01002997 list_T *event_list;
2998 listitem_T *eli;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01002999 event_T event;
3000 char_u *group_name = NULL;
3001 int group;
3002 char_u *pat = NULL;
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003003 list_T *pat_list;
3004 listitem_T *pli;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003005 char_u *cmd = NULL;
3006 char_u *end;
3007 int once;
3008 int nested;
Yegappan Lakshmanan971f6822022-05-24 11:40:11 +01003009 int replace; // replace the cmd for a group/event
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003010 int retval = VVAL_TRUE;
3011 int save_augroup = current_augroup;
3012
3013 rettv->v_type = VAR_BOOL;
3014 rettv->vval.v_number = VVAL_FALSE;
3015
3016 if (check_for_list_arg(argvars, 0) == FAIL)
3017 return;
3018
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003019 aucmd_list = argvars[0].vval.v_list;
3020 if (aucmd_list == NULL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003021 return;
3022
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003023 FOR_ALL_LIST_ITEMS(aucmd_list, li)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003024 {
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003025 VIM_CLEAR(group_name);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003026 VIM_CLEAR(cmd);
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003027 event_name = NULL;
3028 event_list = NULL;
3029 pat = NULL;
3030 pat_list = NULL;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003031
3032 if (li->li_tv.v_type != VAR_DICT)
3033 continue;
3034
3035 event_dict = li->li_tv.vval.v_dict;
3036 if (event_dict == NULL)
3037 continue;
3038
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003039 di = dict_find(event_dict, (char_u *)"event", -1);
3040 if (di != NULL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003041 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003042 if (di->di_tv.v_type == VAR_STRING)
3043 {
3044 event_name = di->di_tv.vval.v_string;
3045 if (event_name == NULL)
3046 {
3047 emsg(_(e_string_required));
3048 continue;
3049 }
3050 }
3051 else if (di->di_tv.v_type == VAR_LIST)
3052 {
3053 event_list = di->di_tv.vval.v_list;
3054 if (event_list == NULL)
3055 {
3056 emsg(_(e_list_required));
3057 continue;
3058 }
3059 }
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003060 else
3061 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003062 emsg(_(e_string_or_list_expected));
3063 continue;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003064 }
3065 }
3066
Bram Moolenaard61efa52022-07-23 09:52:04 +01003067 group_name = dict_get_string(event_dict, "group", TRUE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003068 if (group_name == NULL || *group_name == NUL)
3069 // if the autocmd group name is not specified, then use the current
3070 // autocmd group
3071 group = current_augroup;
3072 else
3073 {
3074 group = au_find_group(group_name);
3075 if (group == AUGROUP_ERROR)
3076 {
3077 if (delete)
3078 {
3079 semsg(_(e_no_such_group_str), group_name);
3080 retval = VVAL_FALSE;
3081 break;
3082 }
3083 // group is not found, create it now
3084 group = au_new_group(group_name);
3085 if (group == AUGROUP_ERROR)
3086 {
3087 semsg(_(e_no_such_group_str), group_name);
3088 retval = VVAL_FALSE;
3089 break;
3090 }
3091
3092 current_augroup = group;
3093 }
3094 }
3095
3096 // if a buffer number is specified, then generate a pattern of the form
3097 // "<buffer=n>. Otherwise, use the pattern supplied by the user.
3098 if (dict_has_key(event_dict, "bufnr"))
3099 {
3100 varnumber_T bnum;
3101
Bram Moolenaard61efa52022-07-23 09:52:04 +01003102 bnum = dict_get_number_def(event_dict, "bufnr", -1);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003103 if (bnum == -1)
3104 continue;
3105
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003106 vim_snprintf((char *)IObuff, IOSIZE, "<buffer=%d>", (int)bnum);
3107 pat = IObuff;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003108 }
3109 else
3110 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003111 di = dict_find(event_dict, (char_u *)"pattern", -1);
3112 if (di != NULL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003113 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003114 if (di->di_tv.v_type == VAR_STRING)
3115 {
3116 pat = di->di_tv.vval.v_string;
3117 if (pat == NULL)
3118 {
3119 emsg(_(e_string_required));
3120 continue;
3121 }
3122 }
3123 else if (di->di_tv.v_type == VAR_LIST)
3124 {
3125 pat_list = di->di_tv.vval.v_list;
3126 if (pat_list == NULL)
3127 {
3128 emsg(_(e_list_required));
3129 continue;
3130 }
3131 }
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003132 else
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003133 {
3134 emsg(_(e_string_or_list_expected));
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003135 continue;
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003136 }
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003137 }
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003138 else if (delete)
3139 pat = (char_u *)"";
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003140 }
3141
Bram Moolenaard61efa52022-07-23 09:52:04 +01003142 once = dict_get_bool(event_dict, "once", FALSE);
3143 nested = dict_get_bool(event_dict, "nested", FALSE);
Yegappan Lakshmanan971f6822022-05-24 11:40:11 +01003144 // if 'replace' is true, then remove all the commands associated with
3145 // this autocmd event/group and add the new command.
Bram Moolenaard61efa52022-07-23 09:52:04 +01003146 replace = dict_get_bool(event_dict, "replace", FALSE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003147
Bram Moolenaard61efa52022-07-23 09:52:04 +01003148 cmd = dict_get_string(event_dict, "cmd", TRUE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003149 if (cmd == NULL)
3150 {
3151 if (delete)
3152 cmd = vim_strsave((char_u *)"");
3153 else
3154 continue;
3155 }
3156
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003157 if (delete && (event_name == NULL
3158 || (event_name[0] == '*' && event_name[1] == NUL)))
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003159 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003160 // if the event name is not specified or '*', delete all the events
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003161 for (event = (event_T)0; (int)event < NUM_EVENTS;
3162 event = (event_T)((int)event + 1))
3163 {
3164 if (do_autocmd_event(event, pat, once, nested, cmd, delete,
3165 group, 0) == FAIL)
3166 {
3167 retval = VVAL_FALSE;
3168 break;
3169 }
3170 }
3171 }
3172 else
3173 {
Bram Moolenaar968443e2022-05-27 21:16:34 +01003174 char_u *p = NULL;
3175
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003176 eli = NULL;
3177 end = NULL;
3178 while (TRUE)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003179 {
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003180 if (event_list != NULL)
3181 {
3182 if (eli == NULL)
3183 eli = event_list->lv_first;
3184 else
3185 eli = eli->li_next;
3186 if (eli == NULL)
3187 break;
3188 if (eli->li_tv.v_type != VAR_STRING
Bram Moolenaar882476a2022-06-01 16:02:38 +01003189 || (p = eli->li_tv.vval.v_string) == NULL)
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003190 {
3191 emsg(_(e_string_required));
Bram Moolenaar882476a2022-06-01 16:02:38 +01003192 break;
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003193 }
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003194 }
3195 else
3196 {
Bram Moolenaar882476a2022-06-01 16:02:38 +01003197 if (p == NULL)
3198 p = event_name;
3199 if (p == NULL || *p == NUL)
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003200 break;
3201 }
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003202
3203 event = event_name2nr(p, &end);
3204 if (event == NUM_EVENTS || *end != NUL)
3205 {
Bram Moolenaar882476a2022-06-01 16:02:38 +01003206 // this also catches something following a valid event name
Yegappan Lakshmanane0ff3a72022-05-27 18:05:33 +01003207 semsg(_(e_no_such_event_str), p);
3208 retval = VVAL_FALSE;
3209 break;
3210 }
3211 if (pat != NULL)
3212 {
3213 if (do_autocmd_event(event, pat, once, nested, cmd,
3214 delete | replace, group, 0) == FAIL)
3215 {
3216 retval = VVAL_FALSE;
3217 break;
3218 }
3219 }
3220 else if (pat_list != NULL)
3221 {
3222 FOR_ALL_LIST_ITEMS(pat_list, pli)
3223 {
3224 if (pli->li_tv.v_type != VAR_STRING
3225 || pli->li_tv.vval.v_string == NULL)
3226 {
3227 emsg(_(e_string_required));
3228 continue;
3229 }
3230 if (do_autocmd_event(event,
3231 pli->li_tv.vval.v_string, once, nested,
3232 cmd, delete | replace, group, 0) ==
3233 FAIL)
3234 {
3235 retval = VVAL_FALSE;
3236 break;
3237 }
3238 }
3239 if (retval == VVAL_FALSE)
3240 break;
3241 }
3242 if (event_name != NULL)
3243 p = end;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003244 }
3245 }
3246
3247 // if only the autocmd group name is specified for delete and the
3248 // autocmd event, pattern and cmd are not specified, then delete the
3249 // autocmd group.
3250 if (delete && group_name != NULL &&
3251 (event_name == NULL || event_name[0] == NUL)
3252 && (pat == NULL || pat[0] == NUL)
3253 && (cmd == NULL || cmd[0] == NUL))
3254 au_del_group(group_name);
3255 }
3256
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003257 VIM_CLEAR(group_name);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003258 VIM_CLEAR(cmd);
3259
3260 current_augroup = save_augroup;
3261 rettv->vval.v_number = retval;
3262}
3263
3264/*
3265 * autocmd_add() function
3266 */
3267 void
3268f_autocmd_add(typval_T *argvars, typval_T *rettv)
3269{
3270 autocmd_add_or_delete(argvars, rettv, FALSE);
3271}
3272
3273/*
3274 * autocmd_delete() function
3275 */
3276 void
3277f_autocmd_delete(typval_T *argvars, typval_T *rettv)
3278{
3279 autocmd_add_or_delete(argvars, rettv, TRUE);
3280}
3281
3282/*
3283 * autocmd_get() function
3284 * Returns a List of autocmds.
3285 */
3286 void
3287f_autocmd_get(typval_T *argvars, typval_T *rettv)
3288{
3289 event_T event_arg = NUM_EVENTS;
3290 event_T event;
3291 AutoPat *ap;
3292 AutoCmd *ac;
3293 list_T *event_list;
3294 dict_T *event_dict;
3295 char_u *event_name = NULL;
3296 char_u *pat = NULL;
3297 char_u *name = NULL;
3298 int group = AUGROUP_ALL;
3299
Yegappan Lakshmananca195cc2022-06-14 13:42:26 +01003300 if (rettv_list_alloc(rettv) == FAIL)
3301 return;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003302 if (check_for_opt_dict_arg(argvars, 0) == FAIL)
3303 return;
3304
3305 if (argvars[0].v_type == VAR_DICT)
3306 {
3307 // return only the autocmds in the specified group
3308 if (dict_has_key(argvars[0].vval.v_dict, "group"))
3309 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003310 name = dict_get_string(argvars[0].vval.v_dict, "group", TRUE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003311 if (name == NULL)
3312 return;
3313
3314 if (*name == NUL)
3315 group = AUGROUP_DEFAULT;
3316 else
3317 {
3318 group = au_find_group(name);
3319 if (group == AUGROUP_ERROR)
3320 {
3321 semsg(_(e_no_such_group_str), name);
3322 vim_free(name);
3323 return;
3324 }
3325 }
3326 vim_free(name);
3327 }
3328
3329 // return only the autocmds for the specified event
3330 if (dict_has_key(argvars[0].vval.v_dict, "event"))
3331 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003332 name = dict_get_string(argvars[0].vval.v_dict, "event", TRUE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003333 if (name == NULL)
3334 return;
3335
3336 if (name[0] == '*' && name[1] == NUL)
3337 event_arg = NUM_EVENTS;
3338 else
3339 {
John Marriott78d742a2024-04-02 20:26:01 +02003340 keyvalue_T target;
3341 keyvalue_T *entry;
3342
3343 target.key = 0;
3344 target.value = (char *)name;
3345 target.length = (int)STRLEN(target.value);
3346 entry = (keyvalue_T *)bsearch(&target, &event_tab, ARRAY_LENGTH(event_tab), sizeof(event_tab[0]), cmp_keyvalue_value_ni);
3347 if (entry == NULL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003348 {
3349 semsg(_(e_no_such_event_str), name);
3350 vim_free(name);
3351 return;
3352 }
John Marriott78d742a2024-04-02 20:26:01 +02003353 event_arg = (event_T)entry->key;
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003354 }
3355 vim_free(name);
3356 }
3357
3358 // return only the autocmds for the specified pattern
3359 if (dict_has_key(argvars[0].vval.v_dict, "pattern"))
3360 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003361 pat = dict_get_string(argvars[0].vval.v_dict, "pattern", TRUE);
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003362 if (pat == NULL)
3363 return;
3364 }
3365 }
3366
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003367 event_list = rettv->vval.v_list;
3368
3369 // iterate through all the autocmd events
3370 for (event = (event_T)0; (int)event < NUM_EVENTS;
3371 event = (event_T)((int)event + 1))
3372 {
3373 if (event_arg != NUM_EVENTS && event != event_arg)
3374 continue;
3375
3376 event_name = event_nr2name(event);
3377
3378 // iterate through all the patterns for this autocmd event
3379 FOR_ALL_AUTOCMD_PATTERNS(event, ap)
3380 {
3381 char_u *group_name;
3382
3383 if (group != AUGROUP_ALL && group != ap->group)
3384 continue;
3385
3386 if (pat != NULL && STRCMP(pat, ap->pat) != 0)
3387 continue;
3388
3389 group_name = get_augroup_name(NULL, ap->group);
3390
3391 // iterate through all the commands for this pattern and add one
3392 // item for each cmd.
3393 for (ac = ap->cmds; ac != NULL; ac = ac->next)
3394 {
3395 event_dict = dict_alloc();
Yegappan Lakshmanan00e977c2022-06-01 12:31:53 +01003396 if (event_dict == NULL
3397 || list_append_dict(event_list, event_dict) == FAIL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003398 return;
3399
Yegappan Lakshmanan00e977c2022-06-01 12:31:53 +01003400 if (dict_add_string(event_dict, "event", event_name) == FAIL
3401 || dict_add_string(event_dict, "group",
3402 group_name == NULL ? (char_u *)""
3403 : group_name) == FAIL
3404 || (ap->buflocal_nr != 0
3405 && (dict_add_number(event_dict, "bufnr",
3406 ap->buflocal_nr) == FAIL))
3407 || dict_add_string(event_dict, "pattern",
3408 ap->pat) == FAIL
3409 || dict_add_string(event_dict, "cmd", ac->cmd) == FAIL
3410 || dict_add_bool(event_dict, "once", ac->once) == FAIL
3411 || dict_add_bool(event_dict, "nested",
3412 ac->nested) == FAIL)
Yegappan Lakshmanan1755a912022-05-19 10:31:47 +01003413 return;
3414 }
3415 }
3416 }
3417
3418 vim_free(pat);
3419}
3420
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01003421#endif