robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 130WIN_HOR = 1 ,// "-o" horizontally split windows 131WIN_VER = 2 ,// "-O" vertically split windows 132WIN_TABS = 3 ,// "-p" windows on tab pages 133}; 134 135// Values for edit_type. 136enum { 137EDIT_NONE = 0 ,// no edit type yet 138EDIT_FILE = 1 ,// file name argument[s] given, use argument list 139EDIT_STDIN = 2 ,// read file from stdin 140EDIT_TAG = 3 ,// tag name argument given, use tagname 141EDIT_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 = 156N_ ("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments" ); 157 158void event_init (void ) 159{ 160loop_init (& main_loop ,NULL ); 161env_init (); 162resize_events = multiqueue_new_child (main_loop .events ); 163 164autocmd_init (); 165signal_init (); 166// mspgack-rpc initialization 167channel_init (); 168terminal_init (); 169ui_init (); 170TIME_MSG ("event init" ); 171} 172 173/// @returns false if main_loop could not be closed gracefully 174static bool event_teardown (void ) 175{ 176if (!main_loop .events ) { 177return true; 178 } 179 180multiqueue_process_events (main_loop .events ); 181loop_poll_events (& main_loop ,0 );// Drain thread_events, fast_events. 182server_teardown (); 183channel_teardown (); 184proc_teardown (& main_loop ); 185timer_teardown (); 186signal_teardown (); 187terminal_teardown (); 188 189return loop_close (& main_loop , true); 190} 191 192/// Performs early initialization. 193static void early_init (mparm_T * paramp ) 194{ 195os_hint_priority (); 196estack_init (); 197cmdline_init (); 198eval_init ();// init global variables 199set_vim_var_nr (VV_STARTTIME , (varnumber_T )os_realtime ()); 200init_path (argv0 ?argv0 :"nvim" ); 201init_normal_cmds ();// Init the table of Normal mode commands. 202runtime_init (); 203highlight_init (); 204mc_init (); 205 206#ifdef MSWIN 207OSVERSIONINFO ovi ; 208ovi .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) 213GetVersionEx (& ovi ); 214# else 215GetVersionEx (& ovi ); 216# endif 217snprintf (windowsVersion ,sizeof (windowsVersion ),"%d.%d" , 218 (int )ovi .dwMajorVersion , (int )ovi .dwMinorVersion ); 219#endif 220 221TIME_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! 226init_locale (); 227 228// tabpage local options (p_ch) must be set before allocating first tabpage. 229set_init_tablocal (); 230 231// Allocate the first tabpage, window and buffer. 232win_alloc_first (); 233TIME_MSG ("init first window" ); 234 235alist_init (& global_alist );// Init the argument list to empty. 236global_alist .id = 0 ; 237 238// Set the default values for the options. 239// First find out the home directory, needed to expand "~" in options. 240init_homedir ();// find real value of $HOME 241set_init_1 (paramp != NULL ?paramp -> clean : false); 242log_init (); 243TIME_MSG ("inits 1" ); 244 245set_lang_var ();// set v:lang and v:ctype 246 247// initialize quickfix list 248qf_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{ 258argv0 = argv [0 ]; 259TO_SLASH (argv0 ); 260 261if (!appname_is_valid ()) { 262fprintf (stderr ,"$NVIM_APPNAME must be a name or relative path.\n" ); 263exit (1 ); 264 } 265 266char * fname = NULL ;// file name from command line 267mparm_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. 272init_params (& params ,argc ,argv ); 273 274init_startuptime (& params ); 275 276// Need to find "--clean" before actually parsing arguments. 277for (int i = 1 ;i < params .argc ;i ++ ) { 278if (STRICMP (params .argv [i ],"--clean" )== 0 ) { 279params .clean = true; 280break ; 281 } 282 } 283 284event_init (); 285 286early_init (& params ); 287 288set_argv_var (argv ,argc );// set v:argv 289 290// Check if we have an interactive window. 291check_and_set_isatty (& params ); 292 293// Process the command line arguments. File names are put in the global 294// argument list "global_alist". 295command_line_scan (& params ); 296 297set_argf_var (); 298 299nlua_init (argv ,argc ,params .lua_arg0 ); 300TIME_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 306int startup_stderr_fd = -1 ; 307if (embedded_mode ) { 308startup_stderr_fd = os_dup_cloexec (STDERR_FILENO ); 309 } 310#endif 311 312if (embedded_mode ) { 313const char * err ; 314if (!channel_from_stdio (true,CALLBACK_READER_INIT ,& err )) { 315abort (); 316 } 317 } 318 319if (GARGCOUNT > 0 ) { 320fname = get_fname (& params ); 321 } 322 323// Recovery mode without a file name: List swap files. 324// In this case, no UI is needed. 325if (recoverymode && fname == NULL ) { 326headless_mode = true; 327 } 328 329#ifdef MSWIN 330// on windows we use CONIN special file, thus we don't know this yet. 331bool has_term = true; 332#else 333bool has_term = (stdin_isatty || stdout_isatty || stderr_isatty ); 334#endif 335bool use_builtin_ui = (has_term && !headless_mode && !embedded_mode && !silent_mode ); 336 337if (params .remote ) { 338remote_request (& params ,params .remote ,params .server_addr ,argc ,argv , 339use_builtin_ui ); 340 } 341 342bool remote_ui = (ui_client_channel_id != 0 ); 343 344if (use_builtin_ui && !remote_ui ) { 345ui_client_forward_stdin = !stdin_isatty ; 346uint64_t rv = ui_client_start_server (get_vim_var_str (VV_PROGPATH ), 347 (size_t )params .argc ,params .argv ); 348if (!rv ) { 349fprintf (stderr ,"Failed to start Nvim server!\n" ); 350os_exit (1 ); 351 } 352ui_client_channel_id = rv ; 353 } 354 355// NORETURN: Start builtin UI client. 356if (ui_client_channel_id ) { 357ui_client_run ();// NORETURN 358 } 359assert (!ui_client_channel_id && !use_builtin_ui ); 360// Nvim server... 361 362if (!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. 366if (startup_stderr_fd >=0 ) { 367dup2 (startup_stderr_fd ,STDERR_FILENO ); 368close (startup_stderr_fd ); 369startup_stderr_fd = -1 ; 370 } 371#endif 372mainerr (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. 378if (startup_stderr_fd >=0 ) { 379close (startup_stderr_fd ); 380startup_stderr_fd = -1 ; 381 } 382#endif 383 384TIME_MSG ("expanding arguments" ); 385 386if (params .diff_mode && params .window_count == -1 ) { 387params .window_count = 0 ;// open up to 3 windows 388 } 389// Don't redraw until much later. 390RedrawingDisabled ++ ; 391 392setbuf (stdout ,NULL );// NOLINT(bugprone-unsafe-functions) 393 394full_screen = !silent_mode ; 395 396// Set the default values for the options that use Rows and Columns. 397win_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. 400if (params .diff_mode ) { 401diff_win_options (firstwin , false); 402 } 403 404assert (p_ch >=0 && Rows >=p_ch && Rows - p_ch <=INT_MAX ); 405cmdline_row = Rows - (int )p_ch ; 406msg_row = cmdline_row ; 407default_grid_alloc ();// allocate screen buffers 408set_init_2 (headless_mode ); 409TIME_MSG ("inits 2" ); 410 411msg_scroll = true; 412no_wait_return = true; 413 414init_highlight (true, false);// Default highlight groups. 415ui_comp_syn_init (); 416TIME_MSG ("init highlight" ); 417 418// Set the break level after the terminal is initialized. 419debug_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, …). 423bool use_remote_ui = (embedded_mode && !headless_mode ); 424if (use_remote_ui ) { 425TIME_MSG ("waiting for UI" ); 426remote_ui_wait_for_attach (); 427TIME_MSG ("done waiting for UI" ); 428firstwin -> w_prev_height = firstwin -> w_height ;// may have changed 429 } 430 431// prepare screen now 432starting = NO_BUFFERS ; 433screenclear (); 434win_new_screensize (); 435TIME_MSG ("clear screen" ); 436 437// Handle "foo | nvim". EDIT_FILE may be overwritten now. #6299 438if (edit_stdin (& params )) { 439params .edit_type = EDIT_STDIN ; 440 } 441 442if (params .scriptin ) { 443if (!open_scriptin (params .scriptin )) { 444os_exit (2 ); 445 } 446 } 447if (params .scriptout ) { 448scriptout = os_fopen (params .scriptout ,params .scriptout_append ?APPENDBIN :WRITEBIN ); 449if (scriptout == NULL ) { 450fprintf (stderr ,_ ("Cannot open for script output: \"" )); 451fprintf (stderr ,"%s\"\n" ,params .scriptout ); 452os_exit (2 ); 453 } 454 } 455 456nlua_init_defaults (); 457 458TIME_MSG ("init default mappings & autocommands" ); 459 460bool 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. 465p_lpl = vimrc_none ?params .clean :p_lpl ; 466 467// Execute --cmd arguments. 468exe_pre_commands (& params ); 469 470if (!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). 474filetype_plugin_enable (); 475 } 476 477// Source startup scripts. 478source_startup_scripts (& params ); 479 480// If using the runtime (-u is not NONE), enable syntax & filetype plugins. 481if (!vimrc_none || params .clean ) { 482// Sources filetype.lua unless the user explicitly disabled it with :filetype off. 483filetype_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. 486syn_maybe_enable (); 487 } 488 489set_vim_var_nr (VV_VIM_DID_INIT ,1 ); 490apply_autocmds (EVENT_VIMINIT ,NULL ,NULL , false,curbuf ); 491TIME_MSG ("VimInit autocommands" ); 492 493// Read all the plugin files. 494load_plugins (); 495 496// Decide about window layout for diff mode after reading vimrc. 497set_window_layout (& params ); 498 499// "nvim -r" (recovery mode) without a file name: List swap files. 500if (recoverymode && fname == NULL ) { 501typval_T items_tv ; 502tv_list_alloc_ret (& items_tv ,0 ); 503recover_names (NULL , false,items_tv .vval .v_list ); 504typval_T lua_args []= {items_tv , { .v_type = VAR_UNKNOWN } }; 505nlua_call_typval ("vim._core.swapfile" ,"list_swaps" ,lua_args ,NULL ); 506tv_clear (& items_tv ); 507os_exit (0 ); 508 } 509 510// Set some option defaults after reading vimrc files. 511set_init_3 (); 512TIME_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. 516if (params .no_swap_file ) { 517p_uc = 0 ; 518 } 519 520// XXX: Minimize 'updatetime' for -es/-Es. #7679 521if (silent_mode ) { 522p_ut = 1 ; 523 } 524 525// Read in registers, history etc, from the ShaDa file. 526// This is where v:oldfiles gets filled. 527if (* p_shada != NUL ) { 528shada_read_everything (NULL , false, true); 529TIME_MSG ("reading ShaDa" ); 530 } 531// It's better to make v:oldfiles an empty list than NULL. 532if (get_vim_var_list (VV_OLDFILES )== NULL ) { 533set_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. 538handle_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// 545starting = NO_BUFFERS ; 546no_wait_return = false; 547msg_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... 557if (params .edit_type == EDIT_STDIN && !recoverymode ) { 558read_stdin (); 559 } 560 561setmouse ();// may start using the mouse 562 563redraw_later (curwin ,UPD_VALID ); 564 565no_wait_return = true; 566 567// Create the requested number of windows and edit buffers in them. 568// Also does recovery if "recoverymode" set. 569create_windows (& params ); 570TIME_MSG ("opening buffers" ); 571 572// Clear v:swapcommand 573set_vim_var_string (VV_SWAPCOMMAND ,NULL ,-1 ); 574 575// Ex starts at last line of the file. 576if (params .exmode ) { 577curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 578 } 579 580apply_autocmds (EVENT_BUFENTER ,NULL ,NULL , false,curbuf ); 581TIME_MSG ("BufEnter autocommands" ); 582setpcmark (); 583 584// When started with "-q errorfile" jump to first error now. 585if (params .edit_type == EDIT_QF ) { 586qf_jump (NULL ,0 ,0 , false); 587TIME_MSG ("jump to first error" ); 588 } 589 590// If opened more than one window, start editing files in the other 591// windows. 592edit_buffers (& params ); 593 594if (params .diff_mode ) { 595// set options in each window for "nvim -d". 596FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 597if (!wp -> w_arg_idx_invalid ) { 598diff_win_options (wp , true); 599 } 600 } 601 } 602 603// Shorten any of the filenames, but only when absolute. 604shorten_fnames (false); 605 606// Need to jump to the tag before executing the '-c command'. 607// Makes "vim -c '/return' -t main" work. 608handle_tag (params .tagname ); 609 610// Execute any "+", "-c" and "-S" arguments. 611if (params .n_commands > 0 ) { 612exe_commands (& params ); 613 } 614 615starting = 0 ; 616 617RedrawingDisabled = 0 ; 618redraw_all_later (UPD_NOT_VALID ); 619no_wait_return = false; 620 621// 'autochdir' has been postponed. 622do_autochdir (); 623 624set_vim_var_nr (VV_VIM_DID_ENTER ,1 ); 625apply_autocmds (EVENT_VIMENTER ,NULL ,NULL , false,curbuf ); 626TIME_MSG ("VimEnter autocommands" ); 627if (use_remote_ui ) { 628do_autocmd_uienter_all (); 629TIME_MSG ("UIEnter autocommands" ); 630 } 631 632#ifdef MSWIN 633if (use_remote_ui ) { 634os_icon_init (); 635 } 636os_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. 643set_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. 647if (curwin -> w_p_diff && curwin -> w_p_scb ) { 648update_topline (curwin ); 649check_scrollbind (0 ,0 ); 650TIME_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. 655if (restart_edit != 0 ) { 656stuffcharReadbuff (K_NOP ); 657 } 658 659// WORKAROUND(mhi): #3023 660if (cb_flags & (kOptCbFlagUnnamed |kOptCbFlagUnnamedplus )) { 661eval_has_provider ("clipboard" , false); 662 } 663 664if (params .luaf != NULL ) { 665// Like "--cmd", "+", "-c" and "-S", don't truncate messages. 666msg_scroll = true; 667DLOG ("executing Lua -l script" ); 668bool lua_ok = nlua_exec_file (params .luaf ); 669TIME_MSG ("executing Lua -l script" ); 670if (msg_didout ) { 671msg_putchar ('\n' ); 672msg_didout = false; 673 } 674getout (lua_ok ?0 :1 ); 675 }else if (silent_mode ) { 676// Non-interactive Ex mode (-es): vim._core.exmode.run() executes Ex commands from stdin. 677msg_scroll = true; 678no_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().) 681if (!params .input_istext && !stdin_isatty ) { 682DLOG ("executing stdin as Ex commands" ); 683typval_T args []= { { .v_type = VAR_UNKNOWN } }; 684nlua_call_typval ("vim._core.exmode" ,"run" ,args ,NULL ); 685 } 686if (msg_didout ) { 687msg_putchar ('\n' );// Terminate the last output line. 688msg_didout = false; 689 } 690getout (0 );// getout() adds `ex_exitval` for "-es". 691 } 692 693if (params .exmode ) { 694// Interactive Ex mode (-e/-E): cmdwin REPL. #40962 695do_cmdline_cmd ("exmode" ); 696 } 697 698TIME_MSG ("before starting main loop" ); 699ILOG ("starting main loop" ); 700 701// Main loop: never returns. 702normal_enter (); 703 704#if defined(MSWIN )&& !defined(MAKE_LIB ) 705xfree (argv ); 706#endif 707return 0 ; 708} 709 710void os_exit (int r ) 711FUNC_ATTR_NORETURN 712{ 713exiting = true; 714// Avoid recursion in case SIGTERM arrives during `os_exit`. 715signal_reject_deadly (); 716 717if (ui_client_channel_id ) { 718ui_client_stop (); 719if (r == 0 ) { 720r = ui_client_exit_status ; 721 } 722 }else { 723ui_flush (); 724ui_call_stop (); 725 } 726 727if (!event_teardown ()&& r == 0 ) { 728r = 1 ;// Exit with error if main_loop did not teardown gracefully. 729 } 730if (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. 735if (stdout_isatty ) { 736tcdrain (STDOUT_FILENO ); 737 } 738if (stderr_isatty ) { 739tcdrain (STDERR_FILENO ); 740 } 741#endif 742 }else { 743ml_close_all (true);// remove all memfiles 744 } 745 746ILOG ("Nvim exit: %d" ,r ); 747 748#ifdef EXITFREE 749free_all_mem (); 750#endif 751 752exit (r ); 753} 754 755/// Exit properly 756void getout (int exitval ) 757FUNC_ATTR_NORETURN 758{ 759assert (!ui_client_channel_id ); 760exiting = true; 761 762// make sure startuptimes have been flushed 763time_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. 767if (exmode_active ) { 768exitval += ex_exitval ; 769 } 770 771set_vim_var_type (VV_EXITING ,VAR_NUMBER ); 772set_vim_var_nr (VV_EXITING ,exitval ); 773 774// Set v:exitreason if not already set (e.g. by :restart). 775if (* get_vim_var_str (VV_EXITREASON )== NUL ) { 776set_vim_var_string (VV_EXITREASON ,S_LEN ("quit" )); 777 } 778 779// Invoked all ":defer" functions in the function stack. 780invoke_all_defer (); 781 782// Optionally print hashtable efficiency. 783hash_debug_results (); 784 785if (v_dying <=1 ) { 786const tabpage_T * next_tp ; 787 788// Trigger BufWinLeave for all windows, but only once per buffer. 789for (const tabpage_T * tp = first_tabpage ;tp != NULL ;tp = next_tp ) { 790next_tp = tp -> tp_next ; 791FOR_ALL_WINDOWS_IN_TAB (wp ,tp ) { 792if (wp -> w_buffer == NULL || !buf_valid (wp -> w_buffer )) { 793// Autocmd must have close the buffer already, skip. 794continue ; 795 } 796 797buf_T * buf = wp -> w_buffer ; 798if (buf_get_changedtick (buf )!= -1 ) { 799bufref_T bufref ; 800 801set_bufref (& bufref ,buf ); 802apply_autocmds_win (EVENT_BUFWINLEAVE ,buf -> b_fname ,buf -> b_fname , false,buf ,wp ); 803if (bufref_valid (& bufref )) { 804buf_set_changedtick (buf ,-1 );// note that we did it already 805 } 806// start all over, autocommands may mess up the lists 807next_tp = first_tabpage ; 808break ; 809 } 810 } 811 } 812 813// Trigger BufUnload for buffers that are loaded 814FOR_ALL_BUFFERS (buf ) { 815if (buf -> b_ml .ml_mfp != NULL ) { 816bufref_T bufref ; 817set_bufref (& bufref ,buf ); 818apply_autocmds (EVENT_BUFUNLOAD ,buf -> b_fname ,buf -> b_fname , false,buf ); 819if (!bufref_valid (& bufref )) { 820// Autocmd deleted the buffer. 821break ; 822 } 823 } 824 } 825 826int unblock = 0 ; 827// deathtrap() blocks autocommands, but we do want to trigger 828// VimLeavePre. 829if (is_autocmd_blocked ()) { 830unblock_autocmds (); 831unblock ++ ; 832 } 833apply_autocmds (EVENT_VIMLEAVEPRE ,NULL ,NULL , false,curbuf ); 834if (unblock ) { 835block_autocmds (); 836 } 837 } 838 839if ( 840#ifdef EXITFREE 841 !entered_free_all_mem && 842#endif 843p_shada && * p_shada != NUL ) { 844// Write out the registers, history, marks etc, to the ShaDa file 845shada_write_file (NULL , false); 846 } 847 848if (v_dying <=1 ) { 849int unblock = 0 ; 850 851// deathtrap() blocks autocommands, but we do want to trigger VimLeave. 852if (is_autocmd_blocked ()) { 853unblock_autocmds (); 854unblock ++ ; 855 } 856apply_autocmds (EVENT_VIMLEAVE ,NULL ,NULL , false,curbuf ); 857if (unblock ) { 858block_autocmds (); 859 } 860 } 861 862profile_dump (); 863 864if (did_emsg ) { 865// give the user a chance to read the (error) message 866no_wait_return = false; 867// TODO(justinmk): this may call getout(0), clobbering exitval... 868wait_return (false); 869 } 870 871// Apply 'titleold'. 872if (p_title && * p_titleold != NUL ) { 873ui_call_set_title (cstr_as_string (p_titleold )); 874 } 875 876if (garbage_collect_at_exit ) { 877garbage_collect (false); 878 } 879 880#ifdef MSWIN 881// Restore Windows console icon before exiting. 882os_icon_reset (); 883os_title_reset (); 884#endif 885 886os_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 ) 894FUNC_ATTR_NORETURN 895{ 896// 'true' when we are sure to exit, e.g., after a deadly signal 897static bool really_exiting = false; 898 899// Prevent repeated calls into this method. 900if ( really_exiting ) { 901exit ( 2 ); 902} 903 904really_exiting = true; 905// Set this now, to neuter a stray `exit_event` on the event-loop. #39675 906exiting = true; 907// Ignore SIGHUP while we are already exiting. #9274 908signal_reject_deadly (); 909 910if ( ui_client_channel_id ) { 911// For TUI: exit alternate screen so that the error messages can be seen. 912ui_client_stop (); 913} 914if ( errmsg != NULL && errmsg [ 0 ] != NUL ) { 915bool has_eol = '\n' == errmsg [ strlen ( errmsg ) - 1 ]; 916fprintf ( stderr , has_eol ? "%s" : "%s\n" , errmsg ); 917} 918if ( ui_client_channel_id ) { 919os_exit ( 1 ); 920} 921 922ml_close_notmod (); // close all not-modified buffers 923 924FOR_ALL_BUFFERS ( buf ) { 925if ( buf -> b_ml . ml_mfp != NULL && buf -> b_ml . ml_mfp -> mf_fname != NULL ) { 926if ( errmsg != NULL ) { 927fprintf ( stderr , "Nvim: preserving files...\n" ); 928} 929ml_sync_all (false, false, true); // preserve all swap files 930break; 931} 932} 933 934ml_close_all (false); // close all memfiles, without deleting 935 936if ( errmsg != NULL ) { 937fprintf ( stderr , "Nvim: Finished.\n" ); 938} 939 940getout ( 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 ) 956FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 957{ 958if ( ascii_isdigit ( p [ * idx ])) { 959def = atoi ( & ( p [ * idx ])); 960while ( ascii_isdigit ( p [ * idx ])) { 961* idx = * idx + 1 ; 962} 963} 964return def ; 965} 966 967static uint64_t server_connect ( char * server_addr , const char ** errmsg ) 968{ 969if ( server_addr == NULL ) { 970* errmsg = "no address specified" ; 971return 0 ; 972} 973CallbackReader on_data = CALLBACK_READER_INIT ; 974const char * error = NULL ; 975bool is_tcp = socket_address_tcp_host_end ( server_addr ) != NULL ; 976// connected to channel 977uint64_t chan = channel_connect ( is_tcp , server_addr , true, on_data , 500 , & error ); 978if ( error ) { 979* errmsg = error ; 980return 0 ; 981} 982return chan ; 983} 984 985/// Handle remote subcommands 986static void remote_request ( mparm_T * params , int remote_args , char * server_addr , int argc , 987char ** argv , bool ui_only ) 988{ 989bool is_ui = strequal ( argv [ remote_args ], "--remote-ui" ); 990if ( 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 993return; 994} 995 996const char * connect_error = NULL ; 997uint64_t chan = server_connect ( server_addr , & connect_error ); 998Object rvobj = OBJECT_INIT ; 999 1000if ( is_ui ) { 1001if (! 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. 1005dup2 ( STDOUT_FILENO , STDERR_FILENO ); 1006#endif 1007fprintf ( stderr , "Remote ui failed to start: %s\n" , connect_error ); 1008os_exit ( 1 ); 1009} else if ( strequal ( server_addr , os_getenv_noalloc ( "NVIM" ))) { 1010fprintf ( stderr , "%s" , "Cannot attach UI of :terminal child to its parent. " ); 1011fprintf ( stderr , "%s\n" , "(Unset $NVIM to skip this check)" ); 1012os_exit ( 1 ); 1013} 1014ui_client_channel_id = chan ; 1015return; 1016} 1017 1018Array args = ARRAY_DICT_INIT ; 1019kv_resize ( args , ( size_t )( argc - remote_args )); 1020for ( int t_argc = remote_args ; t_argc < argc ; t_argc ++ ) { 1021ADD_C ( args , CSTR_AS_OBJ ( argv [ t_argc ])); 1022} 1023 1024Error err = ERROR_INIT ; 1025MAXSIZE_TEMP_ARRAY ( a , 4 ); 1026ADD_C ( a , INTEGER_OBJ (( int ) chan )); 1027ADD_C ( a , CSTR_AS_OBJ ( server_addr )); 1028ADD_C ( a , CSTR_AS_OBJ ( connect_error )); 1029ADD_C ( a , ARRAY_OBJ ( args )); 1030String s = STATIC_CSTR_AS_STRING ( "return vim._cs_remote(...)" ); 1031Object o = nlua_exec ( s , NULL , a , kRetObject , NULL , & err ); 1032kv_destroy ( args ); 1033if ( ERROR_SET ( & err )) { 1034fprintf ( stderr , "%s\n" , err . msg ); 1035os_exit ( 2 ); 1036} 1037 1038if ( o . type == kObjectTypeDict ) { 1039rvobj . data . dict = o . data . dict ; 1040} else { 1041fprintf ( stderr , "vim._cs_remote returned unexpected value\n" ); 1042os_exit ( 2 ); 1043} 1044 1045TriState should_exit = kNone ; 1046TriState tabbed = kNone ; 1047 1048for ( size_t i = 0 ; i < rvobj . data . dict . size ; i ++ ) { 1049if ( strequal ( rvobj . data . dict . items [ i ]. key . data , "errmsg" )) { 1050if ( rvobj . data . dict . items [ i ]. value . type != kObjectTypeString ) { 1051fprintf ( stderr , "vim._cs_remote returned an unexpected type for 'errmsg'\n" ); 1052os_exit ( 2 ); 1053} 1054fprintf ( stderr , "%s\n" , rvobj . data . dict . items [ i ]. value . data . string . data ); 1055os_exit ( 2 ); 1056} else if ( strequal ( rvobj . data . dict . items [ i ]. key . data , "result" )) { 1057if ( rvobj . data . dict . items [ i ]. value . type != kObjectTypeString ) { 1058fprintf ( stderr , "vim._cs_remote returned an unexpected type for 'result'\n" ); 1059os_exit ( 2 ); 1060} 1061printf ( "%s" , rvobj . data . dict . items [ i ]. value . data . string . data ); 1062} else if ( strequal ( rvobj . data . dict . items [ i ]. key . data , "tabbed" )) { 1063if ( rvobj . data . dict . items [ i ]. value . type != kObjectTypeBoolean ) { 1064fprintf ( stderr , "vim._cs_remote returned an unexpected type for 'tabbed'\n" ); 1065os_exit ( 2 ); 1066} 1067tabbed = rvobj . data . dict . items [ i ]. value . data . boolean ? kTrue : kFalse ; 1068} else if ( strequal ( rvobj . data . dict . items [ i ]. key . data , "should_exit" )) { 1069if ( rvobj . data . dict . items [ i ]. value . type != kObjectTypeBoolean ) { 1070fprintf ( stderr , "vim._cs_remote returned an unexpected type for 'should_exit'\n" ); 1071os_exit ( 2 ); 1072} 1073should_exit = rvobj . data . dict . items [ i ]. value . data . boolean ? kTrue : kFalse ; 1074} 1075} 1076if ( should_exit == kNone || tabbed == kNone ) { 1077fprintf ( stderr , "vim._cs_remote didn't return a value for should_exit or tabbed, bailing\n" ); 1078os_exit ( 2 ); 1079} 1080api_free_object ( o ); 1081 1082if ( should_exit == kTrue ) { 1083os_exit ( 0 ); 1084} 1085if ( tabbed == kTrue ) { 1086params -> window_count = argc - remote_args - 1 ; 1087params -> 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{ 1095bool 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. 1101return parmp -> had_stdin_file || implicit ; 1102} 1103 1104/// Scan the command line arguments. 1105static void command_line_scan ( mparm_T * parmp ) 1106{ 1107int argc = parmp -> argc ; 1108char ** argv = parmp -> argv ; 1109int argv_idx ; // index in argv[n][] 1110bool had_minmin = false; // found "--" argument 1111bool want_argument ; // option argument with argument 1112int n ; 1113 1114argc -- ; 1115argv ++ ; 1116argv_idx = 1 ; // active option letter is argv[0][argv_idx] 1117while ( argc > 0 ) { 1118// "+" or "+{number}" or "+/{pat}" or "+{command}" argument. 1119if ( argv [ 0 ][ 0 ] == '+' && ! had_minmin ) { 1120if ( parmp -> n_commands >= MAX_ARG_CMDS ) { 1121mainerr ( err_extra_cmd , NULL , NULL ); 1122} 1123argv_idx = -1 ; // skip to next argument 1124if ( argv [ 0 ][ 1 ] == NUL ) { 1125parmp -> commands [ parmp -> n_commands ++ ] = "$" ; 1126} else { 1127parmp -> commands [ parmp -> n_commands ++ ] = & ( argv [ 0 ][ 1 ]); 1128} 1129} else if ( argv [ 0 ][ 0 ] == '-' && ! had_minmin ) { 1130// Optional argument. 1131 1132want_argument = false; 1133char c = argv [ 0 ][ argv_idx ++ ]; 1134switch ( c ) { 1135case NUL : // "nvim -" read from stdin 1136if ( parmp -> exmode ) { 1137// "nvim -e -" silent mode 1138silent_mode = true; 1139exmode_active = true; 1140parmp -> no_swap_file = true; 1141} else { 1142if ( parmp -> edit_type > EDIT_STDIN ) { 1143mainerr ( err_too_many_args , argv [ 0 ], NULL ); 1144} 1145parmp -> had_stdin_file = true; 1146parmp -> edit_type = EDIT_STDIN ; 1147} 1148argv_idx = -1 ; // skip to next argument 1149break; 1150case '-' : // "--" 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 1157if ( STRICMP ( argv [ 0 ] + argv_idx , "help" ) == 0 ) { 1158usage (); 1159os_exit ( 0 ); 1160} else if ( STRICMP ( argv [ 0 ] + argv_idx , "version" ) == 0 ) { 1161version (); 1162os_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 1169String data = api_metadata_raw (); 1170const ptrdiff_t written_bytes = os_write ( STDOUT_FILENO , data . data , data . size , false); 1171if ( written_bytes < 0 ) { 1172semsg ( _ ( "E5420: Failed to write to file: %s" ), os_strerror (( int ) written_bytes )); 1173} 1174 1175os_exit ( 0 ); 1176} else if ( STRICMP ( argv [ 0 ] + argv_idx , "headless" ) == 0 ) { 1177headless_mode = true; 1178} else if ( STRICMP ( argv [ 0 ] + argv_idx , "embed" ) == 0 ) { 1179embedded_mode = true; 1180} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "listen" , 6 ) == 0 ) { 1181want_argument = true; 1182argv_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 ) { 1186parmp -> remote = parmp -> argc - argc ; 1187} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "server" , 6 ) == 0 ) { 1188want_argument = true; 1189argv_idx += 6 ; 1190} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "noplugin" , 8 ) == 0 ) { 1191p_lpl = false; 1192} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "cmd" , 3 ) == 0 ) { 1193want_argument = true; 1194argv_idx += 3 ; 1195} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "startuptime" , 11 ) == 0 ) { 1196want_argument = true; 1197argv_idx += 11 ; 1198} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "clean" , 5 ) == 0 ) { 1199parmp -> use_vimrc = "NONE" ; 1200parmp -> clean = true; 1201set_option_value_give_err ( kOptShadafile , STATIC_CSTR_AS_OBJ ( "NONE" ), 0 ); 1202} else if ( STRNICMP ( argv [ 0 ] + argv_idx , "luamod-dev" , 9 ) == 0 ) { 1203nlua_disable_preload = true; 1204} else { 1205if ( argv [ 0 ][ argv_idx ]) { 1206mainerr ( err_opt_unknown , argv [ 0 ], NULL ); 1207} 1208had_minmin = true; 1209} 1210if (! want_argument ) { 1211argv_idx = -1 ; // skip to next argument 1212} 1213break; 1214case 'A' : // "-A" start in Arabic mode. 1215set_option_value_give_err ( kOptArabic , BOOLEAN_OBJ (true), 0 ); 1216break; 1217case '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. 1221set_options_bin ( curbuf -> b_p_bin , 1 , 0 ); 1222curbuf -> b_p_bin = 1 ; // Binary file I/O. 1223break; 1224 1225case 'D' : // "-D" Debugging 1226parmp -> use_debug_break_level = 9999 ; 1227break; 1228case 'd' : // "-d" 'diff' 1229parmp -> diff_mode = true; 1230break; 1231case 'e' : // "-e" Ex mode 1232parmp -> exmode = true; 1233break; 1234case 'E' : // "-E" Ex mode 1235parmp -> exmode = true; 1236parmp -> input_istext = true; 1237break; 1238case 'f' : // "-f" GUI: run in foreground. 1239break; 1240case '?' : // "-?" give help message (for MS-Windows) 1241case 'h' : // "-h" give help message 1242usage (); 1243os_exit ( 0 ); 1244case 'H' : // "-H" start in Hebrew mode: rl + keymap=hebrew set. 1245set_option_value_give_err ( kOptKeymap , STATIC_CSTR_AS_OBJ ( "hebrew" ), 0 ); 1246set_option_value_give_err ( kOptRightleft , BOOLEAN_OBJ (true), 0 ); 1247break; 1248case 'M' : // "-M" no changes or writing of files 1249reset_modifiable (); 1250FALLTHROUGH ; 1251case 'm' : // "-m" no writing of files 1252p_write = false; 1253break; 1254 1255case 'N' : // "-N" Nocompatible 1256case 'X' : // "-X" Do not connect to X server 1257// No-op 1258break; 1259 1260case 'n' : // "-n" no swap file 1261parmp -> no_swap_file = true; 1262break; 1263case 'p' : // "-p[N]" open N tab pages 1264// default is 0: open window for each file 1265parmp -> window_count = get_number_arg ( argv [ 0 ], & argv_idx , 0 ); 1266parmp -> window_layout = WIN_TABS ; 1267break; 1268case 'o' : // "-o[N]" open N horizontal split windows 1269// default is 0: open window for each file 1270parmp -> window_count = get_number_arg ( argv [ 0 ], & argv_idx , 0 ); 1271parmp -> window_layout = WIN_HOR ; 1272break; 1273case 'O' : // "-O[N]" open N vertical split windows 1274// default is 0: open window for each file 1275parmp -> window_count = get_number_arg ( argv [ 0 ], & argv_idx , 0 ); 1276parmp -> window_layout = WIN_VER ; 1277break; 1278case 'q' : // "-q" QuickFix mode 1279if ( parmp -> edit_type != EDIT_NONE ) { 1280mainerr ( err_too_many_args , argv [ 0 ], NULL ); 1281} 1282parmp -> edit_type = EDIT_QF ; 1283if ( argv [ 0 ][ argv_idx ]) { // "-q{errorfile}" 1284parmp -> use_ef = argv [ 0 ] + argv_idx ; 1285argv_idx = -1 ; 1286} else if ( argc > 1 ) { // "-q {errorfile}" 1287want_argument = true; 1288} 1289break; 1290case 'R' : // "-R" readonly mode 1291readonlymode = true; 1292curbuf -> b_p_ro = true; 1293p_uc = 10000 ; // don't update very often 1294break; 1295case 'r' : // "-r" recovery mode 1296case 'L' : // "-L" recovery mode 1297recoverymode = 1 ; 1298break; 1299case 's' : 1300if ( parmp -> exmode ) { // "-es" silent (batch) mode 1301silent_mode = true; 1302exmode_active = true; 1303parmp -> no_swap_file = true; 1304if ( p_shadafile == NULL || * p_shadafile == NUL ) { 1305set_option_value_give_err ( kOptShadafile , STATIC_CSTR_AS_OBJ ( "NONE" ), 0 ); 1306} 1307} else { // "-s {scriptin}" read from script file 1308want_argument = true; 1309} 1310break; 1311case 't' : // "-t {tag}" or "-t{tag}" jump to tag 1312if ( parmp -> edit_type != EDIT_NONE ) { 1313mainerr ( err_too_many_args , argv [ 0 ], NULL ); 1314} 1315parmp -> edit_type = EDIT_TAG ; 1316if ( argv [ 0 ][ argv_idx ]) { // "-t{tag}" 1317parmp -> tagname = argv [ 0 ] + argv_idx ; 1318argv_idx = -1 ; 1319} else { // "-t {tag}" 1320want_argument = true; 1321} 1322break; 1323case 'v' : 1324version (); 1325os_exit ( 0 ); 1326case 'V' : // "-V{N}" Verbose level 1327// default is 10: a little bit verbose 1328p_verbose = get_number_arg ( argv [ 0 ], & argv_idx , 10 ); 1329if ( argv [ 0 ][ argv_idx ] != NUL ) { 1330set_option_value_give_err ( kOptVerbosefile , CSTR_AS_OBJ ( argv [ 0 ] + argv_idx ), 0 ); 1331argv_idx = ( int ) strlen ( argv [ 0 ]); 1332} 1333break; 1334case 'w' : // "-w{number}" set window height 1335// "-w {scriptout}" write to script 1336if ( ascii_isdigit (( argv [ 0 ])[ argv_idx ])) { 1337n = get_number_arg ( argv [ 0 ], & argv_idx , 10 ); 1338set_option_value_give_err ( kOptWindow , INTEGER_OBJ (( OptInt ) n ), 0 ); 1339break; 1340} 1341want_argument = true; 1342break; 1343 1344case 'c' : // "-c{command}" or "-c {command}" exec command 1345if ( argv [ 0 ][ argv_idx ] != NUL ) { 1346if ( parmp -> n_commands >= MAX_ARG_CMDS ) { 1347mainerr ( err_extra_cmd , NULL , NULL ); 1348} 1349parmp -> commands [ parmp -> n_commands ++ ] = argv [ 0 ] + argv_idx ; 1350argv_idx = -1 ; 1351break; 1352} 1353FALLTHROUGH ; 1354case 'S' : // "-S {file}" execute Vim script 1355case 'i' : // "-i {shada}" use for ShaDa file 1356case 'l' : // "-l {file}" Lua mode 1357case 'u' : // "-u {vimrc}" vim inits file 1358case 'U' : // "-U {gvimrc}" gvim inits file 1359case 'W' : // "-W {scriptout}" overwrite 1360want_argument = true; 1361break; 1362 1363default: 1364mainerr ( err_opt_unknown , argv [ 0 ], NULL ); 1365} 1366 1367// Handle option arguments with argument. 1368if ( want_argument ) { 1369// Check for garbage immediately after the option letter. 1370if ( argv [ 0 ][ argv_idx ] != NUL ) { 1371mainerr ( err_opt_garbage , argv [ 0 ], NULL ); 1372} 1373 1374argc -- ; 1375if ( argc < 1 && c != 'S' ) { // -S has an optional argument 1376mainerr ( err_arg_missing , argv [ 0 ], NULL ); 1377} 1378argv ++ ; 1379argv_idx = -1 ; 1380 1381switch ( c ) { 1382case 'c' : // "-c {command}" execute command 1383case 'S' : // "-S {file}" execute Vim script 1384if ( parmp -> n_commands >= MAX_ARG_CMDS ) { 1385mainerr ( err_extra_cmd , NULL , NULL ); 1386} 1387if ( c == 'S' ) { 1388char * a ; 1389 1390if ( argc < 1 ) { 1391// "-S" without argument: use default session file name. 1392a = SESSION_FILE ; 1393} else if ( argv [ 0 ][ 0 ] == '-' ) { 1394// "-S" followed by another option: use default session file. 1395a = SESSION_FILE ; 1396argc ++ ; 1397argv -- ; 1398} else { 1399a = argv [ 0 ]; 1400} 1401 1402size_t s_size = strlen ( a ) + 9 ; 1403char * s = xmalloc ( s_size ); 1404snprintf ( s , s_size , "so %s" , a ); 1405parmp -> cmds_tofree [ parmp -> n_commands ] = true; 1406parmp -> commands [ parmp -> n_commands ++ ] = s ; 1407} else { 1408parmp -> commands [ parmp -> n_commands ++ ] = argv [ 0 ]; 1409} 1410break; 1411 1412case '-' : 1413if ( strequal ( argv [ -1 ], "--cmd" )) { 1414// "--cmd {command}" execute command 1415if ( parmp -> n_pre_commands >= MAX_ARG_CMDS ) { 1416mainerr ( err_extra_cmd , NULL , NULL ); 1417} 1418parmp -> pre_commands [ parmp -> n_pre_commands ++ ] = argv [ 0 ]; 1419} else if ( strequal ( argv [ -1 ], "--listen" )) { 1420// "--listen {address}" 1421TO_SLASH ( argv [ 0 ]); 1422parmp -> listen_addr = argv [ 0 ]; 1423} else if ( strequal ( argv [ -1 ], "--server" )) { 1424// "--server {address}" 1425TO_SLASH ( argv [ 0 ]); 1426parmp -> server_addr = argv [ 0 ]; 1427} 1428// "--startuptime <file>" already handled 1429break; 1430 1431case 'q' : // "-q {errorfile}" QuickFix mode 1432parmp -> use_ef = argv [ 0 ]; 1433break; 1434 1435case 'i' : // "-i {shada}" use for shada 1436set_option_value_give_err ( kOptShadafile , CSTR_AS_OBJ ( argv [ 0 ]), 0 ); 1437break; 1438 1439case 'l' : // "-l" Lua script: args after "-l". 1440headless_mode = true; 1441silent_mode = true; 1442p_verbose = 1 ; 1443parmp -> no_swap_file = true; 1444parmp -> use_vimrc = parmp -> use_vimrc ? parmp -> use_vimrc : "NONE" ; 1445if ( p_shadafile == NULL || * p_shadafile == NUL ) { 1446set_option_value_give_err ( kOptShadafile , STATIC_CSTR_AS_OBJ ( "NONE" ), 0 ); 1447} 1448parmp -> luaf = argv [ 0 ]; 1449argc -- ; 1450if ( argc >= 0 ) { // Lua args after "-l <file>". 1451parmp -> lua_arg0 = parmp -> argc - argc ; 1452argc = 0 ; 1453} 1454break; 1455 1456case 's' : // "-s {scriptin}" read from script file 1457if ( parmp -> scriptin != NULL ) { 1458scripterror : 1459vim_snprintf ( IObuff , IOSIZE , 1460_ ( "Attempt to open script file again: \"%s %s\"\n" ), 1461argv [ -1 ], argv [ 0 ]); 1462fprintf ( stderr , "%s" , IObuff ); 1463os_exit ( 2 ); 1464} 1465parmp -> scriptin = argv [ 0 ]; 1466break; 1467 1468case 't' : // "-t {tag}" 1469parmp -> tagname = argv [ 0 ]; 1470break; 1471case 'u' : // "-u {vimrc}" vim inits file 1472parmp -> use_vimrc = argv [ 0 ]; 1473TO_SLASH ( argv [ 0 ]); 1474break; 1475case 'U' : // "-U {gvimrc}" gvim inits file 1476break; 1477 1478case 'w' : // "-w {nr}" 'window' value 1479// "-w {scriptout}" append to script file 1480if ( ascii_isdigit ( * ( argv [ 0 ]))) { 1481argv_idx = 0 ; 1482n = get_number_arg ( argv [ 0 ], & argv_idx , 10 ); 1483set_option_value_give_err ( kOptWindow , INTEGER_OBJ (( OptInt ) n ), 0 ); 1484argv_idx = -1 ; 1485break; 1486} 1487FALLTHROUGH ; 1488case 'W' : // "-W {scriptout}" overwrite script file 1489if ( parmp -> scriptout != NULL ) { 1490goto scripterror ; 1491} 1492parmp -> scriptout = argv [ 0 ]; 1493parmp -> scriptout_append = ( c == 'w' ); 1494} 1495} 1496} else { // File name argument. 1497argv_idx = -1 ; // skip to next argument 1498 1499// Check for only one type of editing. 1500if ( parmp -> edit_type > EDIT_STDIN ) { 1501mainerr ( err_too_many_args , argv [ 0 ], NULL ); 1502} 1503parmp -> edit_type = EDIT_FILE ; 1504 1505// Add the file to the global argument list. 1506ga_grow ( & global_alist . al_ga , 1 ); 1507char * p = xstrdup ( argv [ 0 ]); 1508 1509// On Windows expand "~\" or "~/" prefix in file names to profile directory. 1510#ifdef MSWIN 1511TO_SLASH ( p ); 1512if ( * p == '~' && p [ 1 ] == '/' ) { 1513size_t size = strlen ( os_homedir ()) + strlen ( p ); 1514char * tilde_expanded = xmalloc ( size ); 1515snprintf ( tilde_expanded , size , "%s%s" , os_homedir (), p + 1 ); 1516xfree ( p ); 1517p = tilde_expanded ; 1518} 1519#endif 1520 1521if ( parmp -> diff_mode && os_isdir ( p ) && GARGCOUNT > 0 1522&& ! os_isdir ( alist_name ( & GARGLIST [ 0 ]))) { 1523const char * tail = path_tail ( alist_name ( & GARGLIST [ 0 ])); 1524String ret = concat_fnames ( cstr_as_string ( p ), cstr_as_string ( tail ), true); 1525xfree ( p ); 1526p = ret . data ; 1527} 1528 1529#ifdef CASE_INSENSITIVE_FILENAME 1530// Make the case of the file name match the actual file. 1531path_fix_case ( p ); 1532#endif 1533 1534int alist_fnum_flag = edit_stdin ( parmp ) 1535? 1 // add buffer nr after exp. 1536: 2 ; // add buffer number now and use curbuf 1537alist_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. 1542if ( argv_idx <= 0 || argv [ 0 ][ argv_idx ] == NUL ) { 1543argc -- ; 1544argv ++ ; 1545argv_idx = 1 ; 1546} 1547} 1548 1549if ( embedded_mode && ( silent_mode || parmp -> luaf )) { 1550mainerr ( _ ( "--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. 1554if ( parmp -> n_commands > 0 ) { 1555const size_t swcmd_len = strlen ( parmp -> commands [ 0 ]) + 2 ; 1556char * const swcmd = xmalloc ( swcmd_len + 1 ); 1557snprintf ( swcmd , swcmd_len + 1 , ":%s\r" , parmp -> commands [ 0 ]); 1558set_vim_var_string ( VV_SWAPCOMMAND , swcmd , ( ptrdiff_t ) swcmd_len ); 1559xfree ( swcmd ); 1560} 1561 1562TIME_MSG ( "parsing arguments" ); 1563} 1564 1565static void set_argf_var ( void ) 1566{ 1567list_T * list = tv_list_alloc ( kListLenMayKnow ); 1568 1569for ( int i = 0 ; i < GARGCOUNT ; i ++ ) { 1570char * fname = alist_name ( & GARGLIST [ i ]); 1571if ( fname != NULL ) { 1572( void ) vim_FullName ( fname , NameBuff , sizeof( NameBuff ), false); 1573tv_list_append_string ( list , NameBuff , -1 ); 1574} 1575} 1576 1577tv_list_set_lock ( list , VAR_FIXED ); 1578set_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{ 1586CLEAR_POINTER ( paramp ); 1587paramp -> argc = argc ; 1588paramp -> argv = argv ; 1589paramp -> use_debug_break_level = -1 ; 1590paramp -> window_count = -1 ; 1591paramp -> listen_addr = NULL ; 1592paramp -> server_addr = NULL ; 1593paramp -> remote = 0 ; 1594paramp -> luaf = NULL ; 1595paramp -> lua_arg0 = -1 ; 1596} 1597 1598/// Initialize global startuptime file if "--startuptime" passed as an argument. 1599static void init_startuptime ( mparm_T * paramp ) 1600{ 1601bool is_embed = false; 1602for ( int i = 1 ; i < paramp -> argc - 1 ; i ++ ) { 1603if ( STRICMP ( paramp -> argv [ i ], "--embed" ) == 0 ) { 1604is_embed = true; 1605break; 1606} 1607} 1608for ( int i = 1 ; i < paramp -> argc - 1 ; i ++ ) { 1609if ( STRICMP ( paramp -> argv [ i ], "--startuptime" ) == 0 ) { 1610time_init ( paramp -> argv [ i + 1 ], is_embed ? "Embedded" : "Primary (or UI client)" ); 1611time_start ( "--- NVIM STARTING ---" ); 1612break; 1613} 1614} 1615} 1616 1617static void check_and_set_isatty ( mparm_T * paramp ) 1618{ 1619stdin_isatty = os_isatty ( STDIN_FILENO ); 1620stdout_isatty = os_isatty ( STDOUT_FILENO ); 1621stderr_isatty = os_isatty ( STDERR_FILENO ); 1622TIME_MSG ( "window checked" ); 1623} 1624 1625// Sets v:progname and v:progpath. Also modifies $PATH on Windows. 1626static void init_path (const char * exename ) 1627FUNC_ATTR_NONNULL_ALL 1628{ 1629char exepath [ MAXPATHL ] = { 0 }; 1630size_t exepathlen = MAXPATHL ; 1631// Make v:progpath absolute. 1632if ( os_exepath ( exepath , & exepathlen ) != 0 ) { 1633// Fall back to argv[0]. Missing procfs? #6734 1634path_guess_exepath ( exename , exepath , sizeof( exepath )); 1635} 1636set_vim_var_string ( VV_PROGPATH , exepath , -1 ); 1637set_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(). 1642os_setenv_append_path ( exepath ); 1643#endif 1644} 1645 1646/// Get filename from command line, if any. 1647static char * get_fname ( mparm_T * parmp ) 1648{ 1649return 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{ 1655if ( paramp -> diff_mode && paramp -> window_layout == 0 ) { 1656if ( diffopt_horizontal ()) { 1657paramp -> window_layout = WIN_HOR ; // use horizontal split 1658} else { 1659paramp -> 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{ 1668if ( paramp -> edit_type == EDIT_QF ) { 1669if ( paramp -> use_ef != NULL ) { 1670set_option_direct ( kOptErrorfile , CSTR_AS_OBJ ( paramp -> use_ef ), 0 , SID_CARG ); 1671} 1672vim_snprintf ( IObuff , IOSIZE , "cfile %s" , p_ef ); 1673if ( qf_init ( NULL , p_ef , p_efm , true, IObuff , p_menc ) < 0 ) { 1674msg_putchar ( '\n' ); 1675os_exit ( 3 ); 1676} 1677TIME_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{ 1685if ( tagname != NULL ) { 1686swap_exists_did_quit = false; 1687 1688vim_snprintf ( IObuff , IOSIZE , "ta %s" , tagname ); 1689do_cmdline_cmd ( IObuff ); 1690TIME_MSG ( "jumping to tag" ); 1691 1692// If the user doesn't want to edit the file then we quit here. 1693if ( swap_exists_did_quit ) { 1694ui_call_error_exit ( 1 ); 1695getout ( 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. 1704swap_exists_action = SEA_DIALOG ; 1705no_wait_return = true; 1706bool save_msg_didany = msg_didany ; 1707 1708if ( curbuf -> b_ffname ) { 1709// curbuf is already opened for a file, create a new buffer for stdin. #35269 1710buf_T * stdin_buf = buflist_new ( NULL , NULL , 0 , BLN_LISTED ); 1711if ( stdin_buf == NULL ) { 1712semsg ( "Failed to create buffer for stdin" ); 1713return; 1714} 1715 1716// remember the current buffer number so we can go back to it 1717handle_T initial_buf_handle = curbuf -> handle ; 1718 1719// set the buffer we just created as curbuf so we can read stdin into it 1720set_curbuf ( stdin_buf , 0 , false); 1721readfile ( 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 1724handle_T stdin_buf_handle = stdin_buf -> handle ; 1725bool stdin_buf_empty = buf_is_empty ( curbuf ); 1726 1727// switch back to the original starting buffer 1728char buf [ 100 ]; 1729vim_snprintf ( buf , sizeof( buf ), "silent! buffer %d" , initial_buf_handle ); 1730do_cmdline_cmd ( buf ); 1731 1732if ( 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 1735vim_snprintf ( buf , sizeof( buf ), "silent! bwipeout! %d" , stdin_buf_handle ); 1736do_cmdline_cmd ( buf ); 1737} 1738} else { 1739// stdin buffer is first so we can just use curbuf 1740set_buflisted (true); 1741// Create memfile and read from stdin. 1742open_buffer (true, NULL , 0 ); 1743// stdin was empty so we should wipe it (e.g. "echo file1 | xargs nvim"). #8561 1744if ( buf_is_empty ( curbuf ) && curbuf -> b_next != NULL ) { 1745do_cmdline_cmd ( "silent! bnext" ); 1746do_cmdline_cmd ( "silent! bwipeout 1" ); 1747} 1748} 1749 1750no_wait_return = false; 1751msg_didany = save_msg_didany ; 1752TIME_MSG ( "reading stdin" ); 1753check_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. 1761if ( parmp -> window_count == -1 ) { // was not set 1762parmp -> window_count = 1 ; 1763} 1764if ( parmp -> window_count == 0 ) { 1765parmp -> window_count = GARGCOUNT ; 1766} 1767if ( parmp -> window_count > 1 ) { 1768// Don't change the windows if there was a command in vimrc that 1769// already split some windows 1770if ( parmp -> window_layout == 0 ) { 1771parmp -> window_layout = WIN_HOR ; 1772} 1773if ( parmp -> window_layout == WIN_TABS ) { 1774parmp -> window_count = make_tabpages ( parmp -> window_count ); 1775TIME_MSG ( "making tab pages" ); 1776} else if ( firstwin -> w_next == NULL || firstwin -> w_next -> w_floating ) { 1777parmp -> window_count = make_windows ( parmp -> window_count , parmp -> window_layout == WIN_VER ); 1778TIME_MSG ( "making windows" ); 1779} else { 1780parmp -> window_count = win_count (); 1781} 1782} else { 1783parmp -> window_count = 1 ; 1784} 1785 1786if ( recoverymode ) { // do recover 1787msg_scroll = true; // scroll message up 1788ml_recover (true); 1789if ( curbuf -> b_ml . ml_mfp == NULL ) { // failed 1790getout ( 1 ); 1791} 1792do_modelines ( 0 ); // do modelines 1793} else { 1794int 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 1800autocmd_no_enter ++ ; 1801autocmd_no_leave ++ ; 1802// Save the window selection made by startup scripts. 1803win_T * startup_curwin = curwin ; 1804bool dorewind = true; 1805while ( done ++ < 1000 ) { 1806if ( dorewind ) { 1807if ( parmp -> window_layout == WIN_TABS ) { 1808goto_tabpage ( 1 ); 1809} else { 1810curwin = firstwin ; 1811} 1812} else if ( parmp -> window_layout == WIN_TABS ) { 1813if ( curtab -> tp_next == NULL ) { 1814break; 1815} 1816goto_tabpage ( 0 ); 1817} else { 1818if ( curwin -> w_next == NULL ) { 1819break; 1820} 1821curwin = curwin -> w_next ; 1822} 1823dorewind = false; 1824curbuf = curwin -> w_buffer ; 1825if ( curbuf -> b_ml . ml_mfp == NULL ) { 1826// Set 'foldlevel' to 'foldlevelstart' if it's not negative.. 1827if ( p_fdls >= 0 ) { 1828curwin -> w_p_fdl = p_fdls ; 1829} 1830// When getting the ATTENTION prompt here, use a dialog. 1831swap_exists_action = SEA_DIALOG ; 1832set_buflisted (true); 1833 1834// create memfile, read file 1835open_buffer (false, NULL , 0 ); 1836 1837if ( swap_exists_action == SEA_QUIT ) { 1838if ( got_int || only_one_window ()) { 1839// abort selected or quit and only one window 1840did_emsg = false; // avoid hit-enter prompt 1841ui_call_error_exit ( 1 ); 1842getout ( 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. 1847setfname ( curbuf , NULL , NULL , false); 1848curwin -> w_arg_idx = -1 ; 1849swap_exists_action = SEA_NONE ; 1850} else { 1851handle_swap_exists ( NULL ); 1852} 1853dorewind = true; // start again 1854} 1855os_breakcheck (); 1856if ( got_int ) { 1857vgetc (); // only break the file loading, not the rest 1858break; 1859} 1860} 1861if ( parmp -> window_layout == WIN_TABS ) { 1862goto_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. 1865curwin = firstwin ; 1866} else { 1867curwin = startup_curwin ; 1868} 1869curbuf = curwin -> w_buffer ; 1870autocmd_no_enter -- ; 1871autocmd_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{ 1879int arg_idx ; // index in argument list 1880bool advance = true; 1881win_T * win ; 1882char * p_shm_save = NULL ; 1883 1884// Don't execute Win/Buf Enter/Leave autocommands here 1885autocmd_no_enter ++ ; 1886autocmd_no_leave ++ ; 1887 1888// When w_arg_idx is -1 remove the window (see create_windows()). 1889if ( curwin -> w_arg_idx == -1 ) { 1890win_close ( curwin , true, false); 1891advance = false; 1892} 1893 1894arg_idx = 1 ; 1895for ( int i = 1 ; i < parmp -> window_count ; i ++ ) { 1896// When w_arg_idx is -1 remove the window (see create_windows()). 1897if ( curwin -> w_arg_idx == -1 ) { 1898arg_idx ++ ; 1899win_close ( curwin , true, false); 1900advance = false; 1901continue; 1902} 1903 1904if ( advance ) { 1905if ( parmp -> window_layout == WIN_TABS ) { 1906if ( curtab -> tp_next == NULL ) { // just checking 1907break; 1908} 1909goto_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. 1913if ( i == 1 ) { 1914char buf [ 100 ]; 1915 1916p_shm_save = xstrdup ( p_shm ); 1917snprintf ( buf , sizeof( buf ), "F%s" , p_shm ); 1918set_option_value_give_err ( kOptShortmess , CSTR_AS_OBJ ( buf ), 0 ); 1919} 1920} else { 1921if ( curwin -> w_next == NULL ) { // just checking 1922break; 1923} 1924win_enter ( curwin -> w_next , false); 1925} 1926} 1927advance = true; 1928 1929// Only open the file if there is no file in this window yet (that can 1930// happen when vimrc contains ":sall"). 1931if ( curbuf == firstwin -> w_buffer || curbuf -> b_ffname == NULL ) { 1932curwin -> 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. 1935swap_exists_did_quit = false; 1936do_ecmd ( 0 , arg_idx < GARGCOUNT 1937? alist_name ( & GARGLIST [ arg_idx ]) 1938: NULL , NULL , NULL , ECMD_LASTL , ECMD_HIDE , curwin ); 1939if ( swap_exists_did_quit ) { 1940// abort or quit selected 1941if ( got_int || only_one_window ()) { 1942// abort selected and only one window 1943did_emsg = false; // avoid hit-enter prompt 1944ui_call_error_exit ( 1 ); 1945getout ( 1 ); 1946} 1947win_close ( curwin , true, false); 1948advance = false; 1949} 1950if ( arg_idx == GARGCOUNT - 1 ) { 1951arg_had_last = true; 1952} 1953arg_idx ++ ; 1954} 1955os_breakcheck (); 1956if ( got_int ) { 1957vgetc (); // only break the file loading, not the rest 1958break; 1959} 1960} 1961 1962if ( p_shm_save != NULL ) { 1963set_option_value_give_err ( kOptShortmess , CSTR_AS_OBJ ( p_shm_save ), 0 ); 1964xfree ( p_shm_save ); 1965} 1966 1967if ( parmp -> window_layout == WIN_TABS ) { 1968goto_tabpage ( 1 ); 1969} 1970autocmd_no_enter -- ; 1971 1972// make the first window the current window 1973win = ( parmp -> window_count > 1 ) ? firstwin : curwin ; 1974// Avoid making a preview window the current window. 1975while ( win -> w_p_pvw ) { 1976win = win -> w_next ; 1977if ( win == NULL ) { 1978win = firstwin ; 1979break; 1980} 1981} 1982win_enter ( win , false); 1983 1984autocmd_no_leave -- ; 1985TIME_MSG ( "editing files in windows" ); 1986if ( parmp -> window_count > 1 && parmp -> window_layout != WIN_TABS ) { 1987win_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{ 1994char ** cmds = parmp -> pre_commands ; 1995int cnt = parmp -> n_pre_commands ; 1996ESTACK_CHECK_DECLARATION ; 1997 1998if ( cnt <= 0 ) { 1999return; 2000} 2001 2002curwin -> w_cursor . lnum = 0 ; // just in case.. 2003estack_push ( ETYPE_ARGS , _ ( "pre-vimrc command line" ), 0 ); 2004ESTACK_CHECK_SETUP ; 2005current_sctx . sc_sid = SID_CMDARG ; 2006for ( int i = 0 ; i < cnt ; i ++ ) { 2007do_cmdline_cmd ( cmds [ i ]); 2008} 2009ESTACK_CHECK_NOW ; 2010estack_pop (); 2011current_sctx . sc_sid = 0 ; 2012TIME_MSG ( "--cmd commands" ); 2013} 2014 2015// Execute "+", "-c" and "-S" arguments. 2016static void exe_commands ( mparm_T * parmp ) 2017{ 2018ESTACK_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. 2023msg_scroll = true; 2024if ( parmp -> tagname == NULL && curwin -> w_cursor . lnum <= 1 ) { 2025curwin -> w_cursor . lnum = 0 ; 2026} 2027estack_push ( ETYPE_ARGS , "command line" , 0 ); 2028ESTACK_CHECK_SETUP ; 2029current_sctx . sc_sid = SID_CARG ; 2030current_sctx . sc_seq = 0 ; 2031for ( int i = 0 ; i < parmp -> n_commands ; i ++ ) { 2032do_cmdline_cmd ( parmp -> commands [ i ]); 2033if ( parmp -> cmds_tofree [ i ]) { 2034xfree ( parmp -> commands [ i ]); 2035} 2036} 2037ESTACK_CHECK_NOW ; 2038estack_pop (); 2039current_sctx . sc_sid = 0 ; 2040if ( curwin -> w_cursor . lnum == 0 ) { 2041curwin -> w_cursor . lnum = 1 ; 2042} 2043 2044msg_scroll = false; 2045 2046// When started with "-q errorfile" jump to first error again. 2047if ( parmp -> edit_type == EDIT_QF ) { 2048qf_jump ( NULL , 0 , 0 , false); 2049} 2050TIME_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{ 2061char * const config_dirs = stdpaths_get_xdg_var ( kXDGConfigDirs ); 2062if ( config_dirs != NULL ) { 2063const void * iter = NULL ; 2064const char * appname = get_appname (false); 2065size_t appname_len = strlen ( appname ); 2066const char sysinit_suffix [] = { 2067PATHSEP , 2068's' , 'y' , 's' , 'i' , 'n' , 'i' , 't' , '.' , 'v' , 'i' , 'm' , NUL 2069}; 2070do { 2071const char * dir ; 2072size_t dir_len ; 2073iter = vim_env_iter ( ':' , config_dirs , iter , & dir , & dir_len ); 2074if ( dir == NULL || dir_len == 0 ) { 2075break; 2076} 2077size_t path_len = dir_len + 1 + appname_len + sizeof( sysinit_suffix ); 2078char * vimrc = xmalloc ( path_len ); 2079memcpy ( vimrc , dir , dir_len ); 2080if ( vimrc [ dir_len - 1 ] != PATHSEP ) { 2081vimrc [ dir_len ] = PATHSEP ; 2082dir_len += 1 ; 2083} 2084memcpy ( vimrc + dir_len , appname , appname_len ); 2085memcpy ( vimrc + dir_len + appname_len , sysinit_suffix , sizeof( sysinit_suffix )); 2086if ( do_source ( vimrc , false, DOSO_NONE , NULL ) != FAIL ) { 2087xfree ( vimrc ); 2088xfree ( config_dirs ); 2089return; 2090} 2091xfree ( vimrc ); 2092} while ( iter != NULL ); 2093xfree ( config_dirs ); 2094} 2095 2096#ifdef SYS_VIMRC_FILE 2097// Get system wide defaults, if the file name is defined. 2098do_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 ) 2113FUNC_ATTR_WARN_UNUSED_RESULT 2114{ 2115bool do_exrc = p_exrc ; 2116if ( execute_env ( "VIMINIT" ) == OK ) { 2117do_exrc = p_exrc ; 2118return do_exrc ; 2119} 2120 2121char * init_lua_path = stdpaths_user_conf_subpath ( "init.lua" ); 2122 2123// init.lua 2124if ( os_path_exists ( init_lua_path ) 2125&& do_source ( init_lua_path , false, DOSO_VIMRC , NULL )) { 2126xfree ( init_lua_path ); 2127 2128char * user_conf_path = stdpaths_user_conf (); 2129do_config_initialization ( user_conf_path ); 2130xfree ( user_conf_path ); 2131 2132do_exrc = p_exrc ; 2133return do_exrc ; 2134} 2135xfree ( init_lua_path ); 2136 2137char * const config_dirs = stdpaths_get_xdg_var ( kXDGConfigDirs ); 2138if ( config_dirs != NULL ) { 2139const char * appname = get_appname (false); 2140size_t appname_len = strlen ( appname ); 2141 2142const void * iter = NULL ; 2143do { 2144const char * dir ; 2145size_t dir_len ; 2146iter = vim_env_iter ( ':' , config_dirs , iter , & dir , & dir_len ); 2147if ( dir == NULL || dir_len == 0 ) { 2148break; 2149} 2150 2151// Build: <xdg_dir>/<appname>/init.lua 2152const char init_lua_suffix [] = { PATHSEP , 'i' , 'n' , 'i' , 't' , '.' , 'l' , 'u' , 'a' , NUL }; 2153size_t init_lua_len = dir_len + 1 + appname_len + sizeof( init_lua_suffix ); 2154char * init_lua = xmalloc ( init_lua_len ); 2155memcpy ( init_lua , dir , dir_len ); 2156init_lua [ dir_len ] = PATHSEP ; 2157memcpy ( init_lua + dir_len + 1 , appname , appname_len ); 2158memcpy ( init_lua + dir_len + 1 + appname_len , init_lua_suffix , sizeof( init_lua_suffix )); 2159 2160if ( os_path_exists ( init_lua ) 2161&& do_source ( init_lua , true, DOSO_VIMRC , NULL )) { 2162do_config_initialization ( dir ); 2163xfree ( init_lua ); 2164xfree ( config_dirs ); 2165do_exrc = p_exrc ; 2166return do_exrc ; 2167} 2168xfree ( init_lua ); 2169} while ( iter != NULL ); 2170xfree ( config_dirs ); 2171} 2172 2173if ( execute_env ( "EXINIT" ) == OK ) { 2174do_exrc = p_exrc ; 2175return do_exrc ; 2176} 2177return do_exrc ; 2178} 2179 2180void do_config_initialization ( char * const user_conf_path ) 2181{ 2182char * const init_pattern = "init/**/*" ; 2183source_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{ 2192lua_State * const L = get_global_lstate (); 2193assert ( L ); 2194 2195lua_getglobal ( L , "require" ); 2196lua_pushstring ( L , "vim._core.exrc" ); 2197if ( nlua_pcall ( L , 1 , 0 )) { 2198fprintf ( stderr , "%s\n" , lua_tostring ( L , -1 )); 2199} 2200} 2201 2202/// Source startup scripts 2203static void source_startup_scripts (const mparm_T * const parmp ) 2204FUNC_ATTR_NONNULL_ALL 2205{ 2206// If -u given, use only the initializations from that file and nothing else. 2207if ( parmp -> use_vimrc != NULL ) { 2208if ( strequal ( parmp -> use_vimrc , "NONE" ) || strequal ( parmp -> use_vimrc , "NORC" )) { 2209// Do nothing. 2210} else { 2211if ( do_source ( parmp -> use_vimrc , false, DOSO_NONE , NULL ) != OK ) { 2212semsg ( _ ( e_cannot_read_from_str_2 ), parmp -> use_vimrc ); 2213} 2214} 2215} else if (! silent_mode ) { 2216do_system_initialization (); 2217 2218if ( do_user_initialization ()) { 2219do_exrc_initialization (); 2220} 2221} 2222TIME_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 ) 2232FUNC_ATTR_NONNULL_ALL 2233{ 2234ESTACK_CHECK_DECLARATION ; 2235char * initstr = os_getenv ( env ); 2236if ( initstr == NULL ) { 2237return FAIL ; 2238} 2239 2240estack_push ( ETYPE_ENV , env , 0 ); 2241ESTACK_CHECK_SETUP ; 2242const sctx_T save_current_sctx = current_sctx ; 2243current_sctx . sc_sid = SID_ENV ; 2244current_sctx . sc_seq = 0 ; 2245current_sctx . sc_lnum = 0 ; 2246do_cmdline_cmd ( initstr ); 2247 2248ESTACK_CHECK_NOW ; 2249estack_pop (); 2250current_sctx = save_current_sctx ; 2251 2252xfree ( initstr ); 2253return 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 ) 2262FUNC_ATTR_NORETURN 2263{ 2264print_mainerr ( msg1 , msg2 , msg3 ); 2265os_exit ( 1 ); 2266} 2267 2268static void print_mainerr (const char * msg1 , const char * msg2 , const char * msg3 ) 2269{ 2270char * prgname = path_tail ( argv0 ); 2271 2272signal_stop (); // kill us with CTRL-C here, if you like 2273 2274fprintf ( stderr , "%s: %s" , prgname , _ ( msg1 )); 2275if ( msg2 != NULL ) { 2276fprintf ( stderr , ": \"%s\"" , msg2 ); 2277} 2278if ( msg3 != NULL ) { 2279fprintf ( stderr , ": \"%s\"" , msg3 ); 2280} 2281fprintf ( stderr , _ ( "\nMore info with \"" )); 2282fprintf ( 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? 2289nlua_init ( NULL , 0 , -1 ); 2290info_message = true; // use stdout, not stderr 2291list_version (); 2292msg_putchar ( '\n' ); 2293msg_didout = false; 2294} 2295 2296/// Prints help message for "nvim -h" or "nvim --help". 2297static void usage ( void ) 2298{ 2299signal_stop (); // kill us with CTRL-C here, if you like 2300 2301printf ( _ ( "Usage:\n" )); 2302printf ( _ ( " nvim [options] [file ...]\n" )); 2303printf ( _ ( "\nOptions:\n" )); 2304printf ( _ ( " --cmd <cmd> Execute <cmd> before any config\n" )); 2305printf ( _ ( " +<cmd>, -c <cmd> Execute <cmd> after config and first file\n" )); 2306printf ( _ ( " -l <script> [args...] Execute Lua <script> (with optional args)\n" )); 2307printf ( _ ( " -S <session> Source <session> after loading the first file\n" )); 2308printf ( _ ( " -s <scriptin> Read Normal mode commands from <scriptin>\n" )); 2309printf ( _ ( " -u <config> Use this config file\n" )); 2310printf ( "\n" ); 2311printf ( _ ( " -d Diff mode\n" )); 2312printf ( _ ( " -es, -Es Silent (batch) mode\n" )); 2313printf ( _ ( " -h, --help Print this help message\n" )); 2314printf ( _ ( " -i <shada> Use this shada file\n" )); 2315printf ( _ ( " -n No swap file, use memory only\n" )); 2316printf ( _ ( " -o[N] Open N windows (default: one per file)\n" )); 2317printf ( _ ( " -O[N] Open N vertical windows (default: one per file)\n" )); 2318printf ( _ ( " -p[N] Open N tab pages (default: one per file)\n" )); 2319printf ( _ ( " -R Read-only (view) mode\n" )); 2320printf ( _ ( " -v, --version Print version information\n" )); 2321printf ( _ ( " -V[N][file] Verbose [level][file]\n" )); 2322printf ( "\n" ); 2323printf ( _ ( " -- Only file names after this\n" )); 2324printf ( _ ( " --api-info Write msgpack-encoded API metadata to stdout\n" )); 2325printf ( _ ( " --clean \"Factory defaults\" (skip user config and plugins, shada)\n" )); 2326printf ( _ ( " --embed Use stdin/stdout as a msgpack-rpc channel\n" )); 2327printf ( _ ( " --headless Don't start a user interface\n" )); 2328printf ( _ ( " --listen <address> Serve RPC API from this address\n" )); 2329printf ( _ ( " --remote[-subcommand] Execute commands remotely on a server\n" )); 2330printf ( _ ( " --server <address> Connect to this Nvim server\n" )); 2331printf ( _ ( " --startuptime <file> Write startup timing messages to <file>\n" )); 2332printf ( _ ( "\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{ 2340if ( swap_exists_action == SEA_QUIT ) { 2341ui_call_error_exit ( 1 ); 2342getout ( 1 ); 2343} 2344handle_swap_exists ( NULL ); 2345} 2346 2347#ifdef ENABLE_ASAN_UBSAN 2348const char * __ubsan_default_options ( void ) 2349{ 2350return "print_stacktrace=1" ; 2351} 2352 2353const char * __asan_default_options ( void ) 2354{ 2355return "handle_abort=1,handle_sigill=1" ; 2356} 2357#endif