robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
71.1 KiB2357 linesraw
1// Make sure extern symbols are exported on Windows
2#ifdef WIN32
3# define EXTERN __declspec(dllexport)
4#else
5# define EXTERN
6#endif
7#include <assert.h>
8#include <limits.h>
9#include <stdbool.h>
10#include <stddef.h>
11#include <stdint.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#ifdef ENABLE_ASAN_UBSAN
16# include <sanitizer/asan_interface.h>
17# ifndef MSWIN
18#  include <sanitizer/ubsan_interface.h>
19# endif
20#endif
21
22#include "auto/config.h"  // IWYU pragma: keep
23#include "klib/kvec.h"
24#include "nvim/api/extmark.h"
25#include "nvim/api/private/defs.h"
26#include "nvim/api/private/helpers.h"
27#include "nvim/api/ui.h"
28#include "nvim/arglist.h"
29#include "nvim/ascii_defs.h"
30#include "nvim/autocmd.h"
31#include "nvim/autocmd_defs.h"
32#include "nvim/buffer.h"
33#include "nvim/buffer_defs.h"
34#include "nvim/channel.h"
35#include "nvim/channel_defs.h"
36#include "nvim/context.h"
37#include "nvim/decoration.h"
38#include "nvim/decoration_provider.h"
39#include "nvim/diff.h"
40#include "nvim/drawline.h"
41#include "nvim/drawscreen.h"
42#include "nvim/errors.h"
43#include "nvim/eval.h"
44#include "nvim/eval/typval.h"
45#include "nvim/eval/typval_defs.h"
46#include "nvim/eval/userfunc.h"
47#include "nvim/eval/vars.h"
48#include "nvim/event/loop.h"
49#include "nvim/event/multiqueue.h"
50#include "nvim/event/proc.h"
51#include "nvim/event/socket.h"
52#include "nvim/event/stream.h"
53#include "nvim/ex_cmds.h"
54#include "nvim/ex_docmd.h"
55#include "nvim/ex_getln.h"
56#include "nvim/extmark.h"
57#include "nvim/fileio.h"
58#include "nvim/fold.h"
59#include "nvim/garray.h"
60#include "nvim/gettext_defs.h"
61#include "nvim/globals.h"
62#include "nvim/grid.h"
63#include "nvim/hashtab.h"
64#include "nvim/highlight.h"
65#include "nvim/highlight_group.h"
66#include "nvim/input.h"
67#include "nvim/keycodes.h"
68#include "nvim/log.h"
69#include "nvim/lua/executor.h"
70#include "nvim/lua/secure.h"
71#include "nvim/lua/treesitter.h"
72#include "nvim/macros_defs.h"
73#include "nvim/main.h"
74#include "nvim/mapping.h"
75#include "nvim/mark.h"
76#include "nvim/mcursor.h"
77#include "nvim/memline.h"
78#include "nvim/memory.h"
79#include "nvim/message.h"
80#include "nvim/mouse.h"
81#include "nvim/move.h"
82#include "nvim/msgpack_rpc/channel.h"
83#include "nvim/msgpack_rpc/server.h"
84#include "nvim/normal.h"
85#include "nvim/ops.h"
86#include "nvim/option.h"
87#include "nvim/option_defs.h"
88#include "nvim/option_vars.h"
89#include "nvim/os/fs.h"
90#include "nvim/os/input.h"
91#include "nvim/os/lang.h"
92#include "nvim/os/os.h"
93#include "nvim/os/os_defs.h"
94#include "nvim/os/signal.h"
95#include "nvim/os/stdpaths_defs.h"
96#include "nvim/path.h"
97#include "nvim/popupmenu.h"
98#include "nvim/profile.h"
99#include "nvim/quickfix.h"
100#include "nvim/register.h"
101#include "nvim/runtime.h"
102#include "nvim/runtime_defs.h"
103#include "nvim/shada.h"
104#include "nvim/statusline.h"
105#include "nvim/strings.h"
106#include "nvim/syntax.h"
107#include "nvim/terminal.h"
108#include "nvim/types_defs.h"
109#include "nvim/ui.h"
110#include "nvim/ui_client.h"
111#include "nvim/ui_compositor.h"
112#include "nvim/version.h"
113#include "nvim/vim_defs.h"
114#include "nvim/window.h"
115#include "nvim/winfloat.h"
116
117#ifdef MSWIN
118# include "nvim/os/os_win_console.h"
119# ifndef _UCRT
120#  error UCRT is the only supported C runtime on windows
121# endif
122#endif
123
124#if defined(MSWIN) && !defined(MAKE_LIB)
125# include "nvim/mbyte.h"
126#endif
127
128// values for "window_layout"
129enum {
130  WIN_HOR = 1,   // "-o" horizontally split windows
131  WIN_VER = 2,   // "-O" vertically split windows
132  WIN_TABS = 3,  // "-p" windows on tab pages
133};
134
135// Values for edit_type.
136enum {
137  EDIT_NONE = 0,   // no edit type yet
138  EDIT_FILE = 1,   // file name argument[s] given, use argument list
139  EDIT_STDIN = 2,  // read file from stdin
140  EDIT_TAG = 3,    // tag name argument given, use tagname
141  EDIT_QF = 4,     // start in quickfix mode
142};
143
144#include "main.c.generated.h"
145
146Loop main_loop;
147
148static char *argv0 = NULL;
149
150// Error messages
151static const char *err_arg_missing = N_("Argument missing after");
152static const char *err_opt_garbage = N_("Garbage after option argument");
153static const char *err_opt_unknown = N_("Unknown option argument");
154static const char *err_too_many_args = N_("Too many edit arguments");
155static const char *err_extra_cmd =
156  N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments");
157
158void event_init(void)
159{
160  loop_init(&main_loop, NULL);
161  env_init();
162  resize_events = multiqueue_new_child(main_loop.events);
163
164  autocmd_init();
165  signal_init();
166  // mspgack-rpc initialization
167  channel_init();
168  terminal_init();
169  ui_init();
170  TIME_MSG("event init");
171}
172
173/// @returns false if main_loop could not be closed gracefully
174static bool event_teardown(void)
175{
176  if (!main_loop.events) {
177    return true;
178  }
179
180  multiqueue_process_events(main_loop.events);
181  loop_poll_events(&main_loop, 0);  // Drain thread_events, fast_events.
182  server_teardown();
183  channel_teardown();
184  proc_teardown(&main_loop);
185  timer_teardown();
186  signal_teardown();
187  terminal_teardown();
188
189  return loop_close(&main_loop, true);
190}
191
192/// Performs early initialization.
193static void early_init(mparm_T *paramp)
194{
195  os_hint_priority();
196  estack_init();
197  cmdline_init();
198  eval_init();          // init global variables
199  set_vim_var_nr(VV_STARTTIME, (varnumber_T)os_realtime());
200  init_path(argv0 ? argv0 : "nvim");
201  init_normal_cmds();   // Init the table of Normal mode commands.
202  runtime_init();
203  highlight_init();
204  mc_init();
205
206#ifdef MSWIN
207  OSVERSIONINFO ovi;
208  ovi.dwOSVersionInfoSize = sizeof(ovi);
209  // Disable warning about GetVersionExA being deprecated. There doesn't seem to be a convenient
210  // replacement that doesn't add a ton of extra code as of writing this.
211# ifdef _MSC_VER
212#  pragma warning(suppress : 4996)
213  GetVersionEx(&ovi);
214# else
215  GetVersionEx(&ovi);
216# endif
217  snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
218           (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
219#endif
220
221  TIME_MSG("early init");
222
223  // Setup to use the current locale (for ctype() and many other things).
224  // NOTE: Translated messages with encodings other than latin1 will not
225  // work until set_init_1() has been called!
226  init_locale();
227
228  // tabpage local options (p_ch) must be set before allocating first tabpage.
229  set_init_tablocal();
230
231  // Allocate the first tabpage, window and buffer.
232  win_alloc_first();
233  TIME_MSG("init first window");
234
235  alist_init(&global_alist);    // Init the argument list to empty.
236  global_alist.id = 0;
237
238  // Set the default values for the options.
239  // First find out the home directory, needed to expand "~" in options.
240  init_homedir();               // find real value of $HOME
241  set_init_1(paramp != NULL ? paramp->clean : false);
242  log_init();
243  TIME_MSG("inits 1");
244
245  set_lang_var();               // set v:lang and v:ctype
246
247  // initialize quickfix list
248  qf_init_stack();
249}
250
251#ifdef MAKE_LIB
252int nvim_main(int argc, char **argv);  // silence -Wmissing-prototypes
253int nvim_main(int argc, char **argv)
254#else
255int main(int argc, char **argv)
256#endif
257{
258  argv0 = argv[0];
259  TO_SLASH(argv0);
260
261  if (!appname_is_valid()) {
262    fprintf(stderr, "$NVIM_APPNAME must be a name or relative path.\n");
263    exit(1);
264  }
265
266  char *fname = NULL;     // file name from command line
267  mparm_T params;         // various parameters passed between
268                          // main() and other functions.
269
270  // Many variables are in `params` so that we can pass them around easily.
271  // `argc` and `argv` are also copied, so that they can be changed.
272  init_params(&params, argc, argv);
273
274  init_startuptime(&params);
275
276  // Need to find "--clean" before actually parsing arguments.
277  for (int i = 1; i < params.argc; i++) {
278    if (STRICMP(params.argv[i], "--clean") == 0) {
279      params.clean = true;
280      break;
281    }
282  }
283
284  event_init();
285
286  early_init(&params);
287
288  set_argv_var(argv, argc);  // set v:argv
289
290  // Check if we have an interactive window.
291  check_and_set_isatty(&params);
292
293  // Process the command line arguments.  File names are put in the global
294  // argument list "global_alist".
295  command_line_scan(&params);
296
297  set_argf_var();
298
299  nlua_init(argv, argc, params.lua_arg0);
300  TIME_MSG("init lua interpreter");
301
302  // On Windows, channel_from_stdio() replaces fd 2 with CONOUT$ (for ConPTY
303  // support). Save a dup of the original stderr first so that if server_init()
304  // fails, print_mainerr() can write through the pipe to the TUI client's relay.
305#ifdef MSWIN
306  int startup_stderr_fd = -1;
307  if (embedded_mode) {
308    startup_stderr_fd = os_dup_cloexec(STDERR_FILENO);
309  }
310#endif
311
312  if (embedded_mode) {
313    const char *err;
314    if (!channel_from_stdio(true, CALLBACK_READER_INIT, &err)) {
315      abort();
316    }
317  }
318
319  if (GARGCOUNT > 0) {
320    fname = get_fname(&params);
321  }
322
323  // Recovery mode without a file name: List swap files.
324  // In this case, no UI is needed.
325  if (recoverymode && fname == NULL) {
326    headless_mode = true;
327  }
328
329#ifdef MSWIN
330  // on windows we use CONIN special file, thus we don't know this yet.
331  bool has_term = true;
332#else
333  bool has_term = (stdin_isatty || stdout_isatty || stderr_isatty);
334#endif
335  bool use_builtin_ui = (has_term && !headless_mode && !embedded_mode && !silent_mode);
336
337  if (params.remote) {
338    remote_request(&params, params.remote, params.server_addr, argc, argv,
339                   use_builtin_ui);
340  }
341
342  bool remote_ui = (ui_client_channel_id != 0);
343
344  if (use_builtin_ui && !remote_ui) {
345    ui_client_forward_stdin = !stdin_isatty;
346    uint64_t rv = ui_client_start_server(get_vim_var_str(VV_PROGPATH),
347                                         (size_t)params.argc, params.argv);
348    if (!rv) {
349      fprintf(stderr, "Failed to start Nvim server!\n");
350      os_exit(1);
351    }
352    ui_client_channel_id = rv;
353  }
354
355  // NORETURN: Start builtin UI client.
356  if (ui_client_channel_id) {
357    ui_client_run();  // NORETURN
358  }
359  assert(!ui_client_channel_id && !use_builtin_ui);
360  // Nvim server...
361
362  if (!server_init(params.listen_addr)) {
363#ifdef MSWIN
364    // Restore the original stderr (pipe to TUI client) so print_mainerr()
365    // output is visible in the TUI terminal via the relay in on_channel_output.
366    if (startup_stderr_fd >= 0) {
367      dup2(startup_stderr_fd, STDERR_FILENO);
368      close(startup_stderr_fd);
369      startup_stderr_fd = -1;
370    }
371#endif
372    mainerr(IObuff, NULL, NULL);
373  }
374
375#ifdef MSWIN
376  // Server started successfully. Close the saved fd so the pipe write end is
377  // fully released — child processes inherit CONOUT$ (fd 2), not the pipe.
378  if (startup_stderr_fd >= 0) {
379    close(startup_stderr_fd);
380    startup_stderr_fd = -1;
381  }
382#endif
383
384  TIME_MSG("expanding arguments");
385
386  if (params.diff_mode && params.window_count == -1) {
387    params.window_count = 0;            // open up to 3 windows
388  }
389  // Don't redraw until much later.
390  RedrawingDisabled++;
391
392  setbuf(stdout, NULL);  // NOLINT(bugprone-unsafe-functions)
393
394  full_screen = !silent_mode;
395
396  // Set the default values for the options that use Rows and Columns.
397  win_init_size();
398  // Set the 'diff' option now, so that it can be checked for in a vimrc
399  // file.  There is no buffer yet though.
400  if (params.diff_mode) {
401    diff_win_options(firstwin, false);
402  }
403
404  assert(p_ch >= 0 && Rows >= p_ch && Rows - p_ch <= INT_MAX);
405  cmdline_row = Rows - (int)p_ch;
406  msg_row = cmdline_row;
407  default_grid_alloc();  // allocate screen buffers
408  set_init_2(headless_mode);
409  TIME_MSG("inits 2");
410
411  msg_scroll = true;
412  no_wait_return = true;
413
414  init_highlight(true, false);  // Default highlight groups.
415  ui_comp_syn_init();
416  TIME_MSG("init highlight");
417
418  // Set the break level after the terminal is initialized.
419  debug_break_level = params.use_debug_break_level;
420
421  // Wait for UIs to set up Nvim or show early messages
422  // and prompts (--cmd, swapfile dialog, …).
423  bool use_remote_ui = (embedded_mode && !headless_mode);
424  if (use_remote_ui) {
425    TIME_MSG("waiting for UI");
426    remote_ui_wait_for_attach();
427    TIME_MSG("done waiting for UI");
428    firstwin->w_prev_height = firstwin->w_height;  // may have changed
429  }
430
431  // prepare screen now
432  starting = NO_BUFFERS;
433  screenclear();
434  win_new_screensize();
435  TIME_MSG("clear screen");
436
437  // Handle "foo | nvim". EDIT_FILE may be overwritten now. #6299
438  if (edit_stdin(&params)) {
439    params.edit_type = EDIT_STDIN;
440  }
441
442  if (params.scriptin) {
443    if (!open_scriptin(params.scriptin)) {
444      os_exit(2);
445    }
446  }
447  if (params.scriptout) {
448    scriptout = os_fopen(params.scriptout, params.scriptout_append ? APPENDBIN : WRITEBIN);
449    if (scriptout == NULL) {
450      fprintf(stderr, _("Cannot open for script output: \""));
451      fprintf(stderr, "%s\"\n", params.scriptout);
452      os_exit(2);
453    }
454  }
455
456  nlua_init_defaults();
457
458  TIME_MSG("init default mappings & autocommands");
459
460  bool vimrc_none = strequal(params.use_vimrc, "NONE");
461
462  // Reset 'loadplugins' for "-u NONE" before "--cmd" arguments.
463  // Allows for setting 'loadplugins' there.
464  // For --clean we still want to load plugins.
465  p_lpl = vimrc_none ? params.clean : p_lpl;
466
467  // Execute --cmd arguments.
468  exe_pre_commands(&params);
469
470  if (!vimrc_none || params.clean) {
471    // Sources ftplugin.vim and indent.vim. We do this *before* the user startup scripts to ensure
472    // ftplugins run before FileType autocommands defined in the init file (which allows those
473    // autocommands to overwrite settings from ftplugins).
474    filetype_plugin_enable();
475  }
476
477  // Source startup scripts.
478  source_startup_scripts(&params);
479
480  // If using the runtime (-u is not NONE), enable syntax & filetype plugins.
481  if (!vimrc_none || params.clean) {
482    // Sources filetype.lua unless the user explicitly disabled it with :filetype off.
483    filetype_maybe_enable();
484    // Sources syntax/syntax.vim. We do this *after* the user startup scripts so that users can
485    // disable syntax highlighting with `:syntax off` if they wish.
486    syn_maybe_enable();
487  }
488
489  set_vim_var_nr(VV_VIM_DID_INIT, 1);
490  apply_autocmds(EVENT_VIMINIT, NULL, NULL, false, curbuf);
491  TIME_MSG("VimInit autocommands");
492
493  // Read all the plugin files.
494  load_plugins();
495
496  // Decide about window layout for diff mode after reading vimrc.
497  set_window_layout(&params);
498
499  // "nvim -r" (recovery mode) without a file name: List swap files.
500  if (recoverymode && fname == NULL) {
501    typval_T items_tv;
502    tv_list_alloc_ret(&items_tv, 0);
503    recover_names(NULL, false, items_tv.vval.v_list);
504    typval_T lua_args[] = { items_tv, { .v_type = VAR_UNKNOWN } };
505    nlua_call_typval("vim._core.swapfile", "list_swaps", lua_args, NULL);
506    tv_clear(&items_tv);
507    os_exit(0);
508  }
509
510  // Set some option defaults after reading vimrc files.
511  set_init_3();
512  TIME_MSG("inits 3");
513
514  // "-n" argument: Disable swap file by setting 'updatecount' to 0.
515  // Note that this overrides anything from a vimrc file.
516  if (params.no_swap_file) {
517    p_uc = 0;
518  }
519
520  // XXX: Minimize 'updatetime' for -es/-Es. #7679
521  if (silent_mode) {
522    p_ut = 1;
523  }
524
525  // Read in registers, history etc, from the ShaDa file.
526  // This is where v:oldfiles gets filled.
527  if (*p_shada != NUL) {
528    shada_read_everything(NULL, false, true);
529    TIME_MSG("reading ShaDa");
530  }
531  // It's better to make v:oldfiles an empty list than NULL.
532  if (get_vim_var_list(VV_OLDFILES) == NULL) {
533    set_vim_var_list(VV_OLDFILES, tv_list_alloc(0));
534  }
535
536  // "-q errorfile": Load the error file now.
537  // If the error file can't be read, exit before doing anything else.
538  handle_quickfix(&params);
539
540  //
541  // Start putting things on the screen.
542  // Scroll screen down before drawing over it
543  // Clear screen now, so file message will not be cleared.
544  //
545  starting = NO_BUFFERS;
546  no_wait_return = false;
547  msg_scroll = false;
548
549  // Read file (text, not commands) from stdin if:
550  //    - stdin is not a tty
551  //    - and -e/-es was not given
552  //
553  // Do this before starting Raw mode, because it may change things that the
554  // writing end of the pipe doesn't like, e.g., in case stdin and stderr
555  // are the same terminal: "cat | vim -".
556  // Using autocommands here may cause trouble...
557  if (params.edit_type == EDIT_STDIN && !recoverymode) {
558    read_stdin();
559  }
560
561  setmouse();  // may start using the mouse
562
563  redraw_later(curwin, UPD_VALID);
564
565  no_wait_return = true;
566
567  // Create the requested number of windows and edit buffers in them.
568  // Also does recovery if "recoverymode" set.
569  create_windows(&params);
570  TIME_MSG("opening buffers");
571
572  // Clear v:swapcommand
573  set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
574
575  // Ex starts at last line of the file.
576  if (params.exmode) {
577    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
578  }
579
580  apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
581  TIME_MSG("BufEnter autocommands");
582  setpcmark();
583
584  // When started with "-q errorfile" jump to first error now.
585  if (params.edit_type == EDIT_QF) {
586    qf_jump(NULL, 0, 0, false);
587    TIME_MSG("jump to first error");
588  }
589
590  // If opened more than one window, start editing files in the other
591  // windows.
592  edit_buffers(&params);
593
594  if (params.diff_mode) {
595    // set options in each window for "nvim -d".
596    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
597      if (!wp->w_arg_idx_invalid) {
598        diff_win_options(wp, true);
599      }
600    }
601  }
602
603  // Shorten any of the filenames, but only when absolute.
604  shorten_fnames(false);
605
606  // Need to jump to the tag before executing the '-c command'.
607  // Makes "vim -c '/return' -t main" work.
608  handle_tag(params.tagname);
609
610  // Execute any "+", "-c" and "-S" arguments.
611  if (params.n_commands > 0) {
612    exe_commands(&params);
613  }
614
615  starting = 0;
616
617  RedrawingDisabled = 0;
618  redraw_all_later(UPD_NOT_VALID);
619  no_wait_return = false;
620
621  // 'autochdir' has been postponed.
622  do_autochdir();
623
624  set_vim_var_nr(VV_VIM_DID_ENTER, 1);
625  apply_autocmds(EVENT_VIMENTER, NULL, NULL, false, curbuf);
626  TIME_MSG("VimEnter autocommands");
627  if (use_remote_ui) {
628    do_autocmd_uienter_all();
629    TIME_MSG("UIEnter autocommands");
630  }
631
632#ifdef MSWIN
633  if (use_remote_ui) {
634    os_icon_init();
635  }
636  os_title_save();
637#endif
638
639  // Adjust default register name for "unnamed" in 'clipboard'. Can only be
640  // done after the clipboard is available and all initial commands that may
641  // modify the 'clipboard' setting have run; i.e. just before entering the
642  // main loop.
643  set_reg_var(get_default_register_name());
644
645  // When a startup script or session file setup for diff'ing and
646  // scrollbind, sync the scrollbind now.
647  if (curwin->w_p_diff && curwin->w_p_scb) {
648    update_topline(curwin);
649    check_scrollbind(0, 0);
650    TIME_MSG("diff scrollbinding");
651  }
652
653  // If ":startinsert" command used, stuff a dummy command to be able to
654  // call normal_cmd(), which will then start Insert mode.
655  if (restart_edit != 0) {
656    stuffcharReadbuff(K_NOP);
657  }
658
659  // WORKAROUND(mhi): #3023
660  if (cb_flags & (kOptCbFlagUnnamed | kOptCbFlagUnnamedplus)) {
661    eval_has_provider("clipboard", false);
662  }
663
664  if (params.luaf != NULL) {
665    // Like "--cmd", "+", "-c" and "-S", don't truncate messages.
666    msg_scroll = true;
667    DLOG("executing Lua -l script");
668    bool lua_ok = nlua_exec_file(params.luaf);
669    TIME_MSG("executing Lua -l script");
670    if (msg_didout) {
671      msg_putchar('\n');
672      msg_didout = false;
673    }
674    getout(lua_ok ? 0 : 1);
675  } else if (silent_mode) {
676    // Non-interactive Ex mode (-es): vim._core.exmode.run() executes Ex commands from stdin.
677    msg_scroll = true;
678    no_wait_return++;  // No hit-enter prompts in batch mode, e.g. after "-V1" messages.
679    // Read stdin as commands iff a pipe/file: "nvim -es +cmd" in a tty executes and exits, it
680    // doesn't wait for input. ("-Es" reads stdin as text; already consumed by read_stdin().)
681    if (!params.input_istext && !stdin_isatty) {
682      DLOG("executing stdin as Ex commands");
683      typval_T args[] = { { .v_type = VAR_UNKNOWN } };
684      nlua_call_typval("vim._core.exmode", "run", args, NULL);
685    }
686    if (msg_didout) {
687      msg_putchar('\n');  // Terminate the last output line.
688      msg_didout = false;
689    }
690    getout(0);  // getout() adds `ex_exitval` for "-es".
691  }
692
693  if (params.exmode) {
694    // Interactive Ex mode (-e/-E): cmdwin REPL. #40962
695    do_cmdline_cmd("exmode");
696  }
697
698  TIME_MSG("before starting main loop");
699  ILOG("starting main loop");
700
701  // Main loop: never returns.
702  normal_enter();
703
704#if defined(MSWIN) && !defined(MAKE_LIB)
705  xfree(argv);
706#endif
707  return 0;
708}
709
710void os_exit(int r)
711  FUNC_ATTR_NORETURN
712{
713  exiting = true;
714  // Avoid recursion in case SIGTERM arrives during `os_exit`.
715  signal_reject_deadly();
716
717  if (ui_client_channel_id) {
718    ui_client_stop();
719    if (r == 0) {
720      r = ui_client_exit_status;
721    }
722  } else {
723    ui_flush();
724    ui_call_stop();
725  }
726
727  if (!event_teardown() && r == 0) {
728    r = 1;  // Exit with error if main_loop did not teardown gracefully.
729  }
730  if (ui_client_channel_id) {
731#ifdef HAVE_TERMIOS_H
732    // Sometimes the final output to TTY can be lost (at least on FreeBSD).
733    // Call tcdrain() to ensure all output has been transmitted to host terminal.
734    // Do this after event_teardown() as libuv events may write to stderr.
735    if (stdout_isatty) {
736      tcdrain(STDOUT_FILENO);
737    }
738    if (stderr_isatty) {
739      tcdrain(STDERR_FILENO);
740    }
741#endif
742  } else {
743    ml_close_all(true);  // remove all memfiles
744  }
745
746  ILOG("Nvim exit: %d", r);
747
748#ifdef EXITFREE
749  free_all_mem();
750#endif
751
752  exit(r);
753}
754
755/// Exit properly
756void getout(int exitval)
757  FUNC_ATTR_NORETURN
758{
759  assert(!ui_client_channel_id);
760  exiting = true;
761
762  // make sure startuptimes have been flushed
763  time_finish();
764
765  // On error in "-es" (or explicit ":quit"), exit with a non-zero code.
766  // POSIX requires this, although it's not 100% clear from the standard.
767  if (exmode_active) {
768    exitval += ex_exitval;
769  }
770
771  set_vim_var_type(VV_EXITING, VAR_NUMBER);
772  set_vim_var_nr(VV_EXITING, exitval);
773
774  // Set v:exitreason if not already set (e.g. by :restart).
775  if (*get_vim_var_str(VV_EXITREASON) == NUL) {
776    set_vim_var_string(VV_EXITREASON, S_LEN("quit"));
777  }
778
779  // Invoked all ":defer" functions in the function stack.
780  invoke_all_defer();
781
782  // Optionally print hashtable efficiency.
783  hash_debug_results();
784
785  if (v_dying <= 1) {
786    const tabpage_T *next_tp;
787
788    // Trigger BufWinLeave for all windows, but only once per buffer.
789    for (const tabpage_T *tp = first_tabpage; tp != NULL; tp = next_tp) {
790      next_tp = tp->tp_next;
791      FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
792        if (wp->w_buffer == NULL || !buf_valid(wp->w_buffer)) {
793          // Autocmd must have close the buffer already, skip.
794          continue;
795        }
796
797        buf_T *buf = wp->w_buffer;
798        if (buf_get_changedtick(buf) != -1) {
799          bufref_T bufref;
800
801          set_bufref(&bufref, buf);
802          apply_autocmds_win(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, false, buf, wp);
803          if (bufref_valid(&bufref)) {
804            buf_set_changedtick(buf, -1);  // note that we did it already
805          }
806          // start all over, autocommands may mess up the lists
807          next_tp = first_tabpage;
808          break;
809        }
810      }
811    }
812
813    // Trigger BufUnload for buffers that are loaded
814    FOR_ALL_BUFFERS(buf) {
815      if (buf->b_ml.ml_mfp != NULL) {
816        bufref_T bufref;
817        set_bufref(&bufref, buf);
818        apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, false, buf);
819        if (!bufref_valid(&bufref)) {
820          // Autocmd deleted the buffer.
821          break;
822        }
823      }
824    }
825
826    int unblock = 0;
827    // deathtrap() blocks autocommands, but we do want to trigger
828    // VimLeavePre.
829    if (is_autocmd_blocked()) {
830      unblock_autocmds();
831      unblock++;
832    }
833    apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, false, curbuf);
834    if (unblock) {
835      block_autocmds();
836    }
837  }
838
839  if (
840#ifdef EXITFREE
841      !entered_free_all_mem &&
842#endif
843      p_shada && *p_shada != NUL) {
844    // Write out the registers, history, marks etc, to the ShaDa file
845    shada_write_file(NULL, false);
846  }
847
848  if (v_dying <= 1) {
849    int unblock = 0;
850
851    // deathtrap() blocks autocommands, but we do want to trigger VimLeave.
852    if (is_autocmd_blocked()) {
853      unblock_autocmds();
854      unblock++;
855    }
856    apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, false, curbuf);
857    if (unblock) {
858      block_autocmds();
859    }
860  }
861
862  profile_dump();
863
864  if (did_emsg) {
865    // give the user a chance to read the (error) message
866    no_wait_return = false;
867    // TODO(justinmk): this may call getout(0), clobbering exitval...
868    wait_return(false);
869  }
870
871  // Apply 'titleold'.
872  if (p_title && *p_titleold != NUL) {
873    ui_call_set_title(cstr_as_string(p_titleold));
874  }
875
876  if (garbage_collect_at_exit) {
877    garbage_collect(false);
878  }
879
880#ifdef MSWIN
881  // Restore Windows console icon before exiting.
882  os_icon_reset();
883  os_title_reset();
884#endif
885
886  os_exit(exitval);
887}
888
889/// Preserve files, print contents of `errmsg`, and exit 1.
890/// @param errmsg  If NULL, this function will not print anything.
891///
892/// May be called from deadly_signal().
893void preserve_exit(const char *errmsg)
894  FUNC_ATTR_NORETURN
895{
896  // 'true' when we are sure to exit, e.g., after a deadly signal
897  static bool really_exiting = false;
898
899  // Prevent repeated calls into this method.
900  if (really_exiting) {
901    exit(2);
902  }
903
904  really_exiting = true;
905  // Set this now, to neuter a stray `exit_event` on the event-loop. #39675
906  exiting = true;
907  // Ignore SIGHUP while we are already exiting. #9274
908  signal_reject_deadly();
909
910  if (ui_client_channel_id) {
911    // For TUI: exit alternate screen so that the error messages can be seen.
912    ui_client_stop();
913  }
914  if (errmsg != NULL && errmsg[0] != NUL) {
915    bool has_eol = '\n' == errmsg[strlen(errmsg) - 1];
916    fprintf(stderr, has_eol ? "%s" : "%s\n", errmsg);
917  }
918  if (ui_client_channel_id) {
919    os_exit(1);
920  }
921
922  ml_close_notmod();                // close all not-modified buffers
923
924  FOR_ALL_BUFFERS(buf) {
925    if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) {
926      if (errmsg != NULL) {
927        fprintf(stderr, "Nvim: preserving files...\n");
928      }
929      ml_sync_all(false, false, true);  // preserve all swap files
930      break;
931    }
932  }
933
934  ml_close_all(false);              // close all memfiles, without deleting
935
936  if (errmsg != NULL) {
937    fprintf(stderr, "Nvim: Finished.\n");
938  }
939
940  getout(1);
941}
942
943/// Gets the integer value of a numeric command line argument if given,
944/// such as '-o10'.
945///
946/// @param[in] p         pointer to argument
947/// @param[in, out] idx  pointer to index in argument, is incremented
948/// @param[in] def       default value
949///
950/// @return def unmodified if:
951///   - argument isn't given
952///   - argument is non-numeric
953///
954/// @return argument's numeric value otherwise
955static int get_number_arg(const char *p, int *idx, int def)
956  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
957{
958  if (ascii_isdigit(p[*idx])) {
959    def = atoi(&(p[*idx]));
960    while (ascii_isdigit(p[*idx])) {
961      *idx = *idx + 1;
962    }
963  }
964  return def;
965}
966
967static uint64_t server_connect(char *server_addr, const char **errmsg)
968{
969  if (server_addr == NULL) {
970    *errmsg = "no address specified";
971    return 0;
972  }
973  CallbackReader on_data = CALLBACK_READER_INIT;
974  const char *error = NULL;
975  bool is_tcp = socket_address_tcp_host_end(server_addr) != NULL;
976  // connected to channel
977  uint64_t chan = channel_connect(is_tcp, server_addr, true, on_data, 500, &error);
978  if (error) {
979    *errmsg = error;
980    return 0;
981  }
982  return chan;
983}
984
985/// Handle remote subcommands
986static void remote_request(mparm_T *params, int remote_args, char *server_addr, int argc,
987                           char **argv, bool ui_only)
988{
989  bool is_ui = strequal(argv[remote_args], "--remote-ui");
990  if (ui_only && !is_ui) {
991    // TODO(bfredl): this implies always starting the TUI.
992    // if we be smart we could delay this past should_exit
993    return;
994  }
995
996  const char *connect_error = NULL;
997  uint64_t chan = server_connect(server_addr, &connect_error);
998  Object rvobj = OBJECT_INIT;
999
1000  if (is_ui) {
1001    if (!chan) {
1002#ifdef MSWIN
1003      // The TUI client is spawned in a ConPTY which only captures stdout.
1004      // Redirect stderr to stdout so this error appears in the terminal.
1005      dup2(STDOUT_FILENO, STDERR_FILENO);
1006#endif
1007      fprintf(stderr, "Remote ui failed to start: %s\n", connect_error);
1008      os_exit(1);
1009    } else if (strequal(server_addr, os_getenv_noalloc("NVIM"))) {
1010      fprintf(stderr, "%s", "Cannot attach UI of :terminal child to its parent. ");
1011      fprintf(stderr, "%s\n", "(Unset $NVIM to skip this check)");
1012      os_exit(1);
1013    }
1014    ui_client_channel_id = chan;
1015    return;
1016  }
1017
1018  Array args = ARRAY_DICT_INIT;
1019  kv_resize(args, (size_t)(argc - remote_args));
1020  for (int t_argc = remote_args; t_argc < argc; t_argc++) {
1021    ADD_C(args, CSTR_AS_OBJ(argv[t_argc]));
1022  }
1023
1024  Error err = ERROR_INIT;
1025  MAXSIZE_TEMP_ARRAY(a, 4);
1026  ADD_C(a, INTEGER_OBJ((int)chan));
1027  ADD_C(a, CSTR_AS_OBJ(server_addr));
1028  ADD_C(a, CSTR_AS_OBJ(connect_error));
1029  ADD_C(a, ARRAY_OBJ(args));
1030  String s = STATIC_CSTR_AS_STRING("return vim._cs_remote(...)");
1031  Object o = nlua_exec(s, NULL, a, kRetObject, NULL, &err);
1032  kv_destroy(args);
1033  if (ERROR_SET(&err)) {
1034    fprintf(stderr, "%s\n", err.msg);
1035    os_exit(2);
1036  }
1037
1038  if (o.type == kObjectTypeDict) {
1039    rvobj.data.dict = o.data.dict;
1040  } else {
1041    fprintf(stderr, "vim._cs_remote returned unexpected value\n");
1042    os_exit(2);
1043  }
1044
1045  TriState should_exit = kNone;
1046  TriState tabbed = kNone;
1047
1048  for (size_t i = 0; i < rvobj.data.dict.size; i++) {
1049    if (strequal(rvobj.data.dict.items[i].key.data, "errmsg")) {
1050      if (rvobj.data.dict.items[i].value.type != kObjectTypeString) {
1051        fprintf(stderr, "vim._cs_remote returned an unexpected type for 'errmsg'\n");
1052        os_exit(2);
1053      }
1054      fprintf(stderr, "%s\n", rvobj.data.dict.items[i].value.data.string.data);
1055      os_exit(2);
1056    } else if (strequal(rvobj.data.dict.items[i].key.data, "result")) {
1057      if (rvobj.data.dict.items[i].value.type != kObjectTypeString) {
1058        fprintf(stderr, "vim._cs_remote returned an unexpected type for 'result'\n");
1059        os_exit(2);
1060      }
1061      printf("%s", rvobj.data.dict.items[i].value.data.string.data);
1062    } else if (strequal(rvobj.data.dict.items[i].key.data, "tabbed")) {
1063      if (rvobj.data.dict.items[i].value.type != kObjectTypeBoolean) {
1064        fprintf(stderr, "vim._cs_remote returned an unexpected type for 'tabbed'\n");
1065        os_exit(2);
1066      }
1067      tabbed = rvobj.data.dict.items[i].value.data.boolean ? kTrue : kFalse;
1068    } else if (strequal(rvobj.data.dict.items[i].key.data, "should_exit")) {
1069      if (rvobj.data.dict.items[i].value.type != kObjectTypeBoolean) {
1070        fprintf(stderr, "vim._cs_remote returned an unexpected type for 'should_exit'\n");
1071        os_exit(2);
1072      }
1073      should_exit = rvobj.data.dict.items[i].value.data.boolean ? kTrue : kFalse;
1074    }
1075  }
1076  if (should_exit == kNone || tabbed == kNone) {
1077    fprintf(stderr, "vim._cs_remote didn't return a value for should_exit or tabbed, bailing\n");
1078    os_exit(2);
1079  }
1080  api_free_object(o);
1081
1082  if (should_exit == kTrue) {
1083    os_exit(0);
1084  }
1085  if (tabbed == kTrue) {
1086    params->window_count = argc - remote_args - 1;
1087    params->window_layout = WIN_TABS;
1088  }
1089}
1090
1091/// Decides whether text (as opposed to commands) will be read from stdin.
1092/// @see EDIT_STDIN
1093static bool edit_stdin(mparm_T *parmp)
1094{
1095  bool implicit = !headless_mode
1096                  && !(embedded_mode && stdin_fd <= 0)
1097                  && (!parmp->exmode || parmp->input_istext)
1098                  && !stdin_isatty
1099                  && parmp->edit_type <= EDIT_STDIN
1100                  && parmp->scriptin == NULL;  // `-s -` was not given.
1101  return parmp->had_stdin_file || implicit;
1102}
1103
1104/// Scan the command line arguments.
1105static void command_line_scan(mparm_T *parmp)
1106{
1107  int argc = parmp->argc;
1108  char **argv = parmp->argv;
1109  int argv_idx;                         // index in argv[n][]
1110  bool had_minmin = false;              // found "--" argument
1111  bool want_argument;                   // option argument with argument
1112  int n;
1113
1114  argc--;
1115  argv++;
1116  argv_idx = 1;  // active option letter is argv[0][argv_idx]
1117  while (argc > 0) {
1118    // "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
1119    if (argv[0][0] == '+' && !had_minmin) {
1120      if (parmp->n_commands >= MAX_ARG_CMDS) {
1121        mainerr(err_extra_cmd, NULL, NULL);
1122      }
1123      argv_idx = -1;  // skip to next argument
1124      if (argv[0][1] == NUL) {
1125        parmp->commands[parmp->n_commands++] = "$";
1126      } else {
1127        parmp->commands[parmp->n_commands++] = &(argv[0][1]);
1128      }
1129    } else if (argv[0][0] == '-' && !had_minmin) {
1130      // Optional argument.
1131
1132      want_argument = false;
1133      char c = argv[0][argv_idx++];
1134      switch (c) {
1135      case NUL:    // "nvim -"  read from stdin
1136        if (parmp->exmode) {
1137          // "nvim -e -" silent mode
1138          silent_mode = true;
1139          exmode_active = true;
1140          parmp->no_swap_file = true;
1141        } else {
1142          if (parmp->edit_type > EDIT_STDIN) {
1143            mainerr(err_too_many_args, argv[0], NULL);
1144          }
1145          parmp->had_stdin_file = true;
1146          parmp->edit_type = EDIT_STDIN;
1147        }
1148        argv_idx = -1;  // skip to next argument
1149        break;
1150      case '-':    // "--" No more option arguments.
1151        // "--help" give help message
1152        // "--version" give version message
1153        // "--noplugin[s]" skip plugins
1154        // "--cmd <cmd>" execute cmd before vimrc
1155        // "--remote" execute commands remotey on a server
1156        // "--server" name of vim server to send remote commands to
1157        if (STRICMP(argv[0] + argv_idx, "help") == 0) {
1158          usage();
1159          os_exit(0);
1160        } else if (STRICMP(argv[0] + argv_idx, "version") == 0) {
1161          version();
1162          os_exit(0);
1163        } else if (STRICMP(argv[0] + argv_idx, "api-info") == 0) {
1164#ifdef MSWIN
1165          // set stdout to binary to avoid crlf in --api-info output
1166          _setmode(STDOUT_FILENO, _O_BINARY);
1167#endif
1168
1169          String data = api_metadata_raw();
1170          const ptrdiff_t written_bytes = os_write(STDOUT_FILENO, data.data, data.size, false);
1171          if (written_bytes < 0) {
1172            semsg(_("E5420: Failed to write to file: %s"), os_strerror((int)written_bytes));
1173          }
1174
1175          os_exit(0);
1176        } else if (STRICMP(argv[0] + argv_idx, "headless") == 0) {
1177          headless_mode = true;
1178        } else if (STRICMP(argv[0] + argv_idx, "embed") == 0) {
1179          embedded_mode = true;
1180        } else if (STRNICMP(argv[0] + argv_idx, "listen", 6) == 0) {
1181          want_argument = true;
1182          argv_idx += 6;
1183        } else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0) {
1184          // Do nothing: file args are always literal. #7679
1185        } else if (STRNICMP(argv[0] + argv_idx, "remote", 6) == 0) {
1186          parmp->remote = parmp->argc - argc;
1187        } else if (STRNICMP(argv[0] + argv_idx, "server", 6) == 0) {
1188          want_argument = true;
1189          argv_idx += 6;
1190        } else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0) {
1191          p_lpl = false;
1192        } else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0) {
1193          want_argument = true;
1194          argv_idx += 3;
1195        } else if (STRNICMP(argv[0] + argv_idx, "startuptime", 11) == 0) {
1196          want_argument = true;
1197          argv_idx += 11;
1198        } else if (STRNICMP(argv[0] + argv_idx, "clean", 5) == 0) {
1199          parmp->use_vimrc = "NONE";
1200          parmp->clean = true;
1201          set_option_value_give_err(kOptShadafile, STATIC_CSTR_AS_OBJ("NONE"), 0);
1202        } else if (STRNICMP(argv[0] + argv_idx, "luamod-dev", 9) == 0) {
1203          nlua_disable_preload = true;
1204        } else {
1205          if (argv[0][argv_idx]) {
1206            mainerr(err_opt_unknown, argv[0], NULL);
1207          }
1208          had_minmin = true;
1209        }
1210        if (!want_argument) {
1211          argv_idx = -1;  // skip to next argument
1212        }
1213        break;
1214      case 'A':    // "-A" start in Arabic mode.
1215        set_option_value_give_err(kOptArabic, BOOLEAN_OBJ(true), 0);
1216        break;
1217      case 'b':    // "-b" binary mode.
1218        // Needs to be effective before expanding file names, because
1219        // for Win32 this makes us edit a shortcut file itself,
1220        // instead of the file it links to.
1221        set_options_bin(curbuf->b_p_bin, 1, 0);
1222        curbuf->b_p_bin = 1;  // Binary file I/O.
1223        break;
1224
1225      case 'D':    // "-D" Debugging
1226        parmp->use_debug_break_level = 9999;
1227        break;
1228      case 'd':    // "-d" 'diff'
1229        parmp->diff_mode = true;
1230        break;
1231      case 'e':    // "-e" Ex mode
1232        parmp->exmode = true;
1233        break;
1234      case 'E':    // "-E" Ex mode
1235        parmp->exmode = true;
1236        parmp->input_istext = true;
1237        break;
1238      case 'f':    // "-f"  GUI: run in foreground.
1239        break;
1240      case '?':    // "-?" give help message (for MS-Windows)
1241      case 'h':    // "-h" give help message
1242        usage();
1243        os_exit(0);
1244      case 'H':    // "-H" start in Hebrew mode: rl + keymap=hebrew set.
1245        set_option_value_give_err(kOptKeymap, STATIC_CSTR_AS_OBJ("hebrew"), 0);
1246        set_option_value_give_err(kOptRightleft, BOOLEAN_OBJ(true), 0);
1247        break;
1248      case 'M':    // "-M"  no changes or writing of files
1249        reset_modifiable();
1250        FALLTHROUGH;
1251      case 'm':    // "-m"  no writing of files
1252        p_write = false;
1253        break;
1254
1255      case 'N':    // "-N"  Nocompatible
1256      case 'X':    // "-X"  Do not connect to X server
1257        // No-op
1258        break;
1259
1260      case 'n':    // "-n" no swap file
1261        parmp->no_swap_file = true;
1262        break;
1263      case 'p':    // "-p[N]" open N tab pages
1264        // default is 0: open window for each file
1265        parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
1266        parmp->window_layout = WIN_TABS;
1267        break;
1268      case 'o':    // "-o[N]" open N horizontal split windows
1269        // default is 0: open window for each file
1270        parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
1271        parmp->window_layout = WIN_HOR;
1272        break;
1273      case 'O':    // "-O[N]" open N vertical split windows
1274        // default is 0: open window for each file
1275        parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
1276        parmp->window_layout = WIN_VER;
1277        break;
1278      case 'q':    // "-q" QuickFix mode
1279        if (parmp->edit_type != EDIT_NONE) {
1280          mainerr(err_too_many_args, argv[0], NULL);
1281        }
1282        parmp->edit_type = EDIT_QF;
1283        if (argv[0][argv_idx]) {  // "-q{errorfile}"
1284          parmp->use_ef = argv[0] + argv_idx;
1285          argv_idx = -1;
1286        } else if (argc > 1) {    // "-q {errorfile}"
1287          want_argument = true;
1288        }
1289        break;
1290      case 'R':    // "-R" readonly mode
1291        readonlymode = true;
1292        curbuf->b_p_ro = true;
1293        p_uc = 10000;  // don't update very often
1294        break;
1295      case 'r':    // "-r" recovery mode
1296      case 'L':    // "-L" recovery mode
1297        recoverymode = 1;
1298        break;
1299      case 's':
1300        if (parmp->exmode) {    // "-es" silent (batch) mode
1301          silent_mode = true;
1302          exmode_active = true;
1303          parmp->no_swap_file = true;
1304          if (p_shadafile == NULL || *p_shadafile == NUL) {
1305            set_option_value_give_err(kOptShadafile, STATIC_CSTR_AS_OBJ("NONE"), 0);
1306          }
1307        } else {                // "-s {scriptin}" read from script file
1308          want_argument = true;
1309        }
1310        break;
1311      case 't':    // "-t {tag}" or "-t{tag}" jump to tag
1312        if (parmp->edit_type != EDIT_NONE) {
1313          mainerr(err_too_many_args, argv[0], NULL);
1314        }
1315        parmp->edit_type = EDIT_TAG;
1316        if (argv[0][argv_idx]) {  // "-t{tag}"
1317          parmp->tagname = argv[0] + argv_idx;
1318          argv_idx = -1;
1319        } else {  // "-t {tag}"
1320          want_argument = true;
1321        }
1322        break;
1323      case 'v':
1324        version();
1325        os_exit(0);
1326      case 'V':    // "-V{N}" Verbose level
1327        // default is 10: a little bit verbose
1328        p_verbose = get_number_arg(argv[0], &argv_idx, 10);
1329        if (argv[0][argv_idx] != NUL) {
1330          set_option_value_give_err(kOptVerbosefile, CSTR_AS_OBJ(argv[0] + argv_idx), 0);
1331          argv_idx = (int)strlen(argv[0]);
1332        }
1333        break;
1334      case 'w':    // "-w{number}" set window height
1335        // "-w {scriptout}" write to script
1336        if (ascii_isdigit((argv[0])[argv_idx])) {
1337          n = get_number_arg(argv[0], &argv_idx, 10);
1338          set_option_value_give_err(kOptWindow, INTEGER_OBJ((OptInt)n), 0);
1339          break;
1340        }
1341        want_argument = true;
1342        break;
1343
1344      case 'c':    // "-c{command}" or "-c {command}" exec command
1345        if (argv[0][argv_idx] != NUL) {
1346          if (parmp->n_commands >= MAX_ARG_CMDS) {
1347            mainerr(err_extra_cmd, NULL, NULL);
1348          }
1349          parmp->commands[parmp->n_commands++] = argv[0] + argv_idx;
1350          argv_idx = -1;
1351          break;
1352        }
1353        FALLTHROUGH;
1354      case 'S':    // "-S {file}" execute Vim script
1355      case 'i':    // "-i {shada}" use for ShaDa file
1356      case 'l':    // "-l {file}" Lua mode
1357      case 'u':    // "-u {vimrc}" vim inits file
1358      case 'U':    // "-U {gvimrc}" gvim inits file
1359      case 'W':    // "-W {scriptout}" overwrite
1360        want_argument = true;
1361        break;
1362
1363      default:
1364        mainerr(err_opt_unknown, argv[0], NULL);
1365      }
1366
1367      // Handle option arguments with argument.
1368      if (want_argument) {
1369        // Check for garbage immediately after the option letter.
1370        if (argv[0][argv_idx] != NUL) {
1371          mainerr(err_opt_garbage, argv[0], NULL);
1372        }
1373
1374        argc--;
1375        if (argc < 1 && c != 'S') {  // -S has an optional argument
1376          mainerr(err_arg_missing, argv[0], NULL);
1377        }
1378        argv++;
1379        argv_idx = -1;
1380
1381        switch (c) {
1382        case 'c':    // "-c {command}" execute command
1383        case 'S':    // "-S {file}" execute Vim script
1384          if (parmp->n_commands >= MAX_ARG_CMDS) {
1385            mainerr(err_extra_cmd, NULL, NULL);
1386          }
1387          if (c == 'S') {
1388            char *a;
1389
1390            if (argc < 1) {
1391              // "-S" without argument: use default session file name.
1392              a = SESSION_FILE;
1393            } else if (argv[0][0] == '-') {
1394              // "-S" followed by another option: use default session file.
1395              a = SESSION_FILE;
1396              argc++;
1397              argv--;
1398            } else {
1399              a = argv[0];
1400            }
1401
1402            size_t s_size = strlen(a) + 9;
1403            char *s = xmalloc(s_size);
1404            snprintf(s, s_size, "so %s", a);
1405            parmp->cmds_tofree[parmp->n_commands] = true;
1406            parmp->commands[parmp->n_commands++] = s;
1407          } else {
1408            parmp->commands[parmp->n_commands++] = argv[0];
1409          }
1410          break;
1411
1412        case '-':
1413          if (strequal(argv[-1], "--cmd")) {
1414            // "--cmd {command}" execute command
1415            if (parmp->n_pre_commands >= MAX_ARG_CMDS) {
1416              mainerr(err_extra_cmd, NULL, NULL);
1417            }
1418            parmp->pre_commands[parmp->n_pre_commands++] = argv[0];
1419          } else if (strequal(argv[-1], "--listen")) {
1420            // "--listen {address}"
1421            TO_SLASH(argv[0]);
1422            parmp->listen_addr = argv[0];
1423          } else if (strequal(argv[-1], "--server")) {
1424            // "--server {address}"
1425            TO_SLASH(argv[0]);
1426            parmp->server_addr = argv[0];
1427          }
1428          // "--startuptime <file>" already handled
1429          break;
1430
1431        case 'q':    // "-q {errorfile}" QuickFix mode
1432          parmp->use_ef = argv[0];
1433          break;
1434
1435        case 'i':    // "-i {shada}" use for shada
1436          set_option_value_give_err(kOptShadafile, CSTR_AS_OBJ(argv[0]), 0);
1437          break;
1438
1439        case 'l':    // "-l" Lua script: args after "-l".
1440          headless_mode = true;
1441          silent_mode = true;
1442          p_verbose = 1;
1443          parmp->no_swap_file = true;
1444          parmp->use_vimrc = parmp->use_vimrc ? parmp->use_vimrc : "NONE";
1445          if (p_shadafile == NULL || *p_shadafile == NUL) {
1446            set_option_value_give_err(kOptShadafile, STATIC_CSTR_AS_OBJ("NONE"), 0);
1447          }
1448          parmp->luaf = argv[0];
1449          argc--;
1450          if (argc >= 0) {  // Lua args after "-l <file>".
1451            parmp->lua_arg0 = parmp->argc - argc;
1452            argc = 0;
1453          }
1454          break;
1455
1456        case 's':    // "-s {scriptin}" read from script file
1457          if (parmp->scriptin != NULL) {
1458scripterror:
1459            vim_snprintf(IObuff, IOSIZE,
1460                         _("Attempt to open script file again: \"%s %s\"\n"),
1461                         argv[-1], argv[0]);
1462            fprintf(stderr, "%s", IObuff);
1463            os_exit(2);
1464          }
1465          parmp->scriptin = argv[0];
1466          break;
1467
1468        case 't':    // "-t {tag}"
1469          parmp->tagname = argv[0];
1470          break;
1471        case 'u':    // "-u {vimrc}" vim inits file
1472          parmp->use_vimrc = argv[0];
1473          TO_SLASH(argv[0]);
1474          break;
1475        case 'U':    // "-U {gvimrc}" gvim inits file
1476          break;
1477
1478        case 'w':    // "-w {nr}" 'window' value
1479          // "-w {scriptout}" append to script file
1480          if (ascii_isdigit(*(argv[0]))) {
1481            argv_idx = 0;
1482            n = get_number_arg(argv[0], &argv_idx, 10);
1483            set_option_value_give_err(kOptWindow, INTEGER_OBJ((OptInt)n), 0);
1484            argv_idx = -1;
1485            break;
1486          }
1487          FALLTHROUGH;
1488        case 'W':    // "-W {scriptout}" overwrite script file
1489          if (parmp->scriptout != NULL) {
1490            goto scripterror;
1491          }
1492          parmp->scriptout = argv[0];
1493          parmp->scriptout_append = (c == 'w');
1494        }
1495      }
1496    } else {  // File name argument.
1497      argv_idx = -1;  // skip to next argument
1498
1499      // Check for only one type of editing.
1500      if (parmp->edit_type > EDIT_STDIN) {
1501        mainerr(err_too_many_args, argv[0], NULL);
1502      }
1503      parmp->edit_type = EDIT_FILE;
1504
1505      // Add the file to the global argument list.
1506      ga_grow(&global_alist.al_ga, 1);
1507      char *p = xstrdup(argv[0]);
1508
1509      // On Windows expand "~\" or "~/" prefix in file names to profile directory.
1510#ifdef MSWIN
1511      TO_SLASH(p);
1512      if (*p == '~' && p[1] == '/') {
1513        size_t size = strlen(os_homedir()) + strlen(p);
1514        char *tilde_expanded = xmalloc(size);
1515        snprintf(tilde_expanded, size, "%s%s", os_homedir(), p + 1);
1516        xfree(p);
1517        p = tilde_expanded;
1518      }
1519#endif
1520
1521      if (parmp->diff_mode && os_isdir(p) && GARGCOUNT > 0
1522          && !os_isdir(alist_name(&GARGLIST[0]))) {
1523        const char *tail = path_tail(alist_name(&GARGLIST[0]));
1524        String ret = concat_fnames(cstr_as_string(p), cstr_as_string(tail), true);
1525        xfree(p);
1526        p = ret.data;
1527      }
1528
1529#ifdef CASE_INSENSITIVE_FILENAME
1530      // Make the case of the file name match the actual file.
1531      path_fix_case(p);
1532#endif
1533
1534      int alist_fnum_flag = edit_stdin(parmp)
1535                            ? 1   // add buffer nr after exp.
1536                            : 2;  // add buffer number now and use curbuf
1537      alist_add(&global_alist, p, alist_fnum_flag);
1538    }
1539
1540    // If there are no more letters after the current "-", go to next argument.
1541    // argv_idx is set to -1 when the current argument is to be skipped.
1542    if (argv_idx <= 0 || argv[0][argv_idx] == NUL) {
1543      argc--;
1544      argv++;
1545      argv_idx = 1;
1546    }
1547  }
1548
1549  if (embedded_mode && (silent_mode || parmp->luaf)) {
1550    mainerr(_("--embed conflicts with -es/-Es/-l"), NULL, NULL);
1551  }
1552
1553  // If there is a "+123" or "-c" command, set v:swapcommand to the first one.
1554  if (parmp->n_commands > 0) {
1555    const size_t swcmd_len = strlen(parmp->commands[0]) + 2;
1556    char *const swcmd = xmalloc(swcmd_len + 1);
1557    snprintf(swcmd, swcmd_len + 1, ":%s\r", parmp->commands[0]);
1558    set_vim_var_string(VV_SWAPCOMMAND, swcmd, (ptrdiff_t)swcmd_len);
1559    xfree(swcmd);
1560  }
1561
1562  TIME_MSG("parsing arguments");
1563}
1564
1565static void set_argf_var(void)
1566{
1567  list_T *list = tv_list_alloc(kListLenMayKnow);
1568
1569  for (int i = 0; i < GARGCOUNT; i++) {
1570    char *fname = alist_name(&GARGLIST[i]);
1571    if (fname != NULL) {
1572      (void)vim_FullName(fname, NameBuff, sizeof(NameBuff), false);
1573      tv_list_append_string(list, NameBuff, -1);
1574    }
1575  }
1576
1577  tv_list_set_lock(list, VAR_FIXED);
1578  set_vim_var_list(VV_ARGF, list);
1579}
1580
1581// Many variables are in "params" so that we can pass them to invoked
1582// functions without a lot of arguments.  "argc" and "argv" are also
1583// copied, so that they can be changed.
1584static void init_params(mparm_T *paramp, int argc, char **argv)
1585{
1586  CLEAR_POINTER(paramp);
1587  paramp->argc = argc;
1588  paramp->argv = argv;
1589  paramp->use_debug_break_level = -1;
1590  paramp->window_count = -1;
1591  paramp->listen_addr = NULL;
1592  paramp->server_addr = NULL;
1593  paramp->remote = 0;
1594  paramp->luaf = NULL;
1595  paramp->lua_arg0 = -1;
1596}
1597
1598/// Initialize global startuptime file if "--startuptime" passed as an argument.
1599static void init_startuptime(mparm_T *paramp)
1600{
1601  bool is_embed = false;
1602  for (int i = 1; i < paramp->argc - 1; i++) {
1603    if (STRICMP(paramp->argv[i], "--embed") == 0) {
1604      is_embed = true;
1605      break;
1606    }
1607  }
1608  for (int i = 1; i < paramp->argc - 1; i++) {
1609    if (STRICMP(paramp->argv[i], "--startuptime") == 0) {
1610      time_init(paramp->argv[i + 1], is_embed ? "Embedded" : "Primary (or UI client)");
1611      time_start("--- NVIM STARTING ---");
1612      break;
1613    }
1614  }
1615}
1616
1617static void check_and_set_isatty(mparm_T *paramp)
1618{
1619  stdin_isatty = os_isatty(STDIN_FILENO);
1620  stdout_isatty = os_isatty(STDOUT_FILENO);
1621  stderr_isatty = os_isatty(STDERR_FILENO);
1622  TIME_MSG("window checked");
1623}
1624
1625// Sets v:progname and v:progpath. Also modifies $PATH on Windows.
1626static void init_path(const char *exename)
1627  FUNC_ATTR_NONNULL_ALL
1628{
1629  char exepath[MAXPATHL] = { 0 };
1630  size_t exepathlen = MAXPATHL;
1631  // Make v:progpath absolute.
1632  if (os_exepath(exepath, &exepathlen) != 0) {
1633    // Fall back to argv[0]. Missing procfs? #6734
1634    path_guess_exepath(exename, exepath, sizeof(exepath));
1635  }
1636  set_vim_var_string(VV_PROGPATH, exepath, -1);
1637  set_vim_var_string(VV_PROGNAME, path_tail(exename), -1);
1638
1639#ifdef MSWIN
1640  // Append the process start directory to $PATH, so that ":!foo" finds tools
1641  // shipped with Windows package. This also mimics SearchPath().
1642  os_setenv_append_path(exepath);
1643#endif
1644}
1645
1646/// Get filename from command line, if any.
1647static char *get_fname(mparm_T *parmp)
1648{
1649  return alist_name(&GARGLIST[0]);
1650}
1651
1652// Decide about window layout for diff mode after reading vimrc.
1653static void set_window_layout(mparm_T *paramp)
1654{
1655  if (paramp->diff_mode && paramp->window_layout == 0) {
1656    if (diffopt_horizontal()) {
1657      paramp->window_layout = WIN_HOR;             // use horizontal split
1658    } else {
1659      paramp->window_layout = WIN_VER;             // use vertical split
1660    }
1661  }
1662}
1663
1664// "-q errorfile": Load the error file now.
1665// If the error file can't be read, exit before doing anything else.
1666static void handle_quickfix(mparm_T *paramp)
1667{
1668  if (paramp->edit_type == EDIT_QF) {
1669    if (paramp->use_ef != NULL) {
1670      set_option_direct(kOptErrorfile, CSTR_AS_OBJ(paramp->use_ef), 0, SID_CARG);
1671    }
1672    vim_snprintf(IObuff, IOSIZE, "cfile %s", p_ef);
1673    if (qf_init(NULL, p_ef, p_efm, true, IObuff, p_menc) < 0) {
1674      msg_putchar('\n');
1675      os_exit(3);
1676    }
1677    TIME_MSG("reading errorfile");
1678  }
1679}
1680
1681// Need to jump to the tag before executing the '-c command'.
1682// Makes "vim -c '/return' -t main" work.
1683static void handle_tag(char *tagname)
1684{
1685  if (tagname != NULL) {
1686    swap_exists_did_quit = false;
1687
1688    vim_snprintf(IObuff, IOSIZE, "ta %s", tagname);
1689    do_cmdline_cmd(IObuff);
1690    TIME_MSG("jumping to tag");
1691
1692    // If the user doesn't want to edit the file then we quit here.
1693    if (swap_exists_did_quit) {
1694      ui_call_error_exit(1);
1695      getout(1);
1696    }
1697  }
1698}
1699
1700/// Read text from stdin.
1701static void read_stdin(void)
1702{
1703  // When getting the ATTENTION prompt here, use a dialog.
1704  swap_exists_action = SEA_DIALOG;
1705  no_wait_return = true;
1706  bool save_msg_didany = msg_didany;
1707
1708  if (curbuf->b_ffname) {
1709    // curbuf is already opened for a file, create a new buffer for stdin. #35269
1710    buf_T *stdin_buf = buflist_new(NULL, NULL, 0, BLN_LISTED);
1711    if (stdin_buf == NULL) {
1712      semsg("Failed to create buffer for stdin");
1713      return;
1714    }
1715
1716    // remember the current buffer number so we can go back to it
1717    handle_T initial_buf_handle = curbuf->handle;
1718
1719    // set the buffer we just created as curbuf so we can read stdin into it
1720    set_curbuf(stdin_buf, 0, false);
1721    readfile(NULL, NULL, 0, 0, (linenr_T)MAXLNUM, NULL, READ_NEW + READ_STDIN, true);
1722
1723    // remember stdin_buf_handle so we can close it if stdin_buf ends up empty
1724    handle_T stdin_buf_handle = stdin_buf->handle;
1725    bool stdin_buf_empty = buf_is_empty(curbuf);
1726
1727    // switch back to the original starting buffer
1728    char buf[100];
1729    vim_snprintf(buf, sizeof(buf), "silent! buffer %d", initial_buf_handle);
1730    do_cmdline_cmd(buf);
1731
1732    if (stdin_buf_empty) {
1733      // stdin buffer may be first or last ("echo foo | nvim file1 -"). #35269
1734      // only wipe buffer after having switched to original starting buffer. #35681
1735      vim_snprintf(buf, sizeof(buf), "silent! bwipeout! %d", stdin_buf_handle);
1736      do_cmdline_cmd(buf);
1737    }
1738  } else {
1739    // stdin buffer is first so we can just use curbuf
1740    set_buflisted(true);
1741    // Create memfile and read from stdin.
1742    open_buffer(true, NULL, 0);
1743    // stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561
1744    if (buf_is_empty(curbuf) && curbuf->b_next != NULL) {
1745      do_cmdline_cmd("silent! bnext");
1746      do_cmdline_cmd("silent! bwipeout 1");
1747    }
1748  }
1749
1750  no_wait_return = false;
1751  msg_didany = save_msg_didany;
1752  TIME_MSG("reading stdin");
1753  check_swap_exists_action();
1754}
1755
1756// Create the requested number of windows and edit buffers in them.
1757// Also does recovery if "recoverymode" set.
1758static void create_windows(mparm_T *parmp)
1759{
1760  // Create the number of windows that was requested.
1761  if (parmp->window_count == -1) {      // was not set
1762    parmp->window_count = 1;
1763  }
1764  if (parmp->window_count == 0) {
1765    parmp->window_count = GARGCOUNT;
1766  }
1767  if (parmp->window_count > 1) {
1768    // Don't change the windows if there was a command in vimrc that
1769    // already split some windows
1770    if (parmp->window_layout == 0) {
1771      parmp->window_layout = WIN_HOR;
1772    }
1773    if (parmp->window_layout == WIN_TABS) {
1774      parmp->window_count = make_tabpages(parmp->window_count);
1775      TIME_MSG("making tab pages");
1776    } else if (firstwin->w_next == NULL || firstwin->w_next->w_floating) {
1777      parmp->window_count = make_windows(parmp->window_count, parmp->window_layout == WIN_VER);
1778      TIME_MSG("making windows");
1779    } else {
1780      parmp->window_count = win_count();
1781    }
1782  } else {
1783    parmp->window_count = 1;
1784  }
1785
1786  if (recoverymode) {                   // do recover
1787    msg_scroll = true;                  // scroll message up
1788    ml_recover(true);
1789    if (curbuf->b_ml.ml_mfp == NULL) {   // failed
1790      getout(1);
1791    }
1792    do_modelines(0);                    // do modelines
1793  } else {
1794    int done = 0;
1795    // Open a buffer for windows that don't have one yet.
1796    // Commands in the vimrc might have loaded a file or split the window.
1797    // Watch out for autocommands that delete a window.
1798    //
1799    // Don't execute Win/Buf Enter/Leave autocommands here
1800    autocmd_no_enter++;
1801    autocmd_no_leave++;
1802    // Save the window selection made by startup scripts.
1803    win_T *startup_curwin = curwin;
1804    bool dorewind = true;
1805    while (done++ < 1000) {
1806      if (dorewind) {
1807        if (parmp->window_layout == WIN_TABS) {
1808          goto_tabpage(1);
1809        } else {
1810          curwin = firstwin;
1811        }
1812      } else if (parmp->window_layout == WIN_TABS) {
1813        if (curtab->tp_next == NULL) {
1814          break;
1815        }
1816        goto_tabpage(0);
1817      } else {
1818        if (curwin->w_next == NULL) {
1819          break;
1820        }
1821        curwin = curwin->w_next;
1822      }
1823      dorewind = false;
1824      curbuf = curwin->w_buffer;
1825      if (curbuf->b_ml.ml_mfp == NULL) {
1826        // Set 'foldlevel' to 'foldlevelstart' if it's not negative..
1827        if (p_fdls >= 0) {
1828          curwin->w_p_fdl = p_fdls;
1829        }
1830        // When getting the ATTENTION prompt here, use a dialog.
1831        swap_exists_action = SEA_DIALOG;
1832        set_buflisted(true);
1833
1834        // create memfile, read file
1835        open_buffer(false, NULL, 0);
1836
1837        if (swap_exists_action == SEA_QUIT) {
1838          if (got_int || only_one_window()) {
1839            // abort selected or quit and only one window
1840            did_emsg = false;               // avoid hit-enter prompt
1841            ui_call_error_exit(1);
1842            getout(1);
1843          }
1844          // We can't close the window, it would disturb what
1845          // happens next.  Clear the file name and set the arg
1846          // index to -1 to delete it later.
1847          setfname(curbuf, NULL, NULL, false);
1848          curwin->w_arg_idx = -1;
1849          swap_exists_action = SEA_NONE;
1850        } else {
1851          handle_swap_exists(NULL);
1852        }
1853        dorewind = true;                        // start again
1854      }
1855      os_breakcheck();
1856      if (got_int) {
1857        vgetc();          // only break the file loading, not the rest
1858        break;
1859      }
1860    }
1861    if (parmp->window_layout == WIN_TABS) {
1862      goto_tabpage(1);
1863    } else if (parmp->window_count > 1 || !win_valid(startup_curwin)) {
1864      // Multiple windows mode (-o/-O), or startup_curwin was closed: use firstwin.
1865      curwin = firstwin;
1866    } else {
1867      curwin = startup_curwin;
1868    }
1869    curbuf = curwin->w_buffer;
1870    autocmd_no_enter--;
1871    autocmd_no_leave--;
1872  }
1873}
1874
1875/// If opened more than one window, start editing files in the other
1876/// windows. make_windows() has already opened the windows.
1877static void edit_buffers(mparm_T *parmp)
1878{
1879  int arg_idx;                          // index in argument list
1880  bool advance = true;
1881  win_T *win;
1882  char *p_shm_save = NULL;
1883
1884  // Don't execute Win/Buf Enter/Leave autocommands here
1885  autocmd_no_enter++;
1886  autocmd_no_leave++;
1887
1888  // When w_arg_idx is -1 remove the window (see create_windows()).
1889  if (curwin->w_arg_idx == -1) {
1890    win_close(curwin, true, false);
1891    advance = false;
1892  }
1893
1894  arg_idx = 1;
1895  for (int i = 1; i < parmp->window_count; i++) {
1896    // When w_arg_idx is -1 remove the window (see create_windows()).
1897    if (curwin->w_arg_idx == -1) {
1898      arg_idx++;
1899      win_close(curwin, true, false);
1900      advance = false;
1901      continue;
1902    }
1903
1904    if (advance) {
1905      if (parmp->window_layout == WIN_TABS) {
1906        if (curtab->tp_next == NULL) {          // just checking
1907          break;
1908        }
1909        goto_tabpage(0);
1910        // Temporarily reset 'shm' option to not print fileinfo when
1911        // loading the other buffers. This would overwrite the already
1912        // existing fileinfo for the first tab.
1913        if (i == 1) {
1914          char buf[100];
1915
1916          p_shm_save = xstrdup(p_shm);
1917          snprintf(buf, sizeof(buf), "F%s", p_shm);
1918          set_option_value_give_err(kOptShortmess, CSTR_AS_OBJ(buf), 0);
1919        }
1920      } else {
1921        if (curwin->w_next == NULL) {           // just checking
1922          break;
1923        }
1924        win_enter(curwin->w_next, false);
1925      }
1926    }
1927    advance = true;
1928
1929    // Only open the file if there is no file in this window yet (that can
1930    // happen when vimrc contains ":sall").
1931    if (curbuf == firstwin->w_buffer || curbuf->b_ffname == NULL) {
1932      curwin->w_arg_idx = arg_idx;
1933      // Edit file from arg list, if there is one.  When "Quit" selected
1934      // at the ATTENTION prompt close the window.
1935      swap_exists_did_quit = false;
1936      do_ecmd(0, arg_idx < GARGCOUNT
1937              ? alist_name(&GARGLIST[arg_idx])
1938              : NULL, NULL, NULL, ECMD_LASTL, ECMD_HIDE, curwin);
1939      if (swap_exists_did_quit) {
1940        // abort or quit selected
1941        if (got_int || only_one_window()) {
1942          // abort selected and only one window
1943          did_emsg = false;             // avoid hit-enter prompt
1944          ui_call_error_exit(1);
1945          getout(1);
1946        }
1947        win_close(curwin, true, false);
1948        advance = false;
1949      }
1950      if (arg_idx == GARGCOUNT - 1) {
1951        arg_had_last = true;
1952      }
1953      arg_idx++;
1954    }
1955    os_breakcheck();
1956    if (got_int) {
1957      vgetc();            // only break the file loading, not the rest
1958      break;
1959    }
1960  }
1961
1962  if (p_shm_save != NULL) {
1963    set_option_value_give_err(kOptShortmess, CSTR_AS_OBJ(p_shm_save), 0);
1964    xfree(p_shm_save);
1965  }
1966
1967  if (parmp->window_layout == WIN_TABS) {
1968    goto_tabpage(1);
1969  }
1970  autocmd_no_enter--;
1971
1972  // make the first window the current window
1973  win = (parmp->window_count > 1) ? firstwin : curwin;
1974  // Avoid making a preview window the current window.
1975  while (win->w_p_pvw) {
1976    win = win->w_next;
1977    if (win == NULL) {
1978      win = firstwin;
1979      break;
1980    }
1981  }
1982  win_enter(win, false);
1983
1984  autocmd_no_leave--;
1985  TIME_MSG("editing files in windows");
1986  if (parmp->window_count > 1 && parmp->window_layout != WIN_TABS) {
1987    win_equal(curwin, false, 'b');      // adjust heights
1988  }
1989}
1990
1991// Execute the commands from --cmd arguments "cmds[cnt]".
1992static void exe_pre_commands(mparm_T *parmp)
1993{
1994  char **cmds = parmp->pre_commands;
1995  int cnt = parmp->n_pre_commands;
1996  ESTACK_CHECK_DECLARATION;
1997
1998  if (cnt <= 0) {
1999    return;
2000  }
2001
2002  curwin->w_cursor.lnum = 0;     // just in case..
2003  estack_push(ETYPE_ARGS, _("pre-vimrc command line"), 0);
2004  ESTACK_CHECK_SETUP;
2005  current_sctx.sc_sid = SID_CMDARG;
2006  for (int i = 0; i < cnt; i++) {
2007    do_cmdline_cmd(cmds[i]);
2008  }
2009  ESTACK_CHECK_NOW;
2010  estack_pop();
2011  current_sctx.sc_sid = 0;
2012  TIME_MSG("--cmd commands");
2013}
2014
2015// Execute "+", "-c" and "-S" arguments.
2016static void exe_commands(mparm_T *parmp)
2017{
2018  ESTACK_CHECK_DECLARATION;
2019
2020  // We start commands on line 0, make "vim +/pat file" match a
2021  // pattern on line 1.  But don't move the cursor when an autocommand
2022  // with g`" was used.
2023  msg_scroll = true;
2024  if (parmp->tagname == NULL && curwin->w_cursor.lnum <= 1) {
2025    curwin->w_cursor.lnum = 0;
2026  }
2027  estack_push(ETYPE_ARGS, "command line", 0);
2028  ESTACK_CHECK_SETUP;
2029  current_sctx.sc_sid = SID_CARG;
2030  current_sctx.sc_seq = 0;
2031  for (int i = 0; i < parmp->n_commands; i++) {
2032    do_cmdline_cmd(parmp->commands[i]);
2033    if (parmp->cmds_tofree[i]) {
2034      xfree(parmp->commands[i]);
2035    }
2036  }
2037  ESTACK_CHECK_NOW;
2038  estack_pop();
2039  current_sctx.sc_sid = 0;
2040  if (curwin->w_cursor.lnum == 0) {
2041    curwin->w_cursor.lnum = 1;
2042  }
2043
2044  msg_scroll = false;
2045
2046  // When started with "-q errorfile" jump to first error again.
2047  if (parmp->edit_type == EDIT_QF) {
2048    qf_jump(NULL, 0, 0, false);
2049  }
2050  TIME_MSG("executing command arguments");
2051}
2052
2053/// Source system-wide vimrc if built with one defined
2054///
2055/// Does one of the following things, stops after whichever succeeds:
2056///
2057/// 1. Source system vimrc file from $XDG_CONFIG_DIRS/$NVIM_APPNAME/sysinit.vim
2058/// 2. Source system vimrc file from $VIM
2059static void do_system_initialization(void)
2060{
2061  char *const config_dirs = stdpaths_get_xdg_var(kXDGConfigDirs);
2062  if (config_dirs != NULL) {
2063    const void *iter = NULL;
2064    const char *appname = get_appname(false);
2065    size_t appname_len = strlen(appname);
2066    const char sysinit_suffix[] = {
2067      PATHSEP,
2068      's', 'y', 's', 'i', 'n', 'i', 't', '.', 'v', 'i', 'm', NUL
2069    };
2070    do {
2071      const char *dir;
2072      size_t dir_len;
2073      iter = vim_env_iter(':', config_dirs, iter, &dir, &dir_len);
2074      if (dir == NULL || dir_len == 0) {
2075        break;
2076      }
2077      size_t path_len = dir_len + 1 + appname_len + sizeof(sysinit_suffix);
2078      char *vimrc = xmalloc(path_len);
2079      memcpy(vimrc, dir, dir_len);
2080      if (vimrc[dir_len - 1] != PATHSEP) {
2081        vimrc[dir_len] = PATHSEP;
2082        dir_len += 1;
2083      }
2084      memcpy(vimrc + dir_len, appname, appname_len);
2085      memcpy(vimrc + dir_len + appname_len, sysinit_suffix, sizeof(sysinit_suffix));
2086      if (do_source(vimrc, false, DOSO_NONE, NULL) != FAIL) {
2087        xfree(vimrc);
2088        xfree(config_dirs);
2089        return;
2090      }
2091      xfree(vimrc);
2092    } while (iter != NULL);
2093    xfree(config_dirs);
2094  }
2095
2096#ifdef SYS_VIMRC_FILE
2097  // Get system wide defaults, if the file name is defined.
2098  do_source(SYS_VIMRC_FILE, false, DOSO_NONE, NULL);
2099#endif
2100}
2101
2102/// Source vimrc or do other user initialization
2103///
2104/// Does one of the following things, stops after whichever succeeds:
2105///
2106/// 1. Execution of VIMINIT environment variable.
2107/// 2. Sourcing user config files ($XDG_CONFIG_HOME/$NVIM_APPNAME/init{,/*}.lua).
2108/// 3. Execution of EXINIT environment variable.
2109///
2110/// @return True if it is needed to attempt to source exrc file according to
2111///         'exrc' option definition.
2112static bool do_user_initialization(void)
2113  FUNC_ATTR_WARN_UNUSED_RESULT
2114{
2115  bool do_exrc = p_exrc;
2116  if (execute_env("VIMINIT") == OK) {
2117    do_exrc = p_exrc;
2118    return do_exrc;
2119  }
2120
2121  char *init_lua_path = stdpaths_user_conf_subpath("init.lua");
2122
2123  // init.lua
2124  if (os_path_exists(init_lua_path)
2125      && do_source(init_lua_path, false, DOSO_VIMRC, NULL)) {
2126    xfree(init_lua_path);
2127
2128    char *user_conf_path = stdpaths_user_conf();
2129    do_config_initialization(user_conf_path);
2130    xfree(user_conf_path);
2131
2132    do_exrc = p_exrc;
2133    return do_exrc;
2134  }
2135  xfree(init_lua_path);
2136
2137  char *const config_dirs = stdpaths_get_xdg_var(kXDGConfigDirs);
2138  if (config_dirs != NULL) {
2139    const char *appname = get_appname(false);
2140    size_t appname_len = strlen(appname);
2141
2142    const void *iter = NULL;
2143    do {
2144      const char *dir;
2145      size_t dir_len;
2146      iter = vim_env_iter(':', config_dirs, iter, &dir, &dir_len);
2147      if (dir == NULL || dir_len == 0) {
2148        break;
2149      }
2150
2151      // Build: <xdg_dir>/<appname>/init.lua
2152      const char init_lua_suffix[] = { PATHSEP, 'i', 'n', 'i', 't', '.', 'l', 'u', 'a', NUL };
2153      size_t init_lua_len = dir_len + 1 + appname_len + sizeof(init_lua_suffix);
2154      char *init_lua = xmalloc(init_lua_len);
2155      memcpy(init_lua, dir, dir_len);
2156      init_lua[dir_len] = PATHSEP;
2157      memcpy(init_lua + dir_len + 1, appname, appname_len);
2158      memcpy(init_lua + dir_len + 1 + appname_len, init_lua_suffix, sizeof(init_lua_suffix));
2159
2160      if (os_path_exists(init_lua)
2161          && do_source(init_lua, true, DOSO_VIMRC, NULL)) {
2162        do_config_initialization(dir);
2163        xfree(init_lua);
2164        xfree(config_dirs);
2165        do_exrc = p_exrc;
2166        return do_exrc;
2167      }
2168      xfree(init_lua);
2169    } while (iter != NULL);
2170    xfree(config_dirs);
2171  }
2172
2173  if (execute_env("EXINIT") == OK) {
2174    do_exrc = p_exrc;
2175    return do_exrc;
2176  }
2177  return do_exrc;
2178}
2179
2180void do_config_initialization(char *const user_conf_path)
2181{
2182  char *const init_pattern = "init/**/*";
2183  source_in_path_vim_lua(user_conf_path, init_pattern, DIP_ALL);
2184}
2185
2186// Read initialization commands from ".nvim.lua", ".nvimrc", or ".exrc" in
2187// current directory and all parent directories.  This is only done if the 'exrc'
2188// option is set. Only do this if VIMRC_FILE is not the same as vimrc file
2189// sourced in do_user_initialization.
2190static void do_exrc_initialization(void)
2191{
2192  lua_State *const L = get_global_lstate();
2193  assert(L);
2194
2195  lua_getglobal(L, "require");
2196  lua_pushstring(L, "vim._core.exrc");
2197  if (nlua_pcall(L, 1, 0)) {
2198    fprintf(stderr, "%s\n", lua_tostring(L, -1));
2199  }
2200}
2201
2202/// Source startup scripts
2203static void source_startup_scripts(const mparm_T *const parmp)
2204  FUNC_ATTR_NONNULL_ALL
2205{
2206  // If -u given, use only the initializations from that file and nothing else.
2207  if (parmp->use_vimrc != NULL) {
2208    if (strequal(parmp->use_vimrc, "NONE") || strequal(parmp->use_vimrc, "NORC")) {
2209      // Do nothing.
2210    } else {
2211      if (do_source(parmp->use_vimrc, false, DOSO_NONE, NULL) != OK) {
2212        semsg(_(e_cannot_read_from_str_2), parmp->use_vimrc);
2213      }
2214    }
2215  } else if (!silent_mode) {
2216    do_system_initialization();
2217
2218    if (do_user_initialization()) {
2219      do_exrc_initialization();
2220    }
2221  }
2222  TIME_MSG("sourcing vimrc file(s)");
2223}
2224
2225/// Get an environment variable, and execute it as Ex commands.
2226///
2227/// @param env         environment variable to execute
2228///
2229/// @return FAIL if the environment variable was not executed,
2230///         OK otherwise.
2231static int execute_env(char *env)
2232  FUNC_ATTR_NONNULL_ALL
2233{
2234  ESTACK_CHECK_DECLARATION;
2235  char *initstr = os_getenv(env);
2236  if (initstr == NULL) {
2237    return FAIL;
2238  }
2239
2240  estack_push(ETYPE_ENV, env, 0);
2241  ESTACK_CHECK_SETUP;
2242  const sctx_T save_current_sctx = current_sctx;
2243  current_sctx.sc_sid = SID_ENV;
2244  current_sctx.sc_seq = 0;
2245  current_sctx.sc_lnum = 0;
2246  do_cmdline_cmd(initstr);
2247
2248  ESTACK_CHECK_NOW;
2249  estack_pop();
2250  current_sctx = save_current_sctx;
2251
2252  xfree(initstr);
2253  return OK;
2254}
2255
2256/// Prints a message of the form "{msg1}: {msg2}: {msg3}", then exits with code 1.
2257///
2258/// @param msg1  error message
2259/// @param msg2  extra message, or NULL
2260/// @param msg3  extra message, or NULL
2261static void mainerr(const char *msg1, const char *msg2, const char *msg3)
2262  FUNC_ATTR_NORETURN
2263{
2264  print_mainerr(msg1, msg2, msg3);
2265  os_exit(1);
2266}
2267
2268static void print_mainerr(const char *msg1, const char *msg2, const char *msg3)
2269{
2270  char *prgname = path_tail(argv0);
2271
2272  signal_stop();              // kill us with CTRL-C here, if you like
2273
2274  fprintf(stderr, "%s: %s", prgname, _(msg1));
2275  if (msg2 != NULL) {
2276    fprintf(stderr, ": \"%s\"", msg2);
2277  }
2278  if (msg3 != NULL) {
2279    fprintf(stderr, ": \"%s\"", msg3);
2280  }
2281  fprintf(stderr, _("\nMore info with \""));
2282  fprintf(stderr, "%s -h\"\n", prgname);
2283}
2284
2285/// Prints version information for "nvim -v" or "nvim --version".
2286static void version(void)
2287{
2288  // TODO(bfred): not like this?
2289  nlua_init(NULL, 0, -1);
2290  info_message = true;  // use stdout, not stderr
2291  list_version();
2292  msg_putchar('\n');
2293  msg_didout = false;
2294}
2295
2296/// Prints help message for "nvim -h" or "nvim --help".
2297static void usage(void)
2298{
2299  signal_stop();              // kill us with CTRL-C here, if you like
2300
2301  printf(_("Usage:\n"));
2302  printf(_("  nvim [options] [file ...]\n"));
2303  printf(_("\nOptions:\n"));
2304  printf(_("  --cmd <cmd>           Execute <cmd> before any config\n"));
2305  printf(_("  +<cmd>, -c <cmd>      Execute <cmd> after config and first file\n"));
2306  printf(_("  -l <script> [args...] Execute Lua <script> (with optional args)\n"));
2307  printf(_("  -S <session>          Source <session> after loading the first file\n"));
2308  printf(_("  -s <scriptin>         Read Normal mode commands from <scriptin>\n"));
2309  printf(_("  -u <config>           Use this config file\n"));
2310  printf("\n");
2311  printf(_("  -d                    Diff mode\n"));
2312  printf(_("  -es, -Es              Silent (batch) mode\n"));
2313  printf(_("  -h, --help            Print this help message\n"));
2314  printf(_("  -i <shada>            Use this shada file\n"));
2315  printf(_("  -n                    No swap file, use memory only\n"));
2316  printf(_("  -o[N]                 Open N windows (default: one per file)\n"));
2317  printf(_("  -O[N]                 Open N vertical windows (default: one per file)\n"));
2318  printf(_("  -p[N]                 Open N tab pages (default: one per file)\n"));
2319  printf(_("  -R                    Read-only (view) mode\n"));
2320  printf(_("  -v, --version         Print version information\n"));
2321  printf(_("  -V[N][file]           Verbose [level][file]\n"));
2322  printf("\n");
2323  printf(_("  --                    Only file names after this\n"));
2324  printf(_("  --api-info            Write msgpack-encoded API metadata to stdout\n"));
2325  printf(_("  --clean               \"Factory defaults\" (skip user config and plugins, shada)\n"));
2326  printf(_("  --embed               Use stdin/stdout as a msgpack-rpc channel\n"));
2327  printf(_("  --headless            Don't start a user interface\n"));
2328  printf(_("  --listen <address>    Serve RPC API from this address\n"));
2329  printf(_("  --remote[-subcommand] Execute commands remotely on a server\n"));
2330  printf(_("  --server <address>    Connect to this Nvim server\n"));
2331  printf(_("  --startuptime <file>  Write startup timing messages to <file>\n"));
2332  printf(_("\nSee \":help startup-options\" for all options.\n"));
2333}
2334
2335// Check the result of the ATTENTION dialog:
2336// When "Quit" selected, exit Vim.
2337// When "Recover" selected, recover the file.
2338static void check_swap_exists_action(void)
2339{
2340  if (swap_exists_action == SEA_QUIT) {
2341    ui_call_error_exit(1);
2342    getout(1);
2343  }
2344  handle_swap_exists(NULL);
2345}
2346
2347#ifdef ENABLE_ASAN_UBSAN
2348const char *__ubsan_default_options(void)
2349{
2350  return "print_stacktrace=1";
2351}
2352
2353const char *__asan_default_options(void)
2354{
2355  return "handle_abort=1,handle_sigill=1";
2356}
2357#endif