-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Expand file tree
/
Copy pathmain.c
More file actions
2374 lines (2109 loc) · 71.4 KB
/
Copy pathmain.c
File metadata and controls
2374 lines (2109 loc) · 71.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Make sure extern symbols are exported on Windows
#ifdef WIN32
# define EXTERN __declspec(dllexport)
#else
# define EXTERN
#endif
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef ENABLE_ASAN_UBSAN
# include <sanitizer/asan_interface.h>
# ifndef MSWIN
# include <sanitizer/ubsan_interface.h>
# endif
#endif
#include "auto/config.h" // IWYU pragma: keep
#include "klib/kvec.h"
#include "nvim/api/extmark.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
#include "nvim/api/ui.h"
#include "nvim/arglist.h"
#include "nvim/ascii_defs.h"
#include "nvim/autocmd.h"
#include "nvim/autocmd_defs.h"
#include "nvim/buffer.h"
#include "nvim/buffer_defs.h"
#include "nvim/channel.h"
#include "nvim/channel_defs.h"
#include "nvim/context.h"
#include "nvim/decoration.h"
#include "nvim/decoration_provider.h"
#include "nvim/diff.h"
#include "nvim/drawline.h"
#include "nvim/drawscreen.h"
#include "nvim/errors.h"
#include "nvim/eval.h"
#include "nvim/eval/typval.h"
#include "nvim/eval/typval_defs.h"
#include "nvim/eval/userfunc.h"
#include "nvim/eval/vars.h"
#include "nvim/event/loop.h"
#include "nvim/event/multiqueue.h"
#include "nvim/event/proc.h"
#include "nvim/event/socket.h"
#include "nvim/event/stream.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_docmd.h"
#include "nvim/ex_getln.h"
#include "nvim/extmark.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/garray.h"
#include "nvim/gettext_defs.h"
#include "nvim/globals.h"
#include "nvim/grid.h"
#include "nvim/hashtab.h"
#include "nvim/highlight.h"
#include "nvim/highlight_group.h"
#include "nvim/input.h"
#include "nvim/keycodes.h"
#include "nvim/log.h"
#include "nvim/lua/executor.h"
#include "nvim/lua/secure.h"
#include "nvim/lua/treesitter.h"
#include "nvim/macros_defs.h"
#include "nvim/main.h"
#include "nvim/mark.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/mouse.h"
#include "nvim/move.h"
#include "nvim/msgpack_rpc/channel.h"
#include "nvim/msgpack_rpc/server.h"
#include "nvim/normal.h"
#include "nvim/ops.h"
#include "nvim/option.h"
#include "nvim/option_defs.h"
#include "nvim/option_vars.h"
#include "nvim/os/fs.h"
#include "nvim/os/input.h"
#include "nvim/os/lang.h"
#include "nvim/os/os.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/signal.h"
#include "nvim/os/stdpaths_defs.h"
#include "nvim/path.h"
#include "nvim/popupmenu.h"
#include "nvim/profile.h"
#include "nvim/quickfix.h"
#include "nvim/register.h"
#include "nvim/runtime.h"
#include "nvim/runtime_defs.h"
#include "nvim/shada.h"
#include "nvim/statusline.h"
#include "nvim/strings.h"
#include "nvim/syntax.h"
#include "nvim/terminal.h"
#include "nvim/types_defs.h"
#include "nvim/ui.h"
#include "nvim/ui_client.h"
#include "nvim/ui_compositor.h"
#include "nvim/version.h"
#include "nvim/vim_defs.h"
#include "nvim/window.h"
#include "nvim/winfloat.h"
#ifdef MSWIN
# include "nvim/os/os_win_console.h"
# ifndef _UCRT
# error UCRT is the only supported C runtime on windows
# endif
#endif
#if defined(MSWIN) && !defined(MAKE_LIB)
# include "nvim/mbyte.h"
#endif
// values for "window_layout"
enum {
WIN_HOR = 1, // "-o" horizontally split windows
WIN_VER = 2, // "-O" vertically split windows
WIN_TABS = 3, // "-p" windows on tab pages
};
// Values for edit_type.
enum {
EDIT_NONE = 0, // no edit type yet
EDIT_FILE = 1, // file name argument[s] given, use argument list
EDIT_STDIN = 2, // read file from stdin
EDIT_TAG = 3, // tag name argument given, use tagname
EDIT_QF = 4, // start in quickfix mode
};
#include "main.c.generated.h"
Loop main_loop;
static char *argv0 = NULL;
// Error messages
static const char *err_arg_missing = N_("Argument missing after");
static const char *err_opt_garbage = N_("Garbage after option argument");
static const char *err_opt_unknown = N_("Unknown option argument");
static const char *err_too_many_args = N_("Too many edit arguments");
static const char *err_extra_cmd =
N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments");
void event_init(void)
{
loop_init(&main_loop, NULL);
env_init();
resize_events = multiqueue_new_child(main_loop.events);
autocmd_init();
signal_init();
// mspgack-rpc initialization
channel_init();
terminal_init();
ui_init();
TIME_MSG("event init");
}
/// @returns false if main_loop could not be closed gracefully
static bool event_teardown(void)
{
if (!main_loop.events) {
input_stop();
return true;
}
multiqueue_process_events(main_loop.events);
loop_poll_events(&main_loop, 0); // Drain thread_events, fast_events.
input_stop();
server_teardown();
channel_teardown();
proc_teardown(&main_loop);
timer_teardown();
signal_teardown();
terminal_teardown();
return loop_close(&main_loop, true);
}
/// Performs early initialization.
static void early_init(mparm_T *paramp)
{
os_hint_priority();
estack_init();
cmdline_init();
eval_init(); // init global variables
set_vim_var_nr(VV_STARTTIME, (varnumber_T)os_realtime());
init_path(argv0 ? argv0 : "nvim");
init_normal_cmds(); // Init the table of Normal mode commands.
runtime_init();
highlight_init();
#ifdef MSWIN
OSVERSIONINFO ovi;
ovi.dwOSVersionInfoSize = sizeof(ovi);
// Disable warning about GetVersionExA being deprecated. There doesn't seem to be a convenient
// replacement that doesn't add a ton of extra code as of writing this.
# ifdef _MSC_VER
# pragma warning(suppress : 4996)
GetVersionEx(&ovi);
# else
GetVersionEx(&ovi);
# endif
snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
(int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
#endif
TIME_MSG("early init");
// Setup to use the current locale (for ctype() and many other things).
// NOTE: Translated messages with encodings other than latin1 will not
// work until set_init_1() has been called!
init_locale();
// tabpage local options (p_ch) must be set before allocating first tabpage.
set_init_tablocal();
// Allocate the first tabpage, window and buffer.
win_alloc_first();
TIME_MSG("init first window");
alist_init(&global_alist); // Init the argument list to empty.
global_alist.id = 0;
// Set the default values for the options.
// First find out the home directory, needed to expand "~" in options.
init_homedir(); // find real value of $HOME
set_init_1(paramp != NULL ? paramp->clean : false);
log_init();
TIME_MSG("inits 1");
set_lang_var(); // set v:lang and v:ctype
// initialize quickfix list
qf_init_stack();
}
#ifdef MAKE_LIB
int nvim_main(int argc, char **argv); // silence -Wmissing-prototypes
int nvim_main(int argc, char **argv)
#else
int main(int argc, char **argv)
#endif
{
argv0 = argv[0];
TO_SLASH(argv0);
if (!appname_is_valid()) {
fprintf(stderr, "$NVIM_APPNAME must be a name or relative path.\n");
exit(1);
}
char *fname = NULL; // file name from command line
mparm_T params; // various parameters passed between
// main() and other functions.
// Many variables are in `params` so that we can pass them around easily.
// `argc` and `argv` are also copied, so that they can be changed.
init_params(¶ms, argc, argv);
init_startuptime(¶ms);
// Need to find "--clean" before actually parsing arguments.
for (int i = 1; i < params.argc; i++) {
if (STRICMP(params.argv[i], "--clean") == 0) {
params.clean = true;
break;
}
}
event_init();
early_init(¶ms);
set_argv_var(argv, argc); // set v:argv
// Check if we have an interactive window.
check_and_set_isatty(¶ms);
// Process the command line arguments. File names are put in the global
// argument list "global_alist".
command_line_scan(¶ms);
set_argf_var();
nlua_init(argv, argc, params.lua_arg0);
TIME_MSG("init lua interpreter");
// On Windows, channel_from_stdio() replaces fd 2 with CONOUT$ (for ConPTY
// support). Save a dup of the original stderr first so that if server_init()
// fails, print_mainerr() can write through the pipe to the TUI client's relay.
#ifdef MSWIN
int startup_stderr_fd = -1;
if (embedded_mode) {
startup_stderr_fd = os_dup_cloexec(STDERR_FILENO);
}
#endif
if (embedded_mode) {
const char *err;
if (!channel_from_stdio(true, CALLBACK_READER_INIT, &err)) {
abort();
}
}
if (GARGCOUNT > 0) {
fname = get_fname(¶ms);
}
// Recovery mode without a file name: List swap files.
// In this case, no UI is needed.
if (recoverymode && fname == NULL) {
headless_mode = true;
}
#ifdef MSWIN
// on windows we use CONIN special file, thus we don't know this yet.
bool has_term = true;
#else
bool has_term = (stdin_isatty || stdout_isatty || stderr_isatty);
#endif
bool use_builtin_ui = (has_term && !headless_mode && !embedded_mode && !silent_mode);
if (params.remote) {
remote_request(¶ms, params.remote, params.server_addr, argc, argv,
use_builtin_ui);
}
bool remote_ui = (ui_client_channel_id != 0);
if (use_builtin_ui && !remote_ui) {
ui_client_forward_stdin = !stdin_isatty;
uint64_t rv = ui_client_start_server(get_vim_var_str(VV_PROGPATH),
(size_t)params.argc, params.argv);
if (!rv) {
fprintf(stderr, "Failed to start Nvim server!\n");
os_exit(1);
}
ui_client_channel_id = rv;
}
// NORETURN: Start builtin UI client.
if (ui_client_channel_id) {
ui_client_run(); // NORETURN
}
assert(!ui_client_channel_id && !use_builtin_ui);
// Nvim server...
if (!server_init(params.listen_addr)) {
#ifdef MSWIN
// Restore the original stderr (pipe to TUI client) so print_mainerr()
// output is visible in the TUI terminal via the relay in on_channel_output.
if (startup_stderr_fd >= 0) {
dup2(startup_stderr_fd, STDERR_FILENO);
close(startup_stderr_fd);
startup_stderr_fd = -1;
}
#endif
mainerr(IObuff, NULL, NULL);
}
#ifdef MSWIN
// Server started successfully. Close the saved fd so the pipe write end is
// fully released — child processes inherit CONOUT$ (fd 2), not the pipe.
if (startup_stderr_fd >= 0) {
close(startup_stderr_fd);
startup_stderr_fd = -1;
}
#endif
TIME_MSG("expanding arguments");
if (params.diff_mode && params.window_count == -1) {
params.window_count = 0; // open up to 3 windows
}
// Don't redraw until much later.
RedrawingDisabled++;
setbuf(stdout, NULL); // NOLINT(bugprone-unsafe-functions)
full_screen = !silent_mode;
// Set the default values for the options that use Rows and Columns.
win_init_size();
// Set the 'diff' option now, so that it can be checked for in a vimrc
// file. There is no buffer yet though.
if (params.diff_mode) {
diff_win_options(firstwin, false);
}
assert(p_ch >= 0 && Rows >= p_ch && Rows - p_ch <= INT_MAX);
cmdline_row = Rows - (int)p_ch;
msg_row = cmdline_row;
default_grid_alloc(); // allocate screen buffers
set_init_2(headless_mode);
TIME_MSG("inits 2");
msg_scroll = true;
no_wait_return = true;
init_highlight(true, false); // Default highlight groups.
ui_comp_syn_init();
TIME_MSG("init highlight");
// Set the break level after the terminal is initialized.
debug_break_level = params.use_debug_break_level;
// Read ex-commands if invoked with "-es".
if (!stdin_isatty && !params.input_istext && silent_mode && exmode_active) {
input_start();
}
// Wait for UIs to set up Nvim or show early messages
// and prompts (--cmd, swapfile dialog, …).
bool use_remote_ui = (embedded_mode && !headless_mode);
if (use_remote_ui) {
TIME_MSG("waiting for UI");
remote_ui_wait_for_attach();
TIME_MSG("done waiting for UI");
firstwin->w_prev_height = firstwin->w_height; // may have changed
}
// prepare screen now
starting = NO_BUFFERS;
screenclear();
win_new_screensize();
TIME_MSG("clear screen");
// Handle "foo | nvim". EDIT_FILE may be overwritten now. #6299
if (edit_stdin(¶ms)) {
params.edit_type = EDIT_STDIN;
}
if (params.scriptin) {
if (!open_scriptin(params.scriptin)) {
os_exit(2);
}
}
if (params.scriptout) {
scriptout = os_fopen(params.scriptout, params.scriptout_append ? APPENDBIN : WRITEBIN);
if (scriptout == NULL) {
fprintf(stderr, _("Cannot open for script output: \""));
fprintf(stderr, "%s\"\n", params.scriptout);
os_exit(2);
}
}
nlua_init_defaults();
TIME_MSG("init default mappings & autocommands");
bool vimrc_none = strequal(params.use_vimrc, "NONE");
// Reset 'loadplugins' for "-u NONE" before "--cmd" arguments.
// Allows for setting 'loadplugins' there.
// For --clean we still want to load plugins.
p_lpl = vimrc_none ? params.clean : p_lpl;
// Execute --cmd arguments.
exe_pre_commands(¶ms);
if (!vimrc_none || params.clean) {
// Sources ftplugin.vim and indent.vim. We do this *before* the user startup scripts to ensure
// ftplugins run before FileType autocommands defined in the init file (which allows those
// autocommands to overwrite settings from ftplugins).
filetype_plugin_enable();
}
// Source startup scripts.
source_startup_scripts(¶ms);
// If using the runtime (-u is not NONE), enable syntax & filetype plugins.
if (!vimrc_none || params.clean) {
// Sources filetype.lua unless the user explicitly disabled it with :filetype off.
filetype_maybe_enable();
// Sources syntax/syntax.vim. We do this *after* the user startup scripts so that users can
// disable syntax highlighting with `:syntax off` if they wish.
syn_maybe_enable();
}
set_vim_var_nr(VV_VIM_DID_INIT, 1);
// Read all the plugin files.
load_plugins();
// Decide about window layout for diff mode after reading vimrc.
set_window_layout(¶ms);
// "nvim -r" (recovery mode) without a file name: List swap files.
if (recoverymode && fname == NULL) {
typval_T items_tv;
tv_list_alloc_ret(&items_tv, 0);
recover_names(NULL, false, items_tv.vval.v_list);
typval_T lua_args[] = { items_tv, { .v_type = VAR_UNKNOWN } };
nlua_call_typval("vim._core.swapfile", "list_swaps", lua_args, NULL);
tv_clear(&items_tv);
os_exit(0);
}
// Set some option defaults after reading vimrc files.
set_init_3();
TIME_MSG("inits 3");
// "-n" argument: Disable swap file by setting 'updatecount' to 0.
// Note that this overrides anything from a vimrc file.
if (params.no_swap_file) {
p_uc = 0;
}
// XXX: Minimize 'updatetime' for -es/-Es. #7679
if (silent_mode) {
p_ut = 1;
}
// Read in registers, history etc, from the ShaDa file.
// This is where v:oldfiles gets filled.
if (*p_shada != NUL) {
shada_read_everything(NULL, false, true);
TIME_MSG("reading ShaDa");
}
// It's better to make v:oldfiles an empty list than NULL.
if (get_vim_var_list(VV_OLDFILES) == NULL) {
set_vim_var_list(VV_OLDFILES, tv_list_alloc(0));
}
// "-q errorfile": Load the error file now.
// If the error file can't be read, exit before doing anything else.
handle_quickfix(¶ms);
//
// Start putting things on the screen.
// Scroll screen down before drawing over it
// Clear screen now, so file message will not be cleared.
//
starting = NO_BUFFERS;
no_wait_return = false;
if (!exmode_active) {
msg_scroll = false;
}
// Read file (text, not commands) from stdin if:
// - stdin is not a tty
// - and -e/-es was not given
//
// Do this before starting Raw mode, because it may change things that the
// writing end of the pipe doesn't like, e.g., in case stdin and stderr
// are the same terminal: "cat | vim -".
// Using autocommands here may cause trouble...
if (params.edit_type == EDIT_STDIN && !recoverymode) {
read_stdin();
}
setmouse(); // may start using the mouse
redraw_later(curwin, UPD_VALID);
no_wait_return = true;
// Create the requested number of windows and edit buffers in them.
// Also does recovery if "recoverymode" set.
create_windows(¶ms);
TIME_MSG("opening buffers");
// Clear v:swapcommand
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
// Ex starts at last line of the file.
if (exmode_active) {
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
}
apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
TIME_MSG("BufEnter autocommands");
setpcmark();
// When started with "-q errorfile" jump to first error now.
if (params.edit_type == EDIT_QF) {
qf_jump(NULL, 0, 0, false);
TIME_MSG("jump to first error");
}
// If opened more than one window, start editing files in the other
// windows.
edit_buffers(¶ms);
if (params.diff_mode) {
// set options in each window for "nvim -d".
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (!wp->w_arg_idx_invalid) {
diff_win_options(wp, true);
}
}
}
// Shorten any of the filenames, but only when absolute.
shorten_fnames(false);
// Need to jump to the tag before executing the '-c command'.
// Makes "vim -c '/return' -t main" work.
handle_tag(params.tagname);
// Execute any "+", "-c" and "-S" arguments.
if (params.n_commands > 0) {
exe_commands(¶ms);
}
starting = 0;
RedrawingDisabled = 0;
redraw_all_later(UPD_NOT_VALID);
no_wait_return = false;
// 'autochdir' has been postponed.
do_autochdir();
set_vim_var_nr(VV_VIM_DID_ENTER, 1);
apply_autocmds(EVENT_VIMENTER, NULL, NULL, false, curbuf);
TIME_MSG("VimEnter autocommands");
if (use_remote_ui) {
do_autocmd_uienter_all();
TIME_MSG("UIEnter autocommands");
}
#ifdef MSWIN
if (use_remote_ui) {
os_icon_init();
}
os_title_save();
#endif
// Adjust default register name for "unnamed" in 'clipboard'. Can only be
// done after the clipboard is available and all initial commands that may
// modify the 'clipboard' setting have run; i.e. just before entering the
// main loop.
set_reg_var(get_default_register_name());
// When a startup script or session file setup for diff'ing and
// scrollbind, sync the scrollbind now.
if (curwin->w_p_diff && curwin->w_p_scb) {
update_topline(curwin);
check_scrollbind(0, 0);
TIME_MSG("diff scrollbinding");
}
// If ":startinsert" command used, stuff a dummy command to be able to
// call normal_cmd(), which will then start Insert mode.
if (restart_edit != 0) {
stuffcharReadbuff(K_NOP);
}
// WORKAROUND(mhi): #3023
if (cb_flags & (kOptCbFlagUnnamed | kOptCbFlagUnnamedplus)) {
eval_has_provider("clipboard", false);
}
if (params.luaf != NULL) {
// Like "--cmd", "+", "-c" and "-S", don't truncate messages.
msg_scroll = true;
DLOG("executing Lua -l script");
bool lua_ok = nlua_exec_file(params.luaf);
TIME_MSG("executing Lua -l script");
if (msg_didout) {
msg_putchar('\n');
msg_didout = false;
}
getout(lua_ok ? 0 : 1);
}
TIME_MSG("before starting main loop");
ILOG("starting main loop");
// Main loop: never returns.
normal_enter(false);
#if defined(MSWIN) && !defined(MAKE_LIB)
xfree(argv);
#endif
return 0;
}
void os_exit(int r)
FUNC_ATTR_NORETURN
{
exiting = true;
if (ui_client_channel_id) {
ui_client_stop();
if (r == 0) {
r = ui_client_exit_status;
}
} else {
ui_flush();
ui_call_stop();
}
if (!event_teardown() && r == 0) {
r = 1; // Exit with error if main_loop did not teardown gracefully.
}
if (ui_client_channel_id) {
#ifdef HAVE_TERMIOS_H
// Sometimes the final output to TTY can be lost (at least on FreeBSD).
// Call tcdrain() to ensure all output has been transmitted to host terminal.
// Do this after event_teardown() as libuv events may write to stderr.
if (stdout_isatty) {
tcdrain(STDOUT_FILENO);
}
if (stderr_isatty) {
tcdrain(STDERR_FILENO);
}
#endif
} else {
ml_close_all(true); // remove all memfiles
}
if (used_stdin) {
stream_set_blocking(STDIN_FILENO, true); // normalize stream (#2598)
}
ILOG("Nvim exit: %d", r);
#ifdef EXITFREE
free_all_mem();
#endif
exit(r);
}
/// Exit properly
void getout(int exitval)
FUNC_ATTR_NORETURN
{
assert(!ui_client_channel_id);
exiting = true;
// make sure startuptimes have been flushed
time_finish();
// On error during Ex mode, exit with a non-zero code.
// POSIX requires this, although it's not 100% clear from the standard.
if (exmode_active) {
exitval += ex_exitval;
}
set_vim_var_type(VV_EXITING, VAR_NUMBER);
set_vim_var_nr(VV_EXITING, exitval);
// Set v:exitreason if not already set (e.g. by :restart).
if (*get_vim_var_str(VV_EXITREASON) == NUL) {
set_vim_var_string(VV_EXITREASON, S_LEN("quit"));
}
// Invoked all ":defer" functions in the function stack.
invoke_all_defer();
// Optionally print hashtable efficiency.
hash_debug_results();
if (v_dying <= 1) {
const tabpage_T *next_tp;
// Trigger BufWinLeave for all windows, but only once per buffer.
for (const tabpage_T *tp = first_tabpage; tp != NULL; tp = next_tp) {
next_tp = tp->tp_next;
FOR_ALL_WINDOWS_IN_TAB(wp, tp) {
if (wp->w_buffer == NULL || !buf_valid(wp->w_buffer)) {
// Autocmd must have close the buffer already, skip.
continue;
}
buf_T *buf = wp->w_buffer;
if (buf_get_changedtick(buf) != -1) {
bufref_T bufref;
set_bufref(&bufref, buf);
apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, false, buf);
if (bufref_valid(&bufref)) {
buf_set_changedtick(buf, -1); // note that we did it already
}
// start all over, autocommands may mess up the lists
next_tp = first_tabpage;
break;
}
}
}
// Trigger BufUnload for buffers that are loaded
FOR_ALL_BUFFERS(buf) {
if (buf->b_ml.ml_mfp != NULL) {
bufref_T bufref;
set_bufref(&bufref, buf);
apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, false, buf);
if (!bufref_valid(&bufref)) {
// Autocmd deleted the buffer.
break;
}
}
}
int unblock = 0;
// deathtrap() blocks autocommands, but we do want to trigger
// VimLeavePre.
if (is_autocmd_blocked()) {
unblock_autocmds();
unblock++;
}
apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, false, curbuf);
if (unblock) {
block_autocmds();
}
}
if (
#ifdef EXITFREE
!entered_free_all_mem &&
#endif
p_shada && *p_shada != NUL) {
// Write out the registers, history, marks etc, to the ShaDa file
shada_write_file(NULL, false);
}
if (v_dying <= 1) {
int unblock = 0;
// deathtrap() blocks autocommands, but we do want to trigger VimLeave.
if (is_autocmd_blocked()) {
unblock_autocmds();
unblock++;
}
apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, false, curbuf);
if (unblock) {
block_autocmds();
}
}
profile_dump();
if (did_emsg) {
// give the user a chance to read the (error) message
no_wait_return = false;
// TODO(justinmk): this may call getout(0), clobbering exitval...
wait_return(false);
}
// Apply 'titleold'.
if (p_title && *p_titleold != NUL) {
ui_call_set_title(cstr_as_string(p_titleold));
}
if (garbage_collect_at_exit) {
garbage_collect(false);
}
#ifdef MSWIN
// Restore Windows console icon before exiting.
os_icon_reset();
os_title_reset();
#endif
os_exit(exitval);
}
/// Preserve files, print contents of `errmsg`, and exit 1.
/// @param errmsg If NULL, this function will not print anything.
///
/// May be called from deadly_signal().
void preserve_exit(const char *errmsg)
FUNC_ATTR_NORETURN
{
// 'true' when we are sure to exit, e.g., after a deadly signal
static bool really_exiting = false;
// Prevent repeated calls into this method.
if (really_exiting) {
if (used_stdin) {
// normalize stream (#2598)
stream_set_blocking(STDIN_FILENO, true);
}
exit(2);
}
really_exiting = true;
// Ignore SIGHUP while we are already exiting. #9274
signal_reject_deadly();
if (ui_client_channel_id) {
// For TUI: exit alternate screen so that the error messages can be seen.
ui_client_stop();
}
if (errmsg != NULL && errmsg[0] != NUL) {
bool has_eol = '\n' == errmsg[strlen(errmsg) - 1];
fprintf(stderr, has_eol ? "%s" : "%s\n", errmsg);
}
if (ui_client_channel_id) {
os_exit(1);
}
ml_close_notmod(); // close all not-modified buffers
FOR_ALL_BUFFERS(buf) {
if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) {
if (errmsg != NULL) {
fprintf(stderr, "Nvim: preserving files...\n");
}
ml_sync_all(false, false, true); // preserve all swap files
break;
}
}
ml_close_all(false); // close all memfiles, without deleting
if (errmsg != NULL) {
fprintf(stderr, "Nvim: Finished.\n");
}
getout(1);
}
/// Gets the integer value of a numeric command line argument if given,
/// such as '-o10'.
///
/// @param[in] p pointer to argument
/// @param[in, out] idx pointer to index in argument, is incremented
/// @param[in] def default value
///
/// @return def unmodified if:
/// - argument isn't given
/// - argument is non-numeric
///
/// @return argument's numeric value otherwise
static int get_number_arg(const char *p, int *idx, int def)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
if (ascii_isdigit(p[*idx])) {
def = atoi(&(p[*idx]));
while (ascii_isdigit(p[*idx])) {
*idx = *idx + 1;
}
}
return def;
}
static uint64_t server_connect(char *server_addr, const char **errmsg)
{
if (server_addr == NULL) {
*errmsg = "no address specified";
return 0;
}
CallbackReader on_data = CALLBACK_READER_INIT;
const char *error = NULL;
bool is_tcp = socket_address_tcp_host_end(server_addr) != NULL;
// connected to channel
uint64_t chan = channel_connect(is_tcp, server_addr, true, on_data, 500, &error);
if (error) {
*errmsg = error;
return 0;
}
return chan;
}
/// Handle remote subcommands
static void remote_request(mparm_T *params, int remote_args, char *server_addr, int argc,
char **argv, bool ui_only)
{
bool is_ui = strequal(argv[remote_args], "--remote-ui");
if (ui_only && !is_ui) {
// TODO(bfredl): this implies always starting the TUI.
// if we be smart we could delay this past should_exit
return;
}
const char *connect_error = NULL;
uint64_t chan = server_connect(server_addr, &connect_error);
Object rvobj = OBJECT_INIT;
if (is_ui) {
if (!chan) {
#ifdef MSWIN
// The TUI client is spawned in a ConPTY which only captures stdout.
// Redirect stderr to stdout so this error appears in the terminal.
dup2(STDOUT_FILENO, STDERR_FILENO);
#endif
fprintf(stderr, "Remote ui failed to start: %s\n", connect_error);
os_exit(1);
} else if (strequal(server_addr, os_getenv_noalloc("NVIM"))) {
fprintf(stderr, "%s", "Cannot attach UI of :terminal child to its parent. ");
fprintf(stderr, "%s\n", "(Unset $NVIM to skip this check)");
os_exit(1);
}
ui_client_channel_id = chan;