robin/laufey

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

bfredlMerge pull request #41212 from bfredl/unmagic8a0eb8f10b

master
35.5 KiB1283 linesraw
1// arglist.c: functions for dealing with the argument list
2
3#include <assert.h>
4#include <stdbool.h>
5#include <stdint.h>
6#include <string.h>
7
8#include "auto/config.h"
9#include "nvim/arglist.h"
10#include "nvim/ascii_defs.h"
11#include "nvim/autocmd.h"
12#include "nvim/buffer.h"
13#include "nvim/buffer_defs.h"
14#include "nvim/charset.h"
15#include "nvim/cmdexpand_defs.h"
16#include "nvim/context.h"
17#include "nvim/errors.h"
18#include "nvim/eval/typval.h"
19#include "nvim/eval/typval_defs.h"
20#include "nvim/eval/window.h"
21#include "nvim/ex_cmds.h"
22#include "nvim/ex_cmds2.h"
23#include "nvim/ex_cmds_defs.h"
24#include "nvim/ex_getln.h"
25#include "nvim/fileio.h"
26#include "nvim/garray.h"
27#include "nvim/garray_defs.h"
28#include "nvim/gettext_defs.h"
29#include "nvim/globals.h"
30#include "nvim/macros_defs.h"
31#include "nvim/mark.h"
32#include "nvim/memline_defs.h"
33#include "nvim/memory.h"
34#include "nvim/message.h"
35#include "nvim/normal.h"
36#include "nvim/option.h"
37#include "nvim/option_vars.h"
38#include "nvim/os/input.h"
39#include "nvim/path.h"
40#include "nvim/pos_defs.h"
41#include "nvim/regexp.h"
42#include "nvim/regexp_defs.h"
43#include "nvim/types_defs.h"
44#include "nvim/undo.h"
45#include "nvim/version.h"
46#include "nvim/vim_defs.h"
47#include "nvim/window.h"
48
49/// State used by the :all command to open all the files in the argument list in
50/// separate windows.
51typedef struct {
52  alist_T *alist;     ///< argument list to be used
53  int had_tab;
54  bool keep_tabs;
55  bool forceit;
56
57  bool use_firstwin;  ///< use first window for arglist
58  uint8_t *opened;    ///< Array of weight for which args are open:
59                      ///<  0: not opened
60                      ///<  1: opened in other tab
61                      ///<  2: opened in curtab
62                      ///<  3: opened in curtab and curwin
63  int opened_len;     ///< length of opened[]
64  win_T *new_curwin;
65  tabpage_T *new_curtab;
66} arg_all_state_T;
67
68#include "arglist.c.generated.h"
69
70static const char e_window_layout_changed_unexpectedly[]
71  = N_("E249: Window layout changed unexpectedly");
72
73enum {
74  AL_SET = 1,
75  AL_ADD = 2,
76  AL_DEL = 3,
77};
78
79/// This flag is set whenever the argument list is being changed and calling a
80/// function that might trigger an autocommand.
81static bool arglist_locked = false;
82
83static int check_arglist_locked(void)
84{
85  if (arglist_locked) {
86    emsg(_(e_cannot_change_arglist_recursively));
87    return FAIL;
88  }
89  return OK;
90}
91
92/// Clear an argument list: free all file names and reset it to zero entries.
93void alist_clear(alist_T *al)
94{
95  if (check_arglist_locked() == FAIL) {
96    return;
97  }
98#define FREE_AENTRY_FNAME(arg) xfree((arg)->ae_fname)
99  GA_DEEP_CLEAR(&al->al_ga, aentry_T, FREE_AENTRY_FNAME);
100}
101
102/// Init an argument list.
103void alist_init(alist_T *al)
104{
105  ga_init(&al->al_ga, (int)sizeof(aentry_T), 5);
106}
107
108/// Remove a reference from an argument list.
109/// Ignored when the argument list is the global one.
110/// If the argument list is no longer used by any window, free it.
111void alist_unlink(alist_T *al)
112{
113  if (al != &global_alist && --al->al_refcount <= 0) {
114    alist_clear(al);
115    xfree(al);
116  }
117}
118
119/// Create a new argument list and use it for the current window.
120void alist_new(void)
121{
122  curwin->w_alist = xmalloc(sizeof(*curwin->w_alist));
123  curwin->w_alist->al_refcount = 1;
124  curwin->w_alist->id = ++max_alist_id;
125  alist_init(curwin->w_alist);
126}
127
128#ifndef UNIX
129
130/// Expand the file names in the global argument list.
131/// If "fnum_list" is not NULL, use "fnum_list[fnum_len]" as a list of buffer
132/// numbers to be re-used.
133void alist_expand(int *fnum_list, int fnum_len)
134{
135  char *save_p_su = p_su;
136
137  char **old_arg_files = xmalloc(sizeof(*old_arg_files) * GARGCOUNT);
138
139  // Don't use 'suffixes' here.  This should work like the shell did the
140  // expansion.  Also, the vimrc file isn't read yet, thus the user
141  // can't set the options.
142  p_su = empty_string_option;
143  for (int i = 0; i < GARGCOUNT; i++) {
144    old_arg_files[i] = xstrdup(GARGLIST[i].ae_fname);
145  }
146  int old_arg_count = GARGCOUNT;
147  char **new_arg_files;
148  int new_arg_file_count;
149  if (expand_wildcards(old_arg_count, old_arg_files,
150                       &new_arg_file_count, &new_arg_files,
151                       EW_FILE|EW_NOTFOUND|EW_ADDSLASH|EW_NOERROR) == OK
152      && new_arg_file_count > 0) {
153    alist_set(&global_alist, new_arg_file_count, new_arg_files,
154              true, fnum_list, fnum_len);
155    FreeWild(old_arg_count, old_arg_files);
156  }
157  p_su = save_p_su;
158}
159#endif
160
161/// Set the argument list for the current window.
162/// Takes over the allocated files[] and the allocated fnames in it.
163void alist_set(alist_T *al, int count, char **files, int use_curbuf, int *fnum_list, int fnum_len)
164{
165  if (check_arglist_locked() == FAIL) {
166    return;
167  }
168
169  alist_clear(al);
170  ga_grow(&al->al_ga, count);
171  {
172    for (int i = 0; i < count; i++) {
173      if (got_int) {
174        // When adding many buffers this can take a long time.  Allow
175        // interrupting here.
176        while (i < count) {
177          xfree(files[i++]);
178        }
179        break;
180      }
181
182      // May set buffer name of a buffer previously used for the
183      // argument list, so that it's re-used by alist_add.
184      if (fnum_list != NULL && i < fnum_len) {
185        arglist_locked = true;
186        buf_set_name(fnum_list[i], files[i]);
187        arglist_locked = false;
188      }
189
190      alist_add(al, files[i], use_curbuf ? 2 : 1);
191      os_breakcheck();
192    }
193    xfree(files);
194  }
195
196  if (al == &global_alist) {
197    arg_had_last = false;
198  }
199}
200
201/// Add file "fname" to argument list "al".
202/// "fname" must have been allocated and "al" must have been checked for room.
203///
204/// May trigger Buf* autocommands
205///
206/// @param set_fnum  1: set buffer number; 2: re-use curbuf
207void alist_add(alist_T *al, char *fname, int set_fnum)
208{
209  win_T *wp = curwin;
210
211  if (fname == NULL) {          // don't add NULL file names
212    return;
213  }
214  if (check_arglist_locked() == FAIL) {
215    return;
216  }
217  arglist_locked = true;
218  wp->w_locked++;
219
220  AARGLIST(al)[al->al_ga.ga_len].ae_fname = fname;
221  if (set_fnum > 0) {
222    AARGLIST(al)[al->al_ga.ga_len].ae_fnum =
223      buflist_add(fname, BLN_LISTED | (set_fnum == 2 ? BLN_CURBUF : 0));
224  }
225  al->al_ga.ga_len++;
226
227  arglist_locked = false;
228  wp->w_locked--;
229}
230
231/// Isolate one argument, taking backticks.
232/// Changes the argument in-place, puts a NUL after it.  Backticks remain.
233///
234/// @return  a pointer to the start of the next argument.
235static char *do_one_arg(char *str)
236{
237  char *p;
238
239  bool inbacktick = false;
240  for (p = str; *str; str++) {
241    // When the backslash is used for escaping the special meaning of a
242    // character we need to keep it until wildcard expansion.
243    if (rem_backslash(str)) {
244      *p++ = *str++;
245      *p++ = *str;
246    } else {
247      // An item ends at a space not in backticks
248      if (!inbacktick && ascii_isspace(*str)) {
249        break;
250      }
251      if (*str == '`') {
252        inbacktick ^= true;
253      }
254      *p++ = *str;
255    }
256  }
257  str = skipwhite(str);
258  *p = NUL;
259
260  return str;
261}
262
263/// Separate the arguments in "str" and return a list of pointers in the
264/// growarray "gap".
265static void get_arglist(garray_T *gap, char *str, bool escaped)
266{
267  ga_init(gap, (int)sizeof(char *), 20);
268  while (*str != NUL) {
269    GA_APPEND(char *, gap, str);
270
271    // If str is escaped, don't handle backslashes or spaces
272    if (!escaped) {
273      return;
274    }
275
276    // Isolate one argument, change it in-place, put a NUL after it.
277    str = do_one_arg(str);
278  }
279}
280
281/// Parse a list of arguments (file names), expand them and return in
282/// "fnames[fcountp]".  When "wig" is true, removes files matching 'wildignore'.
283///
284/// @return  FAIL or OK.
285int get_arglist_exp(char *str, int *fcountp, char ***fnamesp, bool wig)
286{
287  garray_T ga;
288  int i;
289
290  get_arglist(&ga, str, true);
291
292  if (wig) {
293    i = expand_wildcards(ga.ga_len, ga.ga_data,
294                         fcountp, fnamesp, EW_FILE|EW_NOTFOUND|EW_NOTWILD);
295  } else {
296    i = gen_expand_wildcards(ga.ga_len, ga.ga_data,
297                             fcountp, fnamesp, EW_FILE|EW_NOTFOUND|EW_NOTWILD);
298  }
299
300  ga_clear(&ga);
301  return i;
302}
303
304/// Check the validity of the arg_idx for each other window.
305static void alist_check_arg_idx(void)
306{
307  FOR_ALL_TAB_WINDOWS(tp, win) {
308    if (win->w_alist == curwin->w_alist) {
309      check_arg_idx(win);
310    }
311  }
312}
313
314/// Add files[count] to the arglist of the current window after arg "after".
315/// The file names in files[count] must have been allocated and are taken over.
316/// Files[] itself is not taken over.
317///
318/// @param after: where to add: 0 = before first one
319/// @param will_edit  will edit adding argument
320static void alist_add_list(int count, char **files, int after, bool will_edit)
321  FUNC_ATTR_NONNULL_ALL
322{
323  int old_argcount = ARGCOUNT;
324
325  if (check_arglist_locked() != FAIL) {
326    win_T *wp = curwin;
327
328    ga_grow(&ALIST(wp)->al_ga, count);
329    after = MIN(MAX(after, 0), ARGCOUNT);
330    if (after < ARGCOUNT) {
331      memmove(&(ARGLIST[after + count]), &(ARGLIST[after]),
332              (size_t)(ARGCOUNT - after) * sizeof(aentry_T));
333    }
334    arglist_locked = true;
335    wp->w_locked++;
336    for (int i = 0; i < count; i++) {
337      const int flags = BLN_LISTED | (will_edit ? BLN_CURBUF : 0);
338      ARGLIST[after + i].ae_fname = files[i];
339      ARGLIST[after + i].ae_fnum = buflist_add(files[i], flags);
340    }
341    arglist_locked = false;
342    wp->w_locked--;
343    ALIST(wp)->al_ga.ga_len += count;
344    if (old_argcount > 0 && wp->w_arg_idx >= after) {
345      wp->w_arg_idx += count;
346    }
347    return;
348  }
349}
350
351/// Delete the file names in "alist_ga" from the argument list.
352static void arglist_del_files(garray_T *alist_ga)
353{
354  regmatch_T regmatch;
355
356  // Delete the items: use each item as a regexp and find a match in the
357  // argument list.
358  regmatch.rm_ic = p_fic;     // ignore case when 'fileignorecase' is set
359  for (int i = 0; i < alist_ga->ga_len && !got_int; i++) {
360    char *p = ((char **)alist_ga->ga_data)[i];
361    p = file_pat_to_reg_pat(p, NULL, NULL, false);
362    if (p == NULL) {
363      break;
364    }
365    regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
366    if (regmatch.regprog == NULL) {
367      xfree(p);
368      break;
369    }
370
371    bool didone = false;
372    for (int match = 0; match < ARGCOUNT; match++) {
373      if (vim_regexec(&regmatch, alist_name(&ARGLIST[match]), 0)) {
374        didone = true;
375        xfree(ARGLIST[match].ae_fname);
376        memmove(ARGLIST + match, ARGLIST + match + 1,
377                (size_t)(ARGCOUNT - match - 1) * sizeof(aentry_T));
378        ARGCOUNT--;
379        if (curwin->w_arg_idx > match) {
380          curwin->w_arg_idx--;
381        }
382        match--;
383      }
384    }
385
386    vim_regfree(regmatch.regprog);
387    xfree(p);
388    if (!didone) {
389      semsg(_(e_nomatch2), ((char **)alist_ga->ga_data)[i]);
390    }
391  }
392  ga_clear(alist_ga);
393}
394
395/// @param str
396/// @param what
397///         AL_SET: Redefine the argument list to 'str'.
398///         AL_ADD: add files in 'str' to the argument list after "after".
399///         AL_DEL: remove files in 'str' from the argument list.
400/// @param after
401///         0 means before first one
402/// @param will_edit  will edit added argument
403///
404/// @return  FAIL for failure, OK otherwise.
405static int do_arglist(char *str, int what, int after, bool will_edit)
406  FUNC_ATTR_NONNULL_ALL
407{
408  garray_T new_ga;
409  int exp_count;
410  char **exp_files;
411  bool arg_escaped = true;
412
413  if (check_arglist_locked() == FAIL) {
414    return FAIL;
415  }
416
417  // Set default argument for ":argadd" command.
418  if (what == AL_ADD && *str == NUL) {
419    if (curbuf->b_ffname == NULL) {
420      return FAIL;
421    }
422    str = curbuf->b_fname;
423    arg_escaped = false;
424  }
425
426  // Collect all file name arguments in "new_ga".
427  get_arglist(&new_ga, str, arg_escaped);
428
429  if (what == AL_DEL) {
430    arglist_del_files(&new_ga);
431  } else {
432    int i = expand_wildcards(new_ga.ga_len, new_ga.ga_data,
433                             &exp_count, &exp_files,
434                             EW_DIR|EW_FILE|EW_ADDSLASH|EW_NOTFOUND);
435    ga_clear(&new_ga);
436    if (i == FAIL || exp_count == 0) {
437      emsg(_(e_nomatch));
438      return FAIL;
439    }
440
441    if (what == AL_ADD) {
442      alist_add_list(exp_count, exp_files, after, will_edit);
443      xfree(exp_files);
444    } else {
445      assert(what == AL_SET);
446      alist_set(ALIST(curwin), exp_count, exp_files, will_edit, NULL, 0);
447    }
448  }
449
450  alist_check_arg_idx();
451
452  return OK;
453}
454
455/// Redefine the argument list.
456void set_arglist(char *str)
457{
458  do_arglist(str, AL_SET, 0, true);
459}
460
461/// @return  true if window "win" is editing the file at the current argument
462///          index.
463bool editing_arg_idx(win_T *win)
464{
465  return !(win->w_arg_idx >= WARGCOUNT(win)
466           || (win->w_buffer->b_fnum
467               != WARGLIST(win)[win->w_arg_idx].ae_fnum
468               && (win->w_buffer->b_ffname == NULL
469                   || !path_equal(alist_name(&WARGLIST(win)[win->w_arg_idx]),
470                                  win->w_buffer->b_ffname, kPathCmpExpand | kPathCmpFull))));
471}
472
473/// Check if window "win" is editing the w_arg_idx file in its argument list.
474void check_arg_idx(win_T *win)
475{
476  if (WARGCOUNT(win) > 1 && !editing_arg_idx(win)) {
477    // We are not editing the current entry in the argument list.
478    // Set "arg_had_last" if we are editing the last one.
479    win->w_arg_idx_invalid = true;
480    if (win->w_arg_idx != WARGCOUNT(win) - 1
481        && arg_had_last == false
482        && ALIST(win) == &global_alist
483        && GARGCOUNT > 0
484        && win->w_arg_idx < GARGCOUNT
485        && (win->w_buffer->b_fnum == GARGLIST[GARGCOUNT - 1].ae_fnum
486            || (win->w_buffer->b_ffname != NULL
487                && path_equal(alist_name(&GARGLIST[GARGCOUNT - 1]),
488                              win->w_buffer->b_ffname, kPathCmpExpand | kPathCmpFull)))) {
489      arg_had_last = true;
490    }
491  } else {
492    // We are editing the current entry in the argument list.
493    // Set "arg_had_last" if it's also the last one
494    win->w_arg_idx_invalid = false;
495    if (win->w_arg_idx == WARGCOUNT(win) - 1 && win->w_alist == &global_alist) {
496      arg_had_last = true;
497    }
498  }
499}
500
501/// ":args", ":arglocal" and ":argglobal".
502void ex_args(exarg_T *eap)
503{
504  if (eap->cmdidx != CMD_args) {
505    if (check_arglist_locked() == FAIL) {
506      return;
507    }
508    alist_unlink(ALIST(curwin));
509    if (eap->cmdidx == CMD_argglobal) {
510      ALIST(curwin) = &global_alist;
511    } else {     // eap->cmdidx == CMD_arglocal
512      alist_new();
513    }
514  }
515
516  // ":args file ..": define new argument list, handle like ":next"
517  // Also for ":argslocal file .." and ":argsglobal file ..".
518  if (*eap->arg != NUL) {
519    if (check_arglist_locked() == FAIL) {
520      return;
521    }
522    ex_next(eap);
523    return;
524  }
525
526  // ":args": list arguments.
527  if (eap->cmdidx == CMD_args) {
528    if (ARGCOUNT <= 0) {
529      return;  // empty argument list
530    }
531
532    char **items = xmalloc(sizeof(char *) * (size_t)ARGCOUNT);
533
534    // Overwrite the command, for a short list there is no scrolling
535    // required and no wait_return().
536    gotocmdline(true);
537
538    for (int i = 0; i < ARGCOUNT; i++) {
539      items[i] = alist_name(&ARGLIST[i]);
540    }
541    list_in_columns(items, ARGCOUNT, curwin->w_arg_idx);
542    xfree(items);
543
544    return;
545  }
546
547  // ":argslocal": make a local copy of the global argument list.
548  if (eap->cmdidx == CMD_arglocal) {
549    garray_T *gap = &curwin->w_alist->al_ga;
550
551    ga_grow(gap, GARGCOUNT);
552
553    for (int i = 0; i < GARGCOUNT; i++) {
554      if (GARGLIST[i].ae_fname != NULL) {
555        AARGLIST(curwin->w_alist)[gap->ga_len].ae_fname = xstrdup(GARGLIST[i].ae_fname);
556        AARGLIST(curwin->w_alist)[gap->ga_len].ae_fnum = GARGLIST[i].ae_fnum;
557        gap->ga_len++;
558      }
559    }
560  }
561}
562
563/// ":previous", ":sprevious", ":Next" and ":sNext".
564void ex_previous(exarg_T *eap)
565{
566  // If past the last one already, go to the last one.
567  if (curwin->w_arg_idx - (int)eap->line2 >= ARGCOUNT) {
568    do_argfile(eap, ARGCOUNT - 1);
569  } else {
570    do_argfile(eap, curwin->w_arg_idx - (int)eap->line2);
571  }
572}
573
574/// ":rewind", ":first", ":sfirst" and ":srewind".
575void ex_rewind(exarg_T *eap)
576{
577  do_argfile(eap, 0);
578}
579
580/// ":last" and ":slast".
581void ex_last(exarg_T *eap)
582{
583  do_argfile(eap, ARGCOUNT - 1);
584}
585
586/// ":argument" and ":sargument".
587void ex_argument(exarg_T *eap)
588{
589  int i;
590
591  if (eap->addr_count > 0) {
592    i = (int)eap->line2 - 1;
593  } else {
594    i = curwin->w_arg_idx;
595  }
596  do_argfile(eap, i);
597}
598
599/// Edit file "argn" of the argument lists.
600void do_argfile(exarg_T *eap, int argn)
601{
602  bool is_split_cmd = *eap->cmd == 's';
603
604  int old_arg_idx = curwin->w_arg_idx;
605
606  if (argn < 0 || argn >= ARGCOUNT) {
607    if (ARGCOUNT <= 1) {
608      emsg(_("E163: There is only one file to edit"));
609    } else if (argn < 0) {
610      emsg(_("E164: Cannot go before first file"));
611    } else {
612      emsg(_("E165: Cannot go beyond last file"));
613    }
614
615    return;
616  }
617
618  if (!is_split_cmd
619      && (&ARGLIST[argn])->ae_fnum != curbuf->b_fnum
620      && !check_can_set_curbuf_forceit(eap->forceit)) {
621    return;
622  }
623
624  setpcmark();
625
626  // split window or create new tab page first
627  if (is_split_cmd || cmdmod.cmod_tab != 0) {
628    if (win_split(0, 0) == FAIL) {
629      return;
630    }
631    RESET_BINDING(curwin);
632  } else {
633    // if 'hidden' set, only check for changed file when re-editing
634    // the same buffer
635    int other = true;
636    if (buf_hide(curbuf)) {
637      char *p = fix_fname(alist_name(&ARGLIST[argn]));
638      other = otherfile(p);
639      xfree(p);
640    }
641    if ((!buf_hide(curbuf) || !other)
642        && check_changed(curbuf, CCGD_AW
643                         | (other ? 0 : CCGD_MULTWIN)
644                         | (eap->forceit ? CCGD_FORCEIT : 0)
645                         | CCGD_EXCMD)) {
646      return;
647    }
648  }
649
650  curwin->w_arg_idx = argn;
651  if (argn == ARGCOUNT - 1 && curwin->w_alist == &global_alist) {
652    arg_had_last = true;
653  }
654
655  // Edit the file; always use the last known line number.
656  // When it fails (e.g. Abort for already edited file) restore the
657  // argument index.
658  if (do_ecmd(0, alist_name(&ARGLIST[curwin->w_arg_idx]), NULL,
659              eap, ECMD_LAST,
660              (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
661              + (eap->forceit ? ECMD_FORCEIT : 0), curwin) == FAIL) {
662    curwin->w_arg_idx = old_arg_idx;
663  } else if (eap->cmdidx != CMD_argdo) {
664    // like Vi: set the mark where the cursor is in the file.
665    setmark('\'');
666  }
667}
668
669/// ":next", and commands that behave like it.
670void ex_next(exarg_T *eap)
671{
672  // check for changed buffer now, if this fails the argument list is not
673  // redefined.
674  if (buf_hide(curbuf)
675      || eap->cmdidx == CMD_snext
676      || !check_changed(curbuf, CCGD_AW
677                        | (eap->forceit ? CCGD_FORCEIT : 0)
678                        | CCGD_EXCMD)) {
679    int i;
680    if (*eap->arg != NUL) {                 // redefine file list
681      if (do_arglist(eap->arg, AL_SET, 0, true) == FAIL) {
682        return;
683      }
684      i = 0;
685    } else {
686      i = curwin->w_arg_idx + (int)eap->line2;
687    }
688    do_argfile(eap, i);
689  }
690}
691
692/// ":argdedupe"
693void ex_argdedupe(exarg_T *eap FUNC_ATTR_UNUSED)
694{
695  for (int i = 0; i < ARGCOUNT; i++) {
696    // Expand each argument to a full path to catch different paths leading
697    // to the same file.
698    char *firstFullname = FullName_save(ARGLIST[i].ae_fname, false);
699
700    for (int j = i + 1; j < ARGCOUNT; j++) {
701      char *secondFullname = FullName_save(ARGLIST[j].ae_fname, false);
702      bool areNamesDuplicate = path_equal(firstFullname, secondFullname, kPathCmpLiteral);
703      xfree(secondFullname);
704
705      if (areNamesDuplicate) {
706        // remove one duplicate argument
707        xfree(ARGLIST[j].ae_fname);
708        memmove(ARGLIST + j, ARGLIST + j + 1,
709                (size_t)(ARGCOUNT - j - 1) * sizeof(aentry_T));
710        ARGCOUNT--;
711
712        if (curwin->w_arg_idx == j) {
713          curwin->w_arg_idx = i;
714        } else if (curwin->w_arg_idx > j) {
715          curwin->w_arg_idx--;
716        }
717
718        j--;
719      }
720    }
721
722    xfree(firstFullname);
723  }
724}
725
726/// ":argedit"
727void ex_argedit(exarg_T *eap)
728{
729  int i = eap->addr_count ? (int)eap->line2 : curwin->w_arg_idx + 1;
730  // Whether curbuf will be reused, curbuf->b_ffname will be set.
731  bool curbuf_is_reusable = curbuf_reusable();
732
733  if (do_arglist(eap->arg, AL_ADD, i, true) == FAIL) {
734    return;
735  }
736  maketitle();
737
738  if (curwin->w_arg_idx == 0
739      && (curbuf->b_ml.ml_flags & ML_EMPTY)
740      && (curbuf->b_ffname == NULL || curbuf_is_reusable)) {
741    i = 0;
742  }
743  // Edit the argument.
744  if (i < ARGCOUNT) {
745    do_argfile(eap, i);
746  }
747}
748
749/// ":argadd"
750void ex_argadd(exarg_T *eap)
751{
752  do_arglist(eap->arg, AL_ADD,
753             eap->addr_count > 0 ? (int)eap->line2 : curwin->w_arg_idx + 1,
754             false);
755  maketitle();
756}
757
758/// ":argdelete"
759void ex_argdelete(exarg_T *eap)
760{
761  if (check_arglist_locked() == FAIL) {
762    return;
763  }
764
765  if (eap->addr_count > 0 || *eap->arg == NUL) {
766    // ":argdel" works like ":.argdel"
767    if (eap->addr_count == 0) {
768      if (curwin->w_arg_idx >= ARGCOUNT) {
769        emsg(_("E610: No argument to delete"));
770        return;
771      }
772      eap->line1 = eap->line2 = curwin->w_arg_idx + 1;
773    } else if (eap->line2 > ARGCOUNT) {
774      // ":1,4argdel": Delete all arguments in the range.
775      eap->line2 = ARGCOUNT;
776    }
777    linenr_T n = eap->line2 - eap->line1 + 1;
778    if (*eap->arg != NUL) {
779      // Can't have both a range and an argument.
780      emsg(_(e_invarg));
781      return;
782    }
783    if (n <= 0) {
784      // Don't give an error for ":%argdel" if the list is empty.
785      if (eap->line1 != 1 || eap->line2 != 0) {
786        emsg(_(e_invrange));
787      }
788      return;
789    }
790
791    for (linenr_T i = eap->line1; i <= eap->line2; i++) {
792      xfree(ARGLIST[i - 1].ae_fname);
793    }
794    memmove(ARGLIST + eap->line1 - 1, ARGLIST + eap->line2,
795            (size_t)(ARGCOUNT - eap->line2) * sizeof(aentry_T));
796    ARGCOUNT -= n;
797    if (curwin->w_arg_idx >= eap->line2) {
798      curwin->w_arg_idx -= n;
799    } else if (curwin->w_arg_idx > eap->line1) {
800      curwin->w_arg_idx = eap->line1;
801    }
802  } else {
803    do_arglist(eap->arg, AL_DEL, 0, false);
804  }
805
806  if (ARGCOUNT == 0) {
807    curwin->w_arg_idx = 0;
808  } else if (curwin->w_arg_idx >= ARGCOUNT) {
809    curwin->w_arg_idx = ARGCOUNT - 1;
810  }
811
812  maketitle();
813}
814
815/// Function given to ExpandGeneric() to obtain the possible arguments of the
816/// argedit and argdelete commands.
817char *get_arglist_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
818{
819  if (idx >= ARGCOUNT) {
820    return NULL;
821  }
822  return alist_name(&ARGLIST[idx]);
823}
824
825/// Get the file name for an argument list entry.
826char *alist_name(aentry_T *aep)
827{
828  // Use the name from the associated buffer if it exists.
829  buf_T *bp = buflist_findnr(aep->ae_fnum);
830  if (bp == NULL || bp->b_fname == NULL) {
831    return aep->ae_fname;
832  }
833  return bp->b_fname;
834}
835
836/// Close all the windows containing files which are not in the argument list.
837/// Used by the ":all" command.
838static void arg_all_close_unused_windows(arg_all_state_T *aall)
839{
840  win_T *old_curwin = curwin;
841  tabpage_T *old_curtab = curtab;
842
843  if (aall->had_tab > 0) {
844    goto_tabpage_tp(first_tabpage, true, true);
845  }
846
847  // moving tabpages around in an autocommand may cause an endless loop
848  tabpage_move_disallowed++;
849  while (true) {
850    win_T *wpnext = NULL;
851    tabpage_T *tpnext = curtab->tp_next;
852    // Try to close floating windows first
853    for (win_T *wp = lastwin->w_floating ? lastwin : firstwin; wp != NULL; wp = wpnext) {
854      int i;
855      wpnext = wp->w_floating
856               ? wp->w_prev->w_floating ? wp->w_prev : firstwin
857               : (wp->w_next == NULL || wp->w_next->w_floating) ? NULL : wp->w_next;
858      buf_T *buf = wp->w_buffer;
859      if (buf->b_ffname == NULL
860          || (!aall->keep_tabs
861              && (buf->b_nwindows > 1 || wp->w_width != Columns
862                  || (wp->w_floating && !is_ctx_win(wp))))) {
863        i = aall->opened_len;
864      } else {
865        // check if the buffer in this window is in the arglist
866        for (i = 0; i < aall->opened_len; i++) {
867          if (i < aall->alist->al_ga.ga_len
868              && (AARGLIST(aall->alist)[i].ae_fnum == buf->b_fnum
869                  || path_equal(alist_name(&AARGLIST(aall->alist)[i]),
870                                buf->b_ffname, kPathCmpExpand | kPathCmpFull))) {
871            int weight = 1;
872
873            if (old_curtab == curtab) {
874              weight++;
875              if (old_curwin == wp) {
876                weight++;
877              }
878            }
879
880            if (weight > (int)aall->opened[i]) {
881              aall->opened[i] = (uint8_t)weight;
882              if (i == 0) {
883                if (aall->new_curwin != NULL) {
884                  aall->new_curwin->w_arg_idx = aall->opened_len;
885                }
886                aall->new_curwin = wp;
887                aall->new_curtab = curtab;
888              }
889            } else if (aall->keep_tabs) {
890              i = aall->opened_len;
891            }
892
893            if (wp->w_alist != aall->alist) {
894              // Use the current argument list for all windows
895              // containing a file from it.
896              alist_unlink(wp->w_alist);
897              wp->w_alist = aall->alist;
898              wp->w_alist->al_refcount++;
899            }
900            break;
901          }
902        }
903      }
904      wp->w_arg_idx = i;
905
906      if (i == aall->opened_len && !aall->keep_tabs) {  // close this window
907        if (buf_hide(buf) || aall->forceit || buf->b_nwindows > 1
908            || !bufIsChanged(buf)) {
909          // If the buffer was changed, and we would like to hide it, try autowriting.
910          if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) {
911            bufref_T bufref;
912            set_bufref(&bufref, buf);
913            autowrite(buf, false);
914            // Check if autocommands removed the window.
915            if (!win_valid(wp) || !bufref_valid(&bufref)) {
916              wpnext = lastwin->w_floating ? lastwin : firstwin;  // Start all over...
917              continue;
918            }
919          }
920          // don't close last window
921          if (ONE_WINDOW
922              && (first_tabpage->tp_next == NULL || !aall->had_tab)) {
923            aall->use_firstwin = true;
924          } else {
925            win_close(wp, !buf_hide(buf) && !bufIsChanged(buf), false);
926            // check if autocommands removed the next window
927            if (!win_valid(wpnext)) {
928              // start all over...
929              wpnext = lastwin->w_floating ? lastwin : firstwin;
930            }
931          }
932        }
933      }
934    }
935
936    // Without the ":tab" modifier only do the current tab page.
937    if (aall->had_tab == 0 || tpnext == NULL) {
938      break;
939    }
940
941    // check if autocommands removed the next tab page
942    if (!valid_tabpage(tpnext)) {
943      tpnext = first_tabpage;           // start all over...
944    }
945    goto_tabpage_tp(tpnext, true, true);
946  }
947  tabpage_move_disallowed--;
948}
949
950/// Open up to "count" windows for the files in the argument list "aall->alist".
951static void arg_all_open_windows(arg_all_state_T *aall, int count)
952{
953  bool tab_drop_empty_window = false;
954
955  // ":tab drop file" should re-use an empty window to avoid "--remote-tab"
956  // leaving an empty tab page when executed locally.
957  if (aall->keep_tabs && buf_is_empty(curbuf) && curbuf->b_nwindows == 1
958      && curbuf->b_ffname == NULL && !curbuf->b_changed) {
959    aall->use_firstwin = true;
960    tab_drop_empty_window = true;
961  }
962
963  int split_ret = OK;
964
965  for (int i = 0; i < count && !got_int; i++) {
966    if (aall->alist == &global_alist && i == global_alist.al_ga.ga_len - 1) {
967      arg_had_last = true;
968    }
969    if (aall->opened[i] > 0) {
970      // Move the already present window to below the current window
971      if (curwin->w_arg_idx != i) {
972        FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
973          if (wp->w_arg_idx == i) {
974            if (aall->keep_tabs) {
975              aall->new_curwin = wp;
976              aall->new_curtab = curtab;
977            } else if (wp->w_floating) {
978              break;
979            } else if (wp->w_frame->fr_parent != curwin->w_frame->fr_parent) {
980              emsg(_(e_window_layout_changed_unexpectedly));
981              i = count;
982              break;
983            } else {
984              win_move_after(wp, curwin);
985            }
986            break;
987          }
988        }
989      }
990    } else if (split_ret == OK) {
991      // trigger events for tab drop
992      if (tab_drop_empty_window && i == count - 1) {
993        autocmd_no_enter--;
994      }
995      if (!aall->use_firstwin) {        // split current window
996        bool p_ea_save = p_ea;
997        p_ea = true;                    // use space from all windows
998        split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
999        p_ea = p_ea_save;
1000        if (split_ret == FAIL) {
1001          continue;
1002        }
1003      } else {      // first window: do autocmd for leaving this buffer
1004        autocmd_no_leave--;
1005      }
1006
1007      // edit file "i"
1008      curwin->w_arg_idx = i;
1009      if (i == 0) {
1010        aall->new_curwin = curwin;
1011        aall->new_curtab = curtab;
1012      }
1013      do_ecmd(0, alist_name(&AARGLIST(aall->alist)[i]), NULL, NULL, ECMD_ONE,
1014              ((buf_hide(curwin->w_buffer)
1015                || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0) + ECMD_OLDBUF,
1016              curwin);
1017      if (tab_drop_empty_window && i == count - 1) {
1018        autocmd_no_enter++;
1019      }
1020      if (aall->use_firstwin) {
1021        autocmd_no_leave++;
1022      }
1023      aall->use_firstwin = false;
1024    }
1025    os_breakcheck();
1026
1027    // When ":tab" was used open a new tab for a new window repeatedly.
1028    if (aall->had_tab > 0 && tabpage_index(NULL) <= p_tpm) {
1029      cmdmod.cmod_tab = 9999;
1030    }
1031  }
1032}
1033
1034/// do_arg_all(): Open up to 'count' windows, one for each argument.
1035///
1036/// @param forceit    hide buffers in current windows
1037/// @param keep_tabs  keep current tabs, for ":tab drop file"
1038static void do_arg_all(int count, int forceit, int keep_tabs)
1039{
1040  win_T *last_curwin;
1041  tabpage_T *last_curtab;
1042  bool prev_arglist_locked = arglist_locked;
1043
1044  assert(firstwin != NULL);  // satisfy coverity
1045
1046  if (ARGCOUNT <= 0) {
1047    // Don't give an error message.  We don't want it when the ":all"
1048    // command is in the .vimrc.
1049    return;
1050  }
1051  setpcmark();
1052
1053  arg_all_state_T aall = {
1054    .use_firstwin = false,
1055    .had_tab = cmdmod.cmod_tab,
1056    .new_curwin = NULL,
1057    .new_curtab = NULL,
1058    .forceit = forceit,
1059    .keep_tabs = keep_tabs,
1060    .opened_len = ARGCOUNT,
1061    .opened = xcalloc((size_t)ARGCOUNT, 1),
1062  };
1063
1064  // Autocommands may do anything to the argument list.  Make sure it's not
1065  // freed while we are working here by "locking" it.  We still have to
1066  // watch out for its size to be changed.
1067  aall.alist = curwin->w_alist;
1068  aall.alist->al_refcount++;
1069  arglist_locked = true;
1070
1071  tabpage_T *const new_lu_tp = curtab;
1072
1073  // Stop Visual mode, the cursor and `Visual.start` may very well be invalid after
1074  // switching to another buffer.
1075  reset_VIsual_and_resel();
1076
1077  // Try closing all windows that are not in the argument list.
1078  // Also close windows that are not full width;
1079  // When 'hidden' or "forceit" set the buffer becomes hidden.
1080  // Windows that have a changed buffer and can't be hidden won't be closed.
1081  // When the ":tab" modifier was used do this for all tab pages.
1082  arg_all_close_unused_windows(&aall);
1083
1084  // Open a window for files in the argument list that don't have one.
1085  // ARGCOUNT may change while doing this, because of autocommands.
1086  if (count > aall.opened_len || count <= 0) {
1087    count = aall.opened_len;
1088  }
1089
1090  // Don't execute Win/Buf Enter/Leave autocommands here.
1091  autocmd_no_enter++;
1092  autocmd_no_leave++;
1093  last_curwin = curwin;
1094  last_curtab = curtab;
1095  // lastwin may be ctx_win
1096  win_enter(lastwin_nofloating(NULL), false);
1097
1098  // Open up to "count" windows.
1099  arg_all_open_windows(&aall, count);
1100
1101  // Remove the "lock" on the argument list.
1102  alist_unlink(aall.alist);
1103  arglist_locked = prev_arglist_locked;
1104
1105  autocmd_no_enter--;
1106
1107  // restore last referenced tabpage's curwin
1108  if (last_curtab != aall.new_curtab) {
1109    if (valid_tabpage(last_curtab)) {
1110      goto_tabpage_tp(last_curtab, true, true);
1111    }
1112    if (win_valid(last_curwin)) {
1113      win_enter(last_curwin, false);
1114    }
1115  }
1116  // to window with first arg
1117  if (valid_tabpage(aall.new_curtab)) {
1118    goto_tabpage_tp(aall.new_curtab, true, true);
1119  }
1120
1121  // Now set the last used tabpage to where we started.
1122  if (valid_tabpage(new_lu_tp)) {
1123    lastused_tabpage = new_lu_tp;
1124  }
1125
1126  if (win_valid(aall.new_curwin)) {
1127    win_enter(aall.new_curwin, false);
1128  }
1129
1130  autocmd_no_leave--;
1131  xfree(aall.opened);
1132}
1133
1134/// ":all" and ":sall".
1135/// Also used for ":tab drop file ..." after setting the argument list.
1136void ex_all(exarg_T *eap)
1137{
1138  if (eap->addr_count == 0) {
1139    eap->line2 = 9999;
1140  }
1141  do_arg_all((int)eap->line2, eap->forceit, eap->cmdidx == CMD_drop);
1142}
1143
1144/// Concatenate all files in the argument list, separated by spaces, and return
1145/// it in one allocated string.
1146/// Spaces and backslashes in the file names are escaped with a backslash.
1147char *arg_all(void)
1148{
1149  char *retval = NULL;
1150
1151  // Do this loop two times:
1152  // first time: compute the total length
1153  // second time: concatenate the names
1154  while (true) {
1155    int len = 0;
1156    for (int idx = 0; idx < ARGCOUNT; idx++) {
1157      char *p = alist_name(&ARGLIST[idx]);
1158      if (p == NULL) {
1159        continue;
1160      }
1161      if (len > 0) {
1162        // insert a space in between names
1163        if (retval != NULL) {
1164          retval[len] = ' ';
1165        }
1166        len++;
1167      }
1168      for (; *p != NUL; p++) {
1169        if (*p == ' '
1170#ifndef BACKSLASH_IN_FILENAME
1171            || *p == '\\'
1172#endif
1173            || *p == '`') {
1174          // insert a backslash
1175          if (retval != NULL) {
1176            retval[len] = '\\';
1177          }
1178          len++;
1179        }
1180        if (retval != NULL) {
1181          retval[len] = *p;
1182        }
1183        len++;
1184      }
1185    }
1186
1187    // second time: break here
1188    if (retval != NULL) {
1189      retval[len] = NUL;
1190      break;
1191    }
1192
1193    // allocate memory
1194    retval = xmalloc((size_t)len + 1);
1195  }
1196
1197  return retval;
1198}
1199
1200/// "argc([window id])" function
1201void f_argc(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1202{
1203  if (argvars[0].v_type == VAR_UNKNOWN) {
1204    // use the current window
1205    rettv->vval.v_number = ARGCOUNT;
1206  } else if (argvars[0].v_type == VAR_NUMBER
1207             && tv_get_number(&argvars[0]) == -1) {
1208    // use the global argument list
1209    rettv->vval.v_number = GARGCOUNT;
1210  } else {
1211    // use the argument list of the specified window
1212    win_T *wp = find_win_by_nr_or_id(&argvars[0]);
1213    if (wp != NULL) {
1214      rettv->vval.v_number = WARGCOUNT(wp);
1215    } else {
1216      rettv->vval.v_number = -1;
1217    }
1218  }
1219}
1220
1221/// "argidx()" function
1222void f_argidx(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1223{
1224  rettv->vval.v_number = curwin->w_arg_idx;
1225}
1226
1227/// "arglistid()" function
1228void f_arglistid(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1229{
1230  rettv->vval.v_number = -1;
1231  win_T *wp = find_tabwin(&argvars[0], &argvars[1]);
1232  if (wp != NULL) {
1233    rettv->vval.v_number = wp->w_alist->id;
1234  }
1235}
1236
1237/// Get the argument list for a given window
1238static void get_arglist_as_rettv(aentry_T *arglist, int argcount, typval_T *rettv)
1239{
1240  tv_list_alloc_ret(rettv, argcount);
1241  if (arglist != NULL) {
1242    for (int idx = 0; idx < argcount; idx++) {
1243      tv_list_append_string(rettv->vval.v_list, alist_name(&arglist[idx]), -1);
1244    }
1245  }
1246}
1247
1248/// "argv(nr)" function
1249void f_argv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1250{
1251  aentry_T *arglist = NULL;
1252  int argcount = -1;
1253
1254  if (argvars[0].v_type == VAR_UNKNOWN) {
1255    get_arglist_as_rettv(ARGLIST, ARGCOUNT, rettv);
1256    return;
1257  }
1258
1259  if (argvars[1].v_type == VAR_UNKNOWN) {
1260    arglist = ARGLIST;
1261    argcount = ARGCOUNT;
1262  } else if (argvars[1].v_type == VAR_NUMBER
1263             && tv_get_number(&argvars[1]) == -1) {
1264    arglist = GARGLIST;
1265    argcount = GARGCOUNT;
1266  } else {
1267    win_T *wp = find_win_by_nr_or_id(&argvars[1]);
1268    if (wp != NULL) {
1269      // Use the argument list of the specified window
1270      arglist = WARGLIST(wp);
1271      argcount = WARGCOUNT(wp);
1272    }
1273  }
1274
1275  rettv->v_type = VAR_STRING;
1276  rettv->vval.v_string = NULL;
1277  int idx = (int)tv_get_number_chk(&argvars[0], NULL);
1278  if (arglist != NULL && idx >= 0 && idx < argcount) {
1279    rettv->vval.v_string = xstrdup(alist_name(&arglist[idx]));
1280  } else if (idx == -1) {
1281    get_arglist_as_rettv(arglist, argcount, rettv);
1282  }
1283}