-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
cmd_core.c
1410 lines (1240 loc) · 30.3 KB
/
cmd_core.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
/* vifm
* Copyright (C) 2001 Ken Steen.
* Copyright (C) 2011 xaizek.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "cmd_core.h"
#include <curses.h>
#include <sys/stat.h> /* gid_t uid_t */
#include <unistd.h> /* unlink() */
#include <assert.h> /* assert() */
#include <ctype.h> /* isspace() */
#include <errno.h> /* errno */
#include <limits.h> /* INT_MAX */
#include <signal.h>
#include <stddef.h> /* NULL size_t */
#include <stdio.h> /* snprintf() */
#include <stdlib.h> /* free() */
#include <string.h> /* strcmp() strcpy() strlen() */
#include "cfg/config.h"
#include "cfg/info.h"
#include "compat/fs_limits.h"
#include "compat/os.h"
#include "engine/autocmds.h"
#include "engine/cmds.h"
#include "engine/mode.h"
#include "engine/parsing.h"
#include "engine/var.h"
#include "engine/variables.h"
#include "int/vim.h"
#include "modes/dialogs/msg_dialog.h"
#include "modes/modes.h"
#include "modes/normal.h"
#include "modes/view.h"
#include "modes/visual.h"
#include "ui/color_scheme.h"
#include "ui/colors.h"
#include "ui/fileview.h"
#include "ui/statusbar.h"
#include "ui/ui.h"
#include "utils/file_streams.h"
#include "utils/filter.h"
#include "utils/fs.h"
#include "utils/hist.h"
#include "utils/int_stack.h"
#include "utils/path.h"
#include "utils/str.h"
#include "utils/string_array.h"
#include "utils/test_helpers.h"
#include "utils/utils.h"
#include "bracket_notation.h"
#include "cmd_completion.h"
#include "cmd_handlers.h"
#include "filelist.h"
#include "filtering.h"
#include "flist_sel.h"
#include "macros.h"
#include "marks.h"
#include "opt_handlers.h"
#include "undo.h"
/* Type of command arguments. */
typedef enum
{
CAT_REGULAR, /* Can be separated by a |. */
CAT_EXPR, /* Accept expressions with || and terminate on |. */
CAT_UNTIL_THE_END, /* Take the rest of line including all |. */
}
CmdArgsType;
/* Values for if_levels stack. */
typedef enum
{
IF_SCOPE_GUARD, /* Command scope marker, prevents mixing of levels. */
IF_BEFORE_MATCH, /* Before condition that evaluates to true is found. */
IF_MATCH, /* Just found true condition and processing that branch. */
IF_AFTER_MATCH, /* Left branch corresponding to true condition. */
IF_ELSE, /* Else branch that should be run (no matches before it). */
IF_FINISH, /* After else branch, only endif is expected by now. */
}
IfFrame;
static int swap_range(void);
static int resolve_mark(char mark);
static char * cmds_expand_macros(const char str[], int for_shell, int *usr1,
int *usr2);
static int setup_extcmd_file(const char path[], const char beginning[],
CmdInputType type);
static void prepare_extcmd_file(FILE *fp, const char beginning[],
CmdInputType type);
static hist_t * history_by_type(CmdInputType type);
static char * get_file_first_line(const char path[]);
static void execute_extcmd(const char command[], CmdInputType type);
static void save_extcmd(const char command[], CmdInputType type);
static void post(int id);
TSTATIC void cmds_select_range(int id, const cmd_info_t *cmd_info);
static int skip_at_beginning(int id, const char args[]);
static void create_builtin_vars(void);
static void session_changed_callback(const char new_session[]);
static char * pattern_expand_hook(const char pattern[]);
static int is_implicit_cd(view_t *view, const char cmd[], int cmd_error);
static int cmd_should_be_processed(int cmd_id);
TSTATIC char ** break_cmdline(const char cmdline[], int for_menu);
static int is_out_of_arg(const char cmd[], const char pos[]);
TSTATIC int line_pos(const char begin[], const char end[], char sep,
int rquoting, int max_args);
static CmdArgsType get_cmd_args_type(const char cmd[]);
static char * skip_to_cmd_name(const char cmd[]);
static int repeat_command(view_t *view, CmdInputType type);
static int is_at_scope_bottom(const int_stack_t *scope_stack);
TSTATIC char * eval_arglist(const char args[], const char **stop_ptr);
/* Settings for the cmds unit. */
static cmds_conf_t cmds_conf = {
.complete_line = &complete_line,
.complete_args = &complete_args,
.swap_range = &swap_range,
.resolve_mark = &resolve_mark,
.expand_macros = &cmds_expand_macros,
.expand_envvars = &cmds_expand_envvars,
.post = &post,
.select_range = &cmds_select_range,
.skip_at_beginning = &skip_at_beginning,
};
/* Shows whether view selection should be preserved on command-line finishing.
* By default it's reset. */
static int keep_view_selection;
/* Stores condition evaluation result for all nesting if-endif statements as
* well as file scope marks (SCOPE_GUARD). */
static int_stack_t if_levels;
static int
swap_range(void)
{
return prompt_msg("Command Error", "Backwards range given, OK to swap?");
}
static int
resolve_mark(char mark)
{
const int result = marks_find_in_view(curr_view, mark);
if(result < 0)
{
ui_sb_errf("Trying to use an invalid mark: '%c", mark);
}
return result;
}
/* Implementation of macros expansion callback for cmds unit. Returns newly
* allocated memory. */
static char *
cmds_expand_macros(const char str[], int for_shell, int *usr1, int *usr2)
{
char *result;
MacroFlags flags = MF_NONE;
result = ma_expand(str, NULL, &flags, for_shell ? MER_SHELL_OP : MER_OP);
*usr1 = flags;
return result;
}
char *
cmds_expand_envvars(const char str[])
{
return expand_envvars(str, EEF_ESCAPE_VALS | EEF_KEEP_ESCAPES);
}
void
get_and_execute_command(const char line[], size_t line_pos, CmdInputType type)
{
char *const cmd = get_ext_command(line, line_pos, type);
if(cmd == NULL)
{
save_extcmd(line, type);
}
else
{
save_extcmd(cmd, type);
execute_extcmd(cmd, type);
free(cmd);
}
}
char *
get_ext_command(const char beginning[], size_t line_pos, CmdInputType type)
{
char cmd_file[PATH_MAX + 1];
char *cmd = NULL;
generate_tmp_file_name("vifm.cmdline", cmd_file, sizeof(cmd_file));
if(setup_extcmd_file(cmd_file, beginning, type) == 0)
{
if(vim_view_file(cmd_file, 1, line_pos, 0) == 0)
{
cmd = get_file_first_line(cmd_file);
}
}
else
{
show_error_msgf("Error Creating Temporary File",
"Could not create file %s: %s", cmd_file, strerror(errno));
}
unlink(cmd_file);
return cmd;
}
/* Create and fill file for external command prompt. Returns zero on success,
* otherwise non-zero is returned and errno contains valid value. */
static int
setup_extcmd_file(const char path[], const char beginning[], CmdInputType type)
{
FILE *const fp = os_fopen(path, "wt");
if(fp == NULL)
{
return 1;
}
prepare_extcmd_file(fp, beginning, type);
fclose(fp);
return 0;
}
/* Fills the file with history (more recent goes first). */
static void
prepare_extcmd_file(FILE *fp, const char beginning[], CmdInputType type)
{
const int is_cmd = (type == CIT_COMMAND);
const hist_t *const hist = history_by_type(type);
int i;
fprintf(fp, "%s\n", beginning);
for(i = 0; i < hist->size; i++)
{
fprintf(fp, "%s\n", hist->items[i].text);
}
if(is_cmd)
{
fputs("\" vim: set filetype=vifm-cmdedit syntax=vifm :\n", fp);
}
else
{
fputs("\" vim: set filetype=vifm-edit :\n", fp);
}
}
/* Picks history by command type. Returns pointer to history. */
static hist_t *
history_by_type(CmdInputType type)
{
switch(type)
{
case CIT_COMMAND:
return &curr_stats.cmd_hist;
case CIT_PROMPT_INPUT:
return &curr_stats.prompt_hist;
case CIT_EXPRREG_INPUT:
return &curr_stats.exprreg_hist;
case CIT_FILTER_PATTERN:
return &curr_stats.filter_hist;
default:
return &curr_stats.search_hist;
}
}
/* Reads the first line of the file specified by the path. Returns NULL on
* error or an empty file, otherwise a newly allocated string, which should be
* freed by the caller, is returned. */
static char *
get_file_first_line(const char path[])
{
FILE *const fp = os_fopen(path, "rb");
char *result = NULL;
if(fp != NULL)
{
result = read_line(fp, NULL);
fclose(fp);
}
return result;
}
/* Executes the command of the type. */
static void
execute_extcmd(const char command[], CmdInputType type)
{
if(type == CIT_COMMAND)
{
commands_scope_start();
curr_stats.save_msg = exec_commands(command, curr_view, type);
if(commands_scope_finish() != 0)
{
curr_stats.save_msg = 1;
}
}
else
{
curr_stats.save_msg = exec_command(command, curr_view, type);
}
}
/* Saves the command to the appropriate history. */
static void
save_extcmd(const char command[], CmdInputType type)
{
if(type == CIT_COMMAND)
{
hists_commands_save(command);
}
else
{
hists_search_save(command);
}
}
int
is_history_command(const char command[])
{
/* Don't add :!! or :! to history list. */
return strcmp(command, "!!") != 0 && strcmp(command, "!") != 0;
}
int
command_accepts_expr(int cmd_id)
{
return cmd_id == COM_ECHO
|| cmd_id == COM_EXE
|| cmd_id == COM_IF_STMT
|| cmd_id == COM_ELSEIF_STMT
|| cmd_id == COM_LET;
}
char *
commands_escape_for_insertion(const char cmd_line[], int pos, const char str[])
{
const CmdLineLocation ipt = get_cmdline_location(cmd_line, cmd_line + pos);
switch(ipt)
{
case CLL_R_QUOTING:
/* XXX: Use of filename escape, while special one might be needed. */
case CLL_OUT_OF_ARG:
case CLL_NO_QUOTING:
return posix_like_escape(str, /*type=*/0);
case CLL_S_QUOTING:
return escape_for_squotes(str, 0);
case CLL_D_QUOTING:
return escape_for_dquotes(str, 0);
default:
return NULL;
}
}
static void
post(int id)
{
/* When one command in a sequence enters visual mode, we don't want to break
* it by resetting selection. */
if(!keep_view_selection && vle_mode_is(NORMAL_MODE))
{
flist_sel_stash_if_nonempty(curr_view);
}
/* Marking made by this unit is for a single command only and shouldn't be
* processed outside of that command. */
curr_view->pending_marking = 0;
}
TSTATIC void
cmds_select_range(int id, const cmd_info_t *cmd_info)
{
if(curr_view->pending_marking)
{
/* It must come from parent :command, so keep it. */
return;
}
int mark_current = (id != COM_FIND && id != COM_GREP);
curr_view->pending_marking = flist_sel_range(curr_view, cmd_info->begin,
cmd_info->end, mark_current);
}
/* Command prefix remover for command parsing unit. Returns < 0 to do nothing
* or x to skip command name and x chars. */
static int
skip_at_beginning(int id, const char args[])
{
if(id == COM_KEEPSEL || id == COM_WINDO)
{
return 0;
}
if(id == COM_WINRUN)
{
args = vle_cmds_at_arg(args);
if(*args != '\0')
{
return 1;
}
}
return -1;
}
void
init_commands(void)
{
if(cmds_conf.inner != NULL)
{
vle_cmds_init(1, &cmds_conf);
return;
}
/* We get here when init_commands() is called the first time. */
vle_cmds_init(1, &cmds_conf);
vle_cmds_add(cmds_list, cmds_list_size);
/* Initialize modules used by this one. */
init_bracket_notation();
init_variables();
create_builtin_vars();
sessions_set_callback(&session_changed_callback);
vle_aucmd_set_expand_hook(&pattern_expand_hook);
}
/* Creates builtin variables with some default values. */
static void
create_builtin_vars(void)
{
var_t var = var_from_int(0);
setvar("v:count", var);
setvar("v:count1", var);
var_free(var);
var = var_from_str("");
setvar("v:session", var);
var_free(var);
var = var_from_int(0);
setvar("v:jobcount", var);
var_free(var);
}
/* Callback to be invoked when active session has changed. */
static void
session_changed_callback(const char new_session[])
{
var_t var = var_from_str(new_session);
setvar("v:session", var);
var_free(var);
}
void
cmds_vars_set_count(int count)
{
var_t var;
var = var_from_int(count == NO_COUNT_GIVEN ? 0 : count);
setvar("v:count", var);
var_free(var);
var = var_from_int(count == NO_COUNT_GIVEN ? 1 : count);
setvar("v:count1", var);
var_free(var);
}
/* Performs custom pattern expansion. Allocate new expanded string. */
static char *
pattern_expand_hook(const char pattern[])
{
char *const no_tilde = expand_tilde(pattern);
char *const expanded_pattern = expand_envvars(no_tilde, EEF_NONE);
free(no_tilde);
return expanded_pattern;
}
int
cmds_exec(view_t *view, const char command[], int menu, int keep_sel)
{
int id;
int result;
if(command == NULL)
{
flist_sel_stash_if_nonempty(view);
return 0;
}
command = skip_to_cmd_name(command);
if(command[0] == '"')
return 0;
if(command[0] == '\0' && !menu)
{
flist_sel_stash_if_nonempty(view);
return 0;
}
if(!menu)
{
vle_cmds_init(1, &cmds_conf);
cmds_conf.begin = 0;
cmds_conf.current = view->list_pos;
cmds_conf.end = view->list_rows - 1;
}
id = vle_cmds_identify(command);
if(!cmd_should_be_processed(id))
{
return 0;
}
if(id == USER_CMD_ID)
{
char undo_msg[COMMAND_GROUP_INFO_LEN];
snprintf(undo_msg, sizeof(undo_msg), "in %s: %s",
replace_home_part(flist_get_dir(view)), command);
un_group_open(undo_msg);
un_group_close();
}
keep_view_selection = keep_sel;
result = vle_cmds_run(command);
if(result >= 0)
return result;
if(is_implicit_cd(view, command, result))
{
return cd(view, flist_get_dir(view), command);
}
switch(result)
{
case CMDS_ERR_LOOP:
ui_sb_err("Loop in commands");
break;
case CMDS_ERR_NO_MEM:
ui_sb_err("Unable to allocate enough memory");
break;
case CMDS_ERR_TOO_FEW_ARGS:
ui_sb_err("Too few arguments");
break;
case CMDS_ERR_TRAILING_CHARS:
ui_sb_err("Trailing characters");
break;
case CMDS_ERR_INCORRECT_NAME:
ui_sb_err("Incorrect command name");
break;
case CMDS_ERR_NEED_BANG:
ui_sb_err("Add bang to force");
break;
case CMDS_ERR_NO_BUILTIN_REDEFINE:
ui_sb_err("Can't redefine builtin command");
break;
case CMDS_ERR_INVALID_CMD:
ui_sb_err("Invalid command name");
break;
case CMDS_ERR_NO_BANG_ALLOWED:
ui_sb_err("No ! is allowed");
break;
case CMDS_ERR_NO_RANGE_ALLOWED:
ui_sb_err("No range is allowed");
break;
case CMDS_ERR_NO_QMARK_ALLOWED:
ui_sb_err("No ? is allowed");
break;
case CMDS_ERR_INVALID_RANGE:
ui_sb_err("Invalid range");
break;
case CMDS_ERR_NO_SUCH_UDF:
ui_sb_err("No such user defined command");
break;
case CMDS_ERR_UDF_IS_AMBIGUOUS:
ui_sb_err("Ambiguous use of user-defined command");
break;
case CMDS_ERR_INVALID_ARG:
ui_sb_err("Invalid argument");
break;
case CMDS_ERR_CUSTOM:
/* error message is posted by command handler */
break;
default:
ui_sb_err("Unknown error");
break;
}
if(!menu && vle_mode_is(NORMAL_MODE))
{
flist_sel_stash_if_nonempty(view);
}
return -1;
}
/* Whether need to process command-line command as implicit :cd. Returns
* non-zero if so, otherwise zero is returned. */
static int
is_implicit_cd(view_t *view, const char cmd[], int cmd_error)
{
if(!cfg.auto_cd)
{
return 0;
}
if(cmd_error != CMDS_ERR_INVALID_CMD && cmd_error != CMDS_ERR_TRAILING_CHARS)
{
return 0;
}
char *expanded = expand_tilde(cmd);
int exists = path_exists_at(flist_get_dir(view), expanded, NODEREF);
free(expanded);
return exists;
}
/* Decides whether next command with id cmd_id should be processed or not,
* taking state of conditional statements into account. Returns non-zero if the
* command should be processed, otherwise zero is returned. */
static int
cmd_should_be_processed(int cmd_id)
{
static int skipped_nested_if_stmts;
if(is_at_scope_bottom(&if_levels) || int_stack_top_is(&if_levels, IF_MATCH)
|| int_stack_top_is(&if_levels, IF_ELSE))
{
return 1;
}
/* Get here only when in false branch of if statement. */
if(cmd_id == COM_IF_STMT)
{
++skipped_nested_if_stmts;
return 0;
}
if(cmd_id == COM_ELSEIF_STMT)
{
return (skipped_nested_if_stmts == 0);
}
if(cmd_id == COM_ELSE_STMT || cmd_id == COM_ENDIF_STMT)
{
if(skipped_nested_if_stmts > 0)
{
if(cmd_id == COM_ENDIF_STMT)
{
--skipped_nested_if_stmts;
}
return 0;
}
return 1;
}
return 0;
}
/* Determines current position in the command line. The rquoting parameter when
* non-zero specifies number of rquoted arguments by its absolute value, while
* negative sign means that last argument doesn't need to be terminated.
* Returns:
* - 0, if not inside an argument;
* - 1, if next character should be skipped (XXX: what does it mean?);
* - 2, if inside escaped argument;
* - 3, if inside single quoted argument;
* - 4, if inside double quoted argument;
* - 5, if inside regexp quoted argument. */
TSTATIC int
line_pos(const char begin[], const char end[], char sep, int rquoting,
int max_args)
{
int count;
enum { BEGIN, NO_QUOTING, S_QUOTING, D_QUOTING, R_QUOTING } state;
int args_left = max_args;
/* Actual separator used for rargs or '\0' if unset. */
char rsep = '\0';
const char *args = vle_cmds_args(begin);
if(args >= end)
{
return 0;
}
if(args == NULL)
{
count = 0;
}
else
{
begin = args;
count = 1;
}
if(rquoting < 0)
{
rquoting = -(rquoting + 1);
}
state = BEGIN;
while(begin != end)
{
switch(state)
{
case BEGIN:
if(sep == ' ' && *begin == '\'')
state = S_QUOTING;
else if(sep == ' ' && *begin == '"')
state = D_QUOTING;
else if(rquoting && ((sep == ' ' && *begin == '/') || *begin == sep) &&
(rsep == '\0' || *begin == rsep))
state = R_QUOTING;
else if(*begin == '&' && begin == end - 1)
state = BEGIN;
else if(*begin != sep)
state = rquoting && (rsep == '\0' || *begin == rsep) ? R_QUOTING
: NO_QUOTING;
break;
case NO_QUOTING:
if(*begin == sep)
{
state = BEGIN;
count++;
}
else if(*begin == '\'')
{
state = S_QUOTING;
}
else if(*begin == '"')
{
state = D_QUOTING;
}
else if(*begin == '\\')
{
begin++;
if(begin == end)
return 1;
}
break;
case S_QUOTING:
if(*begin == '\'')
state = BEGIN;
break;
case D_QUOTING:
if(*begin == '"')
{
state = BEGIN;
}
else if(*begin == '\\')
{
begin++;
if(begin == end)
return 1;
}
break;
case R_QUOTING:
if(rsep == '\0')
{
rsep = *(begin - 1);
}
if(*begin == rsep || *begin == sep)
{
--args_left;
--rquoting;
if(args_left == 0 || rquoting == 0)
{
state = BEGIN;
}
}
else if(*begin == '\\')
{
begin++;
if(begin == end)
return 1;
}
break;
}
begin++;
}
if(state == NO_QUOTING)
{
if(sep == ' ')
{
/* First element is not an argument. */
return (count > 0) ? 2 : 0;
}
else if(count > 0 && count < 3)
{
return 2;
}
}
else if(state != BEGIN)
{
/* "Error": no closing quote. */
switch(state)
{
case S_QUOTING: return 3;
case D_QUOTING: return 4;
case R_QUOTING: return (max_args <= 1 || args_left > 1 ? 5 : 2);
default:
assert(0 && "Unexpected state.");
break;
}
}
else if(sep != ' ' && count > 0 && *end != sep)
return 2;
return 0;
}
int
exec_commands(const char cmdline[], view_t *view, CmdInputType type)
{
int save_msg = 0;
char **cmds = break_cmdline(cmdline, type == CIT_MENU_COMMAND);
char **cmd = cmds;
while(*cmd != NULL)
{
const int ret = exec_command(*cmd, view, type);
if(ret != 0)
{
save_msg = (ret < 0) ? -1 : 1;
}
free(*cmd++);
}
free(cmds);
return save_msg;
}
/* Breaks command-line into sub-commands. Returns NULL-terminated list of
* sub-commands. */
TSTATIC char **
break_cmdline(const char cmdline[], int for_menu)
{
char **cmds = NULL;
int len = 0;
char cmdline_copy[strlen(cmdline) + 1];
char *raw, *processed;
CmdArgsType args_kind;
if(*cmdline == '\0')
{
len = add_to_string_array(&cmds, len, cmdline);
goto finish;
}
strcpy(cmdline_copy, cmdline);
cmdline = cmdline_copy;
raw = cmdline_copy;
processed = cmdline_copy;
/* For non-menu commands set command-line mode configuration before calling
* is_out_of_arg() and get_cmd_args_type() function, which calls functions of
* the cmds module of the engine that use context. */
if(!for_menu)
{
vle_cmds_init(1, &cmds_conf);
}
cmdline = skip_to_cmd_name(cmdline);
args_kind = get_cmd_args_type(cmdline);
/* Throughout the following loop local variables have the following meaning:
* - save_msg -- resultant state of message indication;
* - raw -- not yet processed part of string that can contain \;
* - processed -- ready to consume part of string;
* - cmdline -- points to the start of the last command. */
while(*cmdline != '\0')
{
if(args_kind == CAT_REGULAR && raw[0] == '\\' && raw[1] != '\0')
{
if(*(raw + 1) == '|')
{
*processed++ = '|';
raw += 2;
}
else
{
*processed++ = *raw++;
*processed++ = *raw++;
}
}
else if((*raw == '|' && is_out_of_arg(cmdline, processed)) || *raw == '\0')
{
if(*raw != '\0')
{
++raw;
}
else
{
*processed = '\0';
}
/* Don't break line for whole line commands. */
if(args_kind != CAT_UNTIL_THE_END)
{
if(args_kind == CAT_EXPR)
{
/* Move breaking point forward by consuming parts of the string after
* || until end of the string or | is found. */
while(processed[0] == '|' && processed[1] == '|' &&
processed[2] != '|')
{
processed = until_first(processed + 2, '|');
raw = (processed[0] == '\0') ? processed : (processed + 1);
}
}
*processed = '\0';
processed = raw;
}
len = add_to_string_array(&cmds, len, cmdline);
if(args_kind == CAT_UNTIL_THE_END)
{
/* Whole line command takes the rest of the string, nothing more to
* process. */
break;
}
cmdline = skip_to_cmd_name(processed);
args_kind = get_cmd_args_type(cmdline);
}
else
{
*processed++ = *raw++;
}
}
finish:
(void)put_into_string_array(&cmds, len, NULL);
return cmds;
}
/* Checks whether character at given position in the given command-line is
* outside quoted argument. Returns non-zero if so, otherwise zero is
* returned. */
static int
is_out_of_arg(const char cmd[], const char pos[])
{
const CmdLineLocation location = get_cmdline_location(cmd, pos);
if(location == CLL_NO_QUOTING)
{
if(get_cmd_args_type(cmd) == CAT_REGULAR)
{
return 1;
}
if(get_cmd_args_type(cmd) == CAT_EXPR &&
pos != cmd && pos[0] == '|' && pos[-1] != '|' && pos[1] != '|')
{
/* For "*[^|]|[^|]*" report that we're out of argument. */
return 1;
}
}
return location == CLL_OUT_OF_ARG;
}
CmdLineLocation
get_cmdline_location(const char cmd[], const char pos[])
{