forked from neovim/neovim
/
main.c
1971 lines (1738 loc) · 59.8 KB
/
main.c
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
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#define EXTERN
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#ifdef WIN32
# include <wchar.h>
# include <winnls.h>
#endif
#include <msgpack.h>
#include "nvim/ascii.h"
#include "nvim/vim.h"
#include "nvim/main.h"
#include "nvim/buffer.h"
#include "nvim/charset.h"
#include "nvim/diff.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_cmds2.h"
#include "nvim/ex_docmd.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/getchar.h"
#include "nvim/hashtab.h"
#include "nvim/iconv.h"
#include "nvim/if_cscope.h"
#ifdef HAVE_LOCALE_H
# include <locale.h>
#endif
#include "nvim/mark.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/garray.h"
#include "nvim/log.h"
#include "nvim/memory.h"
#include "nvim/move.h"
#include "nvim/mouse.h"
#include "nvim/normal.h"
#include "nvim/ops.h"
#include "nvim/option.h"
#include "nvim/os_unix.h"
#include "nvim/os/os_defs.h"
#include "nvim/path.h"
#include "nvim/profile.h"
#include "nvim/quickfix.h"
#include "nvim/screen.h"
#include "nvim/state.h"
#include "nvim/strings.h"
#include "nvim/syntax.h"
#include "nvim/ui.h"
#include "nvim/version.h"
#include "nvim/window.h"
#include "nvim/shada.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
#include "nvim/os/time.h"
#include "nvim/os/fileio.h"
#include "nvim/event/loop.h"
#include "nvim/os/signal.h"
#include "nvim/event/process.h"
#include "nvim/msgpack_rpc/helpers.h"
#include "nvim/msgpack_rpc/server.h"
#include "nvim/msgpack_rpc/channel.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
#include "nvim/api/private/handle.h"
#include "nvim/api/private/dispatch.h"
/* Maximum number of commands from + or -c arguments. */
#define MAX_ARG_CMDS 10
/* values for "window_layout" */
#define WIN_HOR 1 /* "-o" horizontally split windows */
#define WIN_VER 2 /* "-O" vertically split windows */
#define WIN_TABS 3 /* "-p" windows on tab pages */
/* Struct for various parameters passed between main() and other functions. */
typedef struct {
int argc;
char **argv;
char *use_vimrc; // vimrc from -u argument
int n_commands; /* no. of commands from + or -c */
char *commands[MAX_ARG_CMDS]; // commands from + or -c arg
char_u cmds_tofree[MAX_ARG_CMDS]; /* commands that need free() */
int n_pre_commands; /* no. of commands from --cmd */
char *pre_commands[MAX_ARG_CMDS]; // commands from --cmd argument
int edit_type; /* type of editing to do */
char_u *tagname; /* tag from -t argument */
char_u *use_ef; /* 'errorfile' from -q argument */
int want_full_screen;
bool input_isatty; // stdin is a terminal
bool output_isatty; // stdout is a terminal
bool err_isatty; // stderr is a terminal
bool headless; // Do not start the builtin UI.
int no_swap_file; // "-n" argument used
int use_debug_break_level;
int window_count; /* number of windows to use */
int window_layout; /* 0, WIN_HOR, WIN_VER or WIN_TABS */
#if !defined(UNIX)
int literal; /* don't expand file names */
#endif
int diff_mode; /* start with 'diff' set */
} mparm_T;
/* Values for edit_type. */
#define EDIT_NONE 0 /* no edit type yet */
#define EDIT_FILE 1 /* file name argument[s] given, use argument list */
#define EDIT_STDIN 2 /* read file from stdin */
#define EDIT_TAG 3 /* tag name argument given, use tagname */
#define EDIT_QF 4 /* start in quickfix mode */
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "main.c.generated.h"
#endif
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);
// early msgpack-rpc initialization
msgpack_rpc_init_method_table();
msgpack_rpc_helpers_init();
// Initialize input events
input_init();
// Timer to wake the event loop if a timeout argument is passed to
// `event_poll`
// Signals
signal_init();
// finish mspgack-rpc initialization
channel_init();
server_init();
terminal_init();
}
/// @returns false if main_loop could not be closed gracefully
bool event_teardown(void)
{
if (!main_loop.events) {
return true;
}
multiqueue_process_events(main_loop.events);
input_stop();
channel_teardown();
process_teardown(&main_loop);
timer_teardown();
server_teardown();
signal_teardown();
terminal_teardown();
return loop_close(&main_loop, true);
}
/// Performs early initialization.
///
/// Needed for unit tests. Must be called after `time_init()`.
void early_init(void)
{
log_init();
fs_init();
handle_init();
eval_init(); // init global variables
init_path(argv0 ? argv0 : "nvim");
init_normal_cmds(); // Init the table of Normal mode commands.
#if defined(HAVE_LOCALE_H)
// 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();
#endif
// Allocate the first window and buffer.
// Can't do anything without it, exit when it fails.
if (!win_alloc_first()) {
mch_exit(0);
}
init_yank(); // init yank buffers
alist_init(&global_alist); // Init the argument list to empty.
global_alist.id = 0;
// Set the default values for the options.
// NOTE: Non-latin1 translated messages are working only after this,
// because this is where "has_mbyte" will be set, which is used by
// msg_outtrans_len_attr().
// First find out the home directory, needed to expand "~" in options.
init_homedir(); // find real value of $HOME
set_init_1();
TIME_MSG("inits 1");
set_lang_var(); // set v:lang and v:ctype
}
#ifdef MAKE_LIB
int nvim_main(int argc, char **argv)
#elif defined(WIN32)
int wmain(int argc, wchar_t **argv_w) // multibyte args on Windows. #7060
#else
int main(int argc, char **argv)
#endif
{
#if defined(WIN32) && !defined(MAKE_LIB)
char *argv[argc];
for (int i = 0; i < argc; i++) {
char *buf = NULL;
utf16_to_utf8(argv_w[i], &buf);
assert(buf);
argv[i] = buf;
}
#endif
argv0 = argv[0];
char_u *fname = NULL; // file name from command line
mparm_T params; // various parameters passed between
// main() and other functions.
char_u *cwd = NULL; // current workding dir on startup
time_init();
/* Many variables are in "params" so that we can pass them to invoked
* functions without a lot of arguments. "argc" and "argv" are also
* copied, so that they can be changed. */
init_params(¶ms, argc, argv);
init_startuptime(¶ms);
early_init();
// Check if we have an interactive window.
check_and_set_isatty(¶ms);
event_init();
/*
* Process the command line arguments. File names are put in the global
* argument list "global_alist".
*/
command_line_scan(¶ms);
if (GARGCOUNT > 0) {
fname = get_fname(¶ms, cwd);
}
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;
/*
* When listing swap file names, don't do cursor positioning et. al.
*/
if (recoverymode && fname == NULL)
params.want_full_screen = FALSE;
setbuf(stdout, NULL);
full_screen = true;
check_tty(¶ms);
/*
* 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 = (int)(Rows - p_ch);
msg_row = cmdline_row;
screenalloc(false); /* allocate screen buffers */
set_init_2(params.headless);
TIME_MSG("inits 2");
msg_scroll = TRUE;
no_wait_return = TRUE;
init_highlight(TRUE, FALSE); /* set the default highlight groups */
TIME_MSG("init highlight");
/* Set the break level after the terminal is initialized. */
debug_break_level = params.use_debug_break_level;
bool reading_input = !params.headless && (params.input_isatty
|| params.output_isatty || params.err_isatty);
if (reading_input) {
// One of the startup commands (arguments, sourced scripts or plugins) may
// prompt the user, so start reading from a tty now.
int fd = fileno(stdin);
if (!params.input_isatty || params.edit_type == EDIT_STDIN) {
// Use stderr or stdout since stdin is not a tty and/or could be used to
// read the "-" file (eg: cat file | nvim -)
fd = params.err_isatty ? fileno(stderr) : fileno(stdout);
}
input_start(fd);
}
// open terminals when opening files that start with term://
#define PROTO "term://"
do_cmdline_cmd("augroup nvim_terminal");
do_cmdline_cmd("autocmd!");
do_cmdline_cmd("autocmd BufReadCmd " PROTO "* nested "
":if !exists('b:term_title')|call termopen( "
// Capture the command string
"matchstr(expand(\"<amatch>\"), "
"'\\c\\m" PROTO "\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), "
// capture the working directory
"{'cwd': get(matchlist(expand(\"<amatch>\"), "
"'\\c\\m" PROTO "\\(.\\{-}\\)//'), 1, '')})"
"|endif");
do_cmdline_cmd("augroup END");
#undef PROTO
// Reset 'loadplugins' for "-u NONE" before "--cmd" arguments.
// Allows for setting 'loadplugins' there.
if (params.use_vimrc != NULL && strcmp(params.use_vimrc, "NONE") == 0) {
p_lpl = false;
}
/* Execute --cmd arguments. */
exe_pre_commands(¶ms);
/* Source startup scripts. */
source_startup_scripts(¶ms);
// If using the runtime (-u is not NONE), enable syntax & filetype plugins.
if (params.use_vimrc == NULL || strcmp(params.use_vimrc, "NONE") != 0) {
// Does ":filetype plugin indent on".
filetype_maybe_enable();
// Sources syntax/syntax.vim, which calls `:filetype on`.
syn_maybe_on();
}
/*
* Read all the plugin files.
* Only when compiled with +eval, since most plugins need it.
*/
load_plugins();
// Decide about window layout for diff mode after reading vimrc.
set_window_layout(¶ms);
/*
* Recovery mode without a file name: List swap files.
* This uses the 'dir' option, therefore it must be after the
* initializations.
*/
if (recoverymode && fname == NULL) {
recover_names(NULL, TRUE, 0, NULL);
mch_exit(0);
}
// Set a few option defaults after reading vimrc files:
// 'title' and 'icon', Unix: 'shellpipe' and 'shellredir'.
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;
if (curwin->w_p_rl && p_altkeymap) {
p_hkmap = FALSE; /* Reset the Hebrew keymap mode */
curwin->w_p_arab = FALSE; /* Reset the Arabic keymap mode */
p_fkmap = TRUE; /* Set the Farsi keymap mode */
}
/*
* 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());
}
/*
* "-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;
/*
* If "-" argument given: Read file from stdin.
* 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();
if (reading_input && (need_wait_return || msg_didany)) {
// Since at this point there's no UI instance running yet, error messages
// would have been printed to stdout. Before starting (which can result in
// a alternate screen buffer being shown) we need confirmation that the
// user has seen the messages and that is done with a call to wait_return.
TIME_MSG("waiting for return");
wait_return(TRUE);
}
if (!params.headless) {
// Stop reading from input stream, the UI layer will take over now.
input_stop();
ui_builtin_start();
}
setmouse(); // may start using the mouse
ui_reset_scroll_region(); // In case Rows changed
// Don't clear the screen when starting in Ex mode, unless using the GUI.
if (exmode_active)
must_redraw = CLEAR;
else {
screenclear(); /* clear screen */
TIME_MSG("clearing screen");
}
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, cwd);
xfree(cwd);
if (params.diff_mode) {
/* set options in each window for "nvim -d". */
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
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);
RedrawingDisabled = 0;
redraw_all_later(NOT_VALID);
no_wait_return = FALSE;
starting = 0;
// 'autochdir' has been postponed.
do_autochdir();
/* start in insert mode */
if (p_im)
need_start_insertmode = TRUE;
set_vim_var_nr(VV_VIM_DID_ENTER, 1L);
apply_autocmds(EVENT_VIMENTER, NULL, NULL, false, curbuf);
TIME_MSG("VimEnter autocommands");
// 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();
check_scrollbind((linenr_T)0, 0L);
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 & CB_UNNAMEDMASK) {
(void)eval_has_provider("clipboard");
}
TIME_MSG("before starting main loop");
ILOG("starting main loop");
/*
* Call the main command loop. This never returns.
*/
normal_enter(false, false);
return 0;
}
/* Exit properly */
void getout(int exitval)
{
tabpage_T *tp, *next_tp;
exiting = TRUE;
/* When running in Ex mode an error causes us to exit with a non-zero exit
* code. POSIX requires this, although it's not 100% clear from the
* standard. */
if (exmode_active)
exitval += ex_exitval;
set_vim_var_nr(VV_EXITING, exitval);
/* Position the cursor on the last screen line, below all the text */
ui_cursor_goto((int)Rows - 1, 0);
/* Optionally print hashtable efficiency. */
hash_debug_results();
if (get_vim_var_nr(VV_DYING) <= 1) {
/* Trigger BufWinLeave for all windows, but only once per buffer. */
for (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) {
/* Autocmd must have close the buffer already, skip. */
continue;
}
buf_T *buf = wp->w_buffer;
if (buf->b_changedtick != -1) {
apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname,
buf->b_fname, false, buf);
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;
}
}
}
apply_autocmds(EVENT_VIMLEAVEPRE, NULL, NULL, FALSE, curbuf);
}
if (p_shada && *p_shada != NUL) {
// Write out the registers, history, marks etc, to the ShaDa file
shada_write_file(NULL, false);
}
if (get_vim_var_nr(VV_DYING) <= 1)
apply_autocmds(EVENT_VIMLEAVE, NULL, NULL, FALSE, curbuf);
profile_dump();
if (did_emsg
) {
/* give the user a chance to read the (error) message */
no_wait_return = FALSE;
wait_return(FALSE);
}
/* Position the cursor again, the autocommands may have moved it */
ui_cursor_goto((int)Rows - 1, 0);
#if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
iconv_end();
#endif
cs_end();
if (garbage_collect_at_exit) {
garbage_collect(false);
}
mch_exit(exitval);
}
/// 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])) { // -V522
def = atoi(&(p[*idx]));
while (ascii_isdigit(p[*idx])) {
*idx = *idx + 1;
}
}
return def;
}
#if defined(HAVE_LOCALE_H)
/*
* Setup to use the current locale (for ctype() and many other things).
*/
static void init_locale(void)
{
setlocale(LC_ALL, "");
# ifdef LC_NUMERIC
/* Make sure strtod() uses a decimal point, not a comma. */
setlocale(LC_NUMERIC, "C");
# endif
# ifdef LOCALE_INSTALL_DIR // gnu/linux standard: $prefix/share/locale
bindtextdomain(PROJECT_NAME, LOCALE_INSTALL_DIR);
# else // old vim style: $runtime/lang
{
char_u *p;
// expand_env() doesn't work yet, because g_chartab[] is not
// initialized yet, call vim_getenv() directly
p = (char_u *)vim_getenv("VIMRUNTIME");
if (p != NULL && *p != NUL) {
vim_snprintf((char *)NameBuff, MAXPATHL, "%s/lang", p);
bindtextdomain(PROJECT_NAME, (char *)NameBuff);
}
xfree(p);
}
# endif
textdomain(PROJECT_NAME);
TIME_MSG("locale set");
}
#endif
/*
* Scan the command line arguments.
*/
static void command_line_scan(mparm_T *parmp)
{
int argc = parmp->argc;
char **argv = parmp->argv;
int argv_idx; /* index in argv[n][] */
int had_minmin = FALSE; /* found "--" argument */
int want_argument; /* option argument with argument */
int c;
char_u *p = NULL;
long n;
--argc;
++argv;
argv_idx = 1; /* active option letter is argv[0][argv_idx] */
while (argc > 0) {
/*
* "+" or "+{number}" or "+/{pat}" or "+{command}" argument.
*/
if (argv[0][0] == '+' && !had_minmin) {
if (parmp->n_commands >= MAX_ARG_CMDS)
mainerr(err_extra_cmd, NULL);
argv_idx = -1; /* skip to next argument */
if (argv[0][1] == NUL)
parmp->commands[parmp->n_commands++] = "$";
else
parmp->commands[parmp->n_commands++] = &(argv[0][1]);
}
/*
* Optional argument.
*/
else if (argv[0][0] == '-' && !had_minmin) {
want_argument = FALSE;
c = argv[0][argv_idx++];
switch (c) {
case NUL: /* "vim -" read from stdin */
if (exmode_active) {
// "ex -" silent mode
silent_mode = TRUE;
} else {
if (parmp->edit_type != EDIT_NONE) {
mainerr(err_too_many_args, argv[0]);
}
parmp->edit_type = EDIT_STDIN;
}
argv_idx = -1; /* skip to next argument */
break;
case '-': /* "--" don't take any more option arguments */
/* "--help" give help message */
/* "--version" give version message */
/* "--literal" take files literally */
/* "--noplugin[s]" skip plugins */
/* "--cmd <cmd>" execute cmd before vimrc */
if (STRICMP(argv[0] + argv_idx, "help") == 0) {
usage();
mch_exit(0);
} else if (STRICMP(argv[0] + argv_idx, "version") == 0) {
version();
mch_exit(0);
} else if (STRICMP(argv[0] + argv_idx, "api-info") == 0) {
FileDescriptor fp;
const int fof_ret = file_open_fd(&fp, OS_STDOUT_FILENO, true);
msgpack_packer *p = msgpack_packer_new(&fp, msgpack_file_write);
if (fof_ret != 0) {
emsgf(_("E5421: Failed to open stdin: %s"), os_strerror(fof_ret));
}
if (p == NULL) {
emsgf(_(e_outofmem));
}
Object md = DICTIONARY_OBJ(api_metadata());
msgpack_rpc_from_object(md, p);
msgpack_packer_free(p);
const int ff_ret = file_flush(&fp);
if (ff_ret < 0) {
msgpack_file_write_error(ff_ret);
}
mch_exit(0);
} else if (STRICMP(argv[0] + argv_idx, "headless") == 0) {
parmp->headless = true;
} else if (STRICMP(argv[0] + argv_idx, "embed") == 0) {
embedded_mode = true;
parmp->headless = true;
channel_from_stdio();
} else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0) {
#if !defined(UNIX)
parmp->literal = TRUE;
#endif
} else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0)
p_lpl = FALSE;
else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0) {
want_argument = TRUE;
argv_idx += 3;
} else if (STRNICMP(argv[0] + argv_idx, "startuptime", 11) == 0) {
want_argument = TRUE;
argv_idx += 11;
} else {
if (argv[0][argv_idx])
mainerr(err_opt_unknown, argv[0]);
had_minmin = TRUE;
}
if (!want_argument)
argv_idx = -1; /* skip to next argument */
break;
case 'A': { // "-A" start in Arabic mode.
set_option_value("arabic", 1L, NULL, 0);
break;
}
case 'b': { // "-b" binary mode.
// Needs to be effective before expanding file names, because
// for Win32 this makes us edit a shortcut file itself,
// instead of the file it links to.
set_options_bin(curbuf->b_p_bin, 1, 0);
curbuf->b_p_bin = 1; // Binary file I/O.
break;
}
case 'e': /* "-e" Ex mode */
exmode_active = EXMODE_NORMAL;
break;
case 'E': /* "-E" Improved Ex mode */
exmode_active = EXMODE_VIM;
break;
case 'f': /* "-f" GUI: run in foreground. */
break;
case 'g': /* "-g" start GUI */
main_start_gui();
break;
case 'F': { // "-F" start in Farsi mode: rl + fkmap set.
p_fkmap = true;
set_option_value("rl", 1L, NULL, 0);
break;
}
case 'h': /* "-h" give help message */
usage();
mch_exit(0);
case 'H': { // "-H" start in Hebrew mode: rl + hkmap set.
p_hkmap = true;
set_option_value("rl", 1L, NULL, 0);
break;
}
case 'l': { // "-l" lisp mode, 'lisp' and 'showmatch' on.
set_option_value("lisp", 1L, NULL, 0);
p_sm = true;
break;
}
case 'M': /* "-M" no changes or writing of files */
reset_modifiable();
/* FALLTHROUGH */
case 'm': /* "-m" no writing of files */
p_write = FALSE;
break;
case 'N': /* "-N" Nocompatible */
/* No-op */
break;
case 'n': /* "-n" no swap file */
parmp->no_swap_file = TRUE;
break;
case 'p': /* "-p[N]" open N tab pages */
#ifdef TARGET_API_MAC_OSX
/* For some reason on MacOS X, an argument like:
-psn_0_10223617 is passed in when invoke from Finder
or with the 'open' command */
if (argv[0][argv_idx] == 's') {
argv_idx = -1; /* bypass full -psn */
main_start_gui();
break;
}
#endif
/* default is 0: open window for each file */
parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
parmp->window_layout = WIN_TABS;
break;
case 'o': /* "-o[N]" open N horizontal split windows */
/* default is 0: open window for each file */
parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
parmp->window_layout = WIN_HOR;
break;
case 'O': /* "-O[N]" open N vertical split windows */
/* default is 0: open window for each file */
parmp->window_count = get_number_arg(argv[0], &argv_idx, 0);
parmp->window_layout = WIN_VER;
break;
case 'q': /* "-q" QuickFix mode */
if (parmp->edit_type != EDIT_NONE)
mainerr(err_too_many_args, argv[0]);
parmp->edit_type = EDIT_QF;
if (argv[0][argv_idx]) { /* "-q{errorfile}" */
parmp->use_ef = (char_u *)argv[0] + argv_idx;
argv_idx = -1;
} else if (argc > 1) /* "-q {errorfile}" */
want_argument = TRUE;
break;
case 'R': /* "-R" readonly mode */
readonlymode = TRUE;
curbuf->b_p_ro = TRUE;
p_uc = 10000; /* don't update very often */
break;
case 'r': /* "-r" recovery mode */
case 'L': /* "-L" recovery mode */
recoverymode = 1;
break;
case 's':
if (exmode_active) { // "-es" silent (batch) mode
silent_mode = true;
} else { // "-s {scriptin}" read from script file
want_argument = true;
}
break;
case 't': /* "-t {tag}" or "-t{tag}" jump to tag */
if (parmp->edit_type != EDIT_NONE)
mainerr(err_too_many_args, argv[0]);
parmp->edit_type = EDIT_TAG;
if (argv[0][argv_idx]) { /* "-t{tag}" */
parmp->tagname = (char_u *)argv[0] + argv_idx;
argv_idx = -1;
} else /* "-t {tag}" */
want_argument = TRUE;
break;
case 'D': /* "-D" Debugging */
parmp->use_debug_break_level = 9999;
break;
case 'd': /* "-d" 'diff' */
parmp->diff_mode = TRUE;
break;
case 'v':
version();
mch_exit(0);
case 'V': /* "-V{N}" Verbose level */
/* default is 10: a little bit verbose */
p_verbose = get_number_arg(argv[0], &argv_idx, 10);
if (argv[0][argv_idx] != NUL) {
set_option_value("verbosefile", 0L, argv[0] + argv_idx, 0);
argv_idx = (int)STRLEN(argv[0]);
}
break;
case 'w': /* "-w{number}" set window height */
/* "-w {scriptout}" write to script */
if (ascii_isdigit(((char_u *)argv[0])[argv_idx])) {
n = get_number_arg(argv[0], &argv_idx, 10);
set_option_value("window", n, NULL, 0);
break;
}
want_argument = TRUE;
break;
case 'Z': /* "-Z" restricted mode */
restricted = TRUE;
break;
case 'c': /* "-c{command}" or "-c {command}" execute