-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreadline.c
2629 lines (2253 loc) · 51.4 KB
/
readline.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
/* $NetBSD: readline.c,v 1.182 2024/03/26 18:02:04 christos Exp $ */
/*-
* Copyright (c) 1997 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jaromir Dolecek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if !defined(lint) && !defined(SCCSID)
__RCSID("$NetBSD: readline.c,v 1.182 2024/03/26 18:02:04 christos Exp $");
#endif /* not lint && not SCCSID */
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vis.h>
#define completion_matches xxx_completion_matches
#include "readline/readline.h"
#undef completion_matches
#include "el.h"
#include "fcns.h"
#include "filecomplete.h"
void rl_prep_terminal(int);
void rl_deprep_terminal(void);
/* for rl_complete() */
#define TAB '\r'
/* see comment at the #ifdef for sense of this */
/* #define GDB_411_HACK */
/* readline compatibility stuff - look at readline sources/documentation */
/* to see what these variables mean */
const char *rl_library_version = "EditLine wrapper";
int rl_readline_version = RL_READLINE_VERSION;
static char empty[] = { '\0' };
static char expand_chars[] = { ' ', '\t', '\n', '=', '(', '\0' };
static char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', '$',
'>', '<', '=', ';', '|', '&', '{', '(', '\0' };
const char *rl_readline_name = empty;
FILE *rl_instream = NULL;
FILE *rl_outstream = NULL;
int rl_point = 0;
int rl_end = 0;
char *rl_line_buffer = NULL;
rl_vcpfunc_t *rl_linefunc = NULL;
int rl_done = 0;
rl_hook_func_t *rl_event_hook = NULL;
KEYMAP_ENTRY_ARRAY emacs_standard_keymap,
emacs_meta_keymap,
emacs_ctlx_keymap;
/*
* The following is not implemented; we always catch signals in the
* libedit fashion: set handlers on entry to el_gets() and clear them
* on the way out. This simplistic approach works for most cases; if
* it does not work for your application, please let us know.
*/
int rl_catch_signals = 1;
int rl_catch_sigwinch = 1;
int history_base = 1; /* probably never subject to change */
int history_length = 0;
int history_offset = 0;
int max_input_history = 0;
char history_expansion_char = '!';
char history_subst_char = '^';
char *history_no_expand_chars = expand_chars;
rl_linebuf_func_t *history_inhibit_expansion_function = NULL;
char *history_arg_extract(int start, int end, const char *str);
int rl_inhibit_completion = 0;
int rl_attempted_completion_over = 0;
const char *rl_basic_word_break_characters = break_chars;
char *rl_completer_word_break_characters = NULL;
const char *rl_completer_quote_characters = NULL;
const char *rl_basic_quote_characters = "\"'";
rl_compentry_func_t *rl_completion_entry_function = NULL;
char *(*rl_completion_word_break_hook)(void) = NULL;
rl_completion_func_t *rl_attempted_completion_function = NULL;
rl_hook_func_t *rl_pre_input_hook = NULL;
rl_hook_func_t *rl_startup1_hook = NULL;
int (*rl_getc_function)(FILE *) = NULL;
char *rl_terminal_name = NULL;
int rl_already_prompted = 0;
int rl_filename_completion_desired = 0;
int rl_ignore_completion_duplicates = 0;
int readline_echoing_p = 1;
int _rl_print_completions_horizontally = 0;
rl_voidfunc_t *rl_redisplay_function = NULL;
rl_hook_func_t *rl_startup_hook = NULL;
rl_compdisp_func_t *rl_completion_display_matches_hook = NULL;
rl_vintfunc_t *rl_prep_term_function = (rl_vintfunc_t *)rl_prep_terminal;
rl_voidfunc_t *rl_deprep_term_function = (rl_voidfunc_t *)rl_deprep_terminal;
KEYMAP_ENTRY_ARRAY emacs_meta_keymap;
unsigned long rl_readline_state = RL_STATE_NONE;
int _rl_complete_mark_directories;
rl_icppfunc_t *rl_directory_completion_hook;
int rl_completion_suppress_append;
int rl_sort_completion_matches;
int _rl_completion_prefix_display_length;
int _rl_echoing_p;
int history_max_entries;
char *rl_display_prompt;
int rl_erase_empty_line;
/*
* The current prompt string.
*/
char *rl_prompt = NULL;
char *rl_prompt_saved = NULL;
/*
* This is set to character indicating type of completion being done by
* rl_complete_internal(); this is available for application completion
* functions.
*/
int rl_completion_type = 0;
/*
* If more than this number of items results from query for possible
* completions, we ask user if they are sure to really display the list.
*/
int rl_completion_query_items = 100;
/*
* List of characters which are word break characters, but should be left
* in the parsed text when it is passed to the completion function.
* Shell uses this to help determine what kind of completing to do.
*/
const char *rl_special_prefixes = NULL;
/*
* This is the character appended to the completed words if at the end of
* the line. Default is ' ' (a space).
*/
int rl_completion_append_character = ' ';
/* stuff below is used internally by libedit for readline emulation */
static History *h = NULL;
static EditLine *e = NULL;
static rl_command_func_t *map[256];
static jmp_buf topbuf;
/* internal functions */
static unsigned char _el_rl_complete(EditLine *, int);
static unsigned char _el_rl_tstp(EditLine *, int);
static char *_get_prompt(EditLine *);
static int _getc_function(EditLine *, wchar_t *);
static int _history_expand_command(const char *, size_t, size_t,
char **);
static char *_rl_compat_sub(const char *, const char *,
const char *, int);
static int _rl_event_read_char(EditLine *, wchar_t *);
static void _rl_update_pos(void);
static HIST_ENTRY rl_he;
/* ARGSUSED */
static char *
_get_prompt(EditLine *el __attribute__((__unused__)))
{
rl_already_prompted = 1;
return rl_prompt;
}
/*
* read one key from user defined input function
*/
static int
/*ARGSUSED*/
_getc_function(EditLine *el __attribute__((__unused__)), wchar_t *c)
{
int i;
i = (*rl_getc_function)(rl_instream);
if (i == -1)
return 0;
*c = (wchar_t)i;
return 1;
}
static void
_resize_fun(EditLine *el, void *a)
{
const LineInfo *li;
const char **ap = a;
li = el_line(el);
*ap = li->buffer;
}
static const char *
_default_history_file(void)
{
struct passwd *p;
static char *path;
size_t len;
if (path)
return path;
if ((p = getpwuid(getuid())) == NULL)
return NULL;
len = strlen(p->pw_dir) + sizeof("/.history");
if ((path = el_malloc(len)) == NULL)
return NULL;
(void)snprintf(path, len, "%s/.history", p->pw_dir);
return path;
}
/*
* READLINE compatibility stuff
*/
/*
* Set the prompt
*/
int
rl_set_prompt(const char *prompt)
{
char *p;
if (!prompt)
prompt = "";
if (rl_prompt != NULL && strcmp(rl_prompt, prompt) == 0)
return 0;
if (rl_prompt)
el_free(rl_prompt);
rl_prompt = strdup(prompt);
if (rl_prompt == NULL)
return -1;
while ((p = strchr(rl_prompt, RL_PROMPT_END_IGNORE)) != NULL) {
/* Remove adjacent end/start markers to avoid double-escapes. */
if (p[1] == RL_PROMPT_START_IGNORE) {
memmove(p, p + 2, 1 + strlen(p + 2));
} else {
*p = RL_PROMPT_START_IGNORE;
}
}
return 0;
}
void
rl_save_prompt(void)
{
rl_prompt_saved = strdup(rl_prompt);
}
void
rl_restore_prompt(void)
{
if (!rl_prompt_saved)
return;
rl_prompt = rl_prompt_saved;
rl_prompt_saved = NULL;
}
/*
* initialize rl compat stuff
*/
int
rl_initialize(void)
{
HistEvent ev;
int editmode = 1;
struct termios t;
if (e != NULL)
el_end(e);
if (h != NULL)
history_end(h);
RL_UNSETSTATE(RL_STATE_DONE);
if (!rl_instream)
rl_instream = stdin;
if (!rl_outstream)
rl_outstream = stdout;
/*
* See if we don't really want to run the editor
*/
if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
editmode = 0;
e = el_init_internal(rl_readline_name, rl_instream, rl_outstream,
stderr, fileno(rl_instream), fileno(rl_outstream), fileno(stderr),
NO_RESET);
if (!editmode)
el_set(e, EL_EDITMODE, 0);
h = history_init();
if (!e || !h)
return -1;
history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
history_length = 0;
max_input_history = INT_MAX;
el_set(e, EL_HIST, history, h);
/* Setup resize function */
el_set(e, EL_RESIZE, _resize_fun, &rl_line_buffer);
/* setup getc function if valid */
if (rl_getc_function)
el_set(e, EL_GETCFN, _getc_function);
/* for proper prompt printing in readline() */
if (rl_set_prompt("") == -1) {
history_end(h);
el_end(e);
return -1;
}
el_set(e, EL_PROMPT_ESC, _get_prompt, RL_PROMPT_START_IGNORE);
el_set(e, EL_SIGNAL, rl_catch_signals);
/* set default mode to "emacs"-style and read setting afterwards */
/* so this can be overridden */
el_set(e, EL_EDITOR, "emacs");
if (rl_terminal_name != NULL)
el_set(e, EL_TERMINAL, rl_terminal_name);
else
el_get(e, EL_TERMINAL, &rl_terminal_name);
/*
* Word completion - this has to go AFTER rebinding keys
* to emacs-style.
*/
el_set(e, EL_ADDFN, "rl_complete",
"ReadLine compatible completion function",
_el_rl_complete);
el_set(e, EL_BIND, "^I", "rl_complete", NULL);
/*
* Send TSTP when ^Z is pressed.
*/
el_set(e, EL_ADDFN, "rl_tstp",
"ReadLine compatible suspend function",
_el_rl_tstp);
el_set(e, EL_BIND, "^Z", "rl_tstp", NULL);
/*
* Set some readline compatible key-bindings.
*/
el_set(e, EL_BIND, "^R", "em-inc-search-prev", NULL);
/*
* Allow the use of Home/End keys.
*/
el_set(e, EL_BIND, "\\e[1~", "ed-move-to-beg", NULL);
el_set(e, EL_BIND, "\\e[4~", "ed-move-to-end", NULL);
el_set(e, EL_BIND, "\\e[7~", "ed-move-to-beg", NULL);
el_set(e, EL_BIND, "\\e[8~", "ed-move-to-end", NULL);
el_set(e, EL_BIND, "\\e[H", "ed-move-to-beg", NULL);
el_set(e, EL_BIND, "\\e[F", "ed-move-to-end", NULL);
/*
* Allow the use of the Delete/Insert keys.
*/
el_set(e, EL_BIND, "\\e[3~", "ed-delete-next-char", NULL);
el_set(e, EL_BIND, "\\e[2~", "em-toggle-overwrite", NULL);
/*
* Ctrl-left-arrow and Ctrl-right-arrow for word moving.
*/
el_set(e, EL_BIND, "\\e[1;5C", "em-next-word", NULL);
el_set(e, EL_BIND, "\\e[1;5D", "ed-prev-word", NULL);
el_set(e, EL_BIND, "\\e[5C", "em-next-word", NULL);
el_set(e, EL_BIND, "\\e[5D", "ed-prev-word", NULL);
el_set(e, EL_BIND, "\\e\\e[C", "em-next-word", NULL);
el_set(e, EL_BIND, "\\e\\e[D", "ed-prev-word", NULL);
/* read settings from configuration file */
el_source(e, NULL);
/*
* Unfortunately, some applications really do use rl_point
* and rl_line_buffer directly.
*/
_resize_fun(e, &rl_line_buffer);
_rl_update_pos();
tty_end(e, TCSADRAIN);
return 0;
}
/*
* read one line from input stream and return it, chomping
* trailing newline (if there is any)
*/
char *
readline(const char *p)
{
HistEvent ev;
const char * volatile prompt = p;
int count;
const char *ret;
char *buf;
static int used_event_hook;
if (e == NULL || h == NULL)
rl_initialize();
if (rl_startup_hook) {
(*rl_startup_hook)();
}
tty_init(e);
rl_done = 0;
(void)setjmp(topbuf);
buf = NULL;
/* update prompt accordingly to what has been passed */
if (rl_set_prompt(prompt) == -1)
goto out;
if (rl_pre_input_hook)
(*rl_pre_input_hook)();
if (rl_event_hook && !(e->el_flags & NO_TTY)) {
el_set(e, EL_GETCFN, _rl_event_read_char);
used_event_hook = 1;
}
if (!rl_event_hook && used_event_hook) {
el_set(e, EL_GETCFN, EL_BUILTIN_GETCFN);
used_event_hook = 0;
}
rl_already_prompted = 0;
/* get one line from input stream */
ret = el_gets(e, &count);
if (ret && count > 0) {
int lastidx;
buf = strdup(ret);
if (buf == NULL)
goto out;
lastidx = count - 1;
if (buf[lastidx] == '\n')
buf[lastidx] = '\0';
} else
buf = NULL;
history(h, &ev, H_GETSIZE);
history_length = ev.num;
out:
tty_end(e, TCSADRAIN);
return buf;
}
/*
* history functions
*/
/*
* is normally called before application starts to use
* history expansion functions
*/
void
using_history(void)
{
if (h == NULL || e == NULL)
rl_initialize();
history_offset = history_length;
}
/*
* substitute ``what'' with ``with'', returning resulting string; if
* globally == 1, substitutes all occurrences of what, otherwise only the
* first one
*/
static char *
_rl_compat_sub(const char *str, const char *what, const char *with,
int globally)
{
const char *s;
char *r, *result;
size_t len, with_len, what_len;
len = strlen(str);
with_len = strlen(with);
what_len = strlen(what);
/* calculate length we need for result */
s = str;
while (*s) {
if (*s == *what && !strncmp(s, what, what_len)) {
len += with_len - what_len;
if (!globally)
break;
s += what_len;
} else
s++;
}
r = result = el_calloc(len + 1, sizeof(*r));
if (result == NULL)
return NULL;
s = str;
while (*s) {
if (*s == *what && !strncmp(s, what, what_len)) {
memcpy(r, with, with_len);
r += with_len;
s += what_len;
if (!globally) {
(void)strcpy(r, s);
return result;
}
} else
*r++ = *s++;
}
*r = '\0';
return result;
}
static char *last_search_pat; /* last !?pat[?] search pattern */
static char *last_search_match; /* last !?pat[?] that matched */
const char *
get_history_event(const char *cmd, int *cindex, int qchar)
{
int idx, sign, sub, num, begin, ret;
size_t len;
char *pat;
const char *rptr;
HistEvent ev;
idx = *cindex;
if (cmd[idx++] != history_expansion_char)
return NULL;
/* find out which event to take */
if (cmd[idx] == history_expansion_char || cmd[idx] == '\0') {
if (history(h, &ev, H_FIRST) != 0)
return NULL;
*cindex = cmd[idx]? (idx + 1):idx;
return ev.str;
}
sign = 0;
if (cmd[idx] == '-') {
sign = 1;
idx++;
}
if ('0' <= cmd[idx] && cmd[idx] <= '9') {
HIST_ENTRY *he;
num = 0;
while (cmd[idx] && '0' <= cmd[idx] && cmd[idx] <= '9') {
num = num * 10 + cmd[idx] - '0';
idx++;
}
if (sign)
num = history_length - num + history_base;
if (!(he = history_get(num)))
return NULL;
*cindex = idx;
return he->line;
}
sub = 0;
if (cmd[idx] == '?') {
sub = 1;
idx++;
}
begin = idx;
while (cmd[idx]) {
if (cmd[idx] == '\n')
break;
if (sub && cmd[idx] == '?')
break;
if (!sub && (cmd[idx] == ':' || cmd[idx] == ' '
|| cmd[idx] == '\t' || cmd[idx] == qchar))
break;
idx++;
}
len = (size_t)idx - (size_t)begin;
if (sub && cmd[idx] == '?')
idx++;
if (sub && len == 0 && last_search_pat && *last_search_pat)
pat = last_search_pat;
else if (len == 0)
return NULL;
else {
if ((pat = el_calloc(len + 1, sizeof(*pat))) == NULL)
return NULL;
(void)strlcpy(pat, cmd + begin, len + 1);
}
if (history(h, &ev, H_CURR) != 0) {
if (pat != last_search_pat)
el_free(pat);
return NULL;
}
num = ev.num;
if (sub) {
if (pat != last_search_pat) {
el_free(last_search_pat);
last_search_pat = pat;
}
ret = history_search(pat, -1);
} else
ret = history_search_prefix(pat, -1);
if (ret == -1) {
/* restore to end of list on failed search */
history(h, &ev, H_FIRST);
(void)fprintf(rl_outstream, "%s: Event not found\n", pat);
if (pat != last_search_pat)
el_free(pat);
return NULL;
}
if (sub && len) {
el_free(last_search_match);
last_search_match = strdup(pat);
}
if (pat != last_search_pat)
el_free(pat);
if (history(h, &ev, H_CURR) != 0)
return NULL;
*cindex = idx;
rptr = ev.str;
/* roll back to original position */
(void)history(h, &ev, H_SET, num);
return rptr;
}
static int
getfrom(const char **cmdp, char **fromp, const char *search, int delim)
{
size_t size = 16;
size_t len = 0;
const char *cmd = *cmdp;
char *what = el_realloc(*fromp, size * sizeof(*what));
if (what == NULL){
el_free(*fromp);
*fromp = NULL;
return 0;
}
for (; *cmd && *cmd != delim; cmd++) {
if (*cmd == '\\' && cmd[1] == delim)
cmd++;
if (len - 1 >= size) {
char *nwhat;
nwhat = el_realloc(what, (size <<= 1) * sizeof(*nwhat));
if (nwhat == NULL) {
el_free(what);
el_free(*fromp);
*cmdp = cmd;
*fromp = NULL;
return 0;
}
what = nwhat;
}
what[len++] = *cmd;
}
what[len] = '\0';
*fromp = what;
*cmdp = cmd;
if (*what == '\0') {
el_free(what);
if (search) {
*fromp = strdup(search);
if (*fromp == NULL) {
return 0;
}
} else {
*fromp = NULL;
return -1;
}
}
if (!*cmd) {
el_free(what);
*fromp = NULL;
return -1;
}
cmd++; /* shift after delim */
*cmdp = cmd;
if (!*cmd) {
el_free(what);
*fromp = NULL;
return -1;
}
return 1;
}
static int
getto(const char **cmdp, char **top, const char *from, int delim)
{
size_t size = 16;
size_t len = 0;
size_t from_len = strlen(from);
const char *cmd = *cmdp;
char *with = el_realloc(*top, size * sizeof(*with));
*top = NULL;
if (with == NULL)
goto out;
for (; *cmd && *cmd != delim; cmd++) {
if (len + from_len + 1 >= size) {
char *nwith;
size += from_len + 1;
nwith = el_realloc(with, size * sizeof(*nwith));
if (nwith == NULL)
goto out;
with = nwith;
}
if (*cmd == '&') {
/* safe */
strcpy(&with[len], from);
len += from_len;
continue;
}
if (*cmd == '\\' && (*(cmd + 1) == delim || *(cmd + 1) == '&'))
cmd++;
with[len++] = *cmd;
}
if (!*cmd)
goto out;
with[len] = '\0';
*top = with;
*cmdp = cmd;
return 1;
out:
el_free(with);
el_free(*top);
*top = NULL;
*cmdp = cmd;
return -1;
}
static void
replace(char **tmp, int c)
{
char *aptr;
if ((aptr = strrchr(*tmp, c)) == NULL)
return;
aptr = strdup(aptr + 1); // XXX: check
el_free(*tmp);
*tmp = aptr;
}
/*
* the real function doing history expansion - takes as argument command
* to do and data upon which the command should be executed
* does expansion the way I've understood readline documentation
*
* returns 0 if data was not modified, 1 if it was and 2 if the string
* should be only printed and not executed; in case of error,
* returns -1 and *result points to NULL
* it's the caller's responsibility to free() the string returned in *result
*/
static int
_history_expand_command(const char *command, size_t offs, size_t cmdlen,
char **result)
{
char *tmp, *search = NULL, *aptr, delim;
const char *ptr, *cmd;
static char *from = NULL, *to = NULL;
int start, end, idx, has_mods = 0;
int p_on = 0, g_on = 0, ev;
*result = NULL;
aptr = NULL;
ptr = NULL;
/* First get event specifier */
idx = 0;
if (strchr(":^*$", command[offs + 1])) {
char str[4];
/*
* "!:" is shorthand for "!!:".
* "!^", "!*" and "!$" are shorthand for
* "!!:^", "!!:*" and "!!:$" respectively.
*/
str[0] = str[1] = '!';
str[2] = '0';
ptr = get_history_event(str, &idx, 0);
idx = (command[offs + 1] == ':')? 1:0;
has_mods = 1;
} else {
if (command[offs + 1] == '#') {
/* use command so far */
if ((aptr = el_calloc(offs + 1, sizeof(*aptr)))
== NULL)
return -1;
(void)strlcpy(aptr, command, offs + 1);
idx = 1;
} else {
int qchar;
qchar = (offs > 0 && command[offs - 1] == '"')
? '"' : '\0';
ptr = get_history_event(command + offs, &idx, qchar);
}
has_mods = command[offs + (size_t)idx] == ':';
}
if (ptr == NULL && aptr == NULL)
return -1;
if (!has_mods) {
*result = strdup(aptr ? aptr : ptr);
if (aptr)
el_free(aptr);
if (*result == NULL)
return -1;
return 1;
}
cmd = command + offs + idx + 1;
/* Now parse any word designators */
if (*cmd == '%') /* last word matched by ?pat? */
tmp = strdup(last_search_match ? last_search_match : "");
else if (strchr("^*$-0123456789", *cmd)) {
start = end = -1;
if (*cmd == '^')
start = end = 1, cmd++;
else if (*cmd == '$')
start = -1, cmd++;
else if (*cmd == '*')
start = 1, cmd++;
else if (*cmd == '-' || isdigit((unsigned char) *cmd)) {
start = 0;
while (*cmd && '0' <= *cmd && *cmd <= '9')
start = start * 10 + *cmd++ - '0';
if (*cmd == '-') {
if (isdigit((unsigned char) cmd[1])) {
cmd++;
end = 0;
while (*cmd && '0' <= *cmd && *cmd <= '9')
end = end * 10 + *cmd++ - '0';
} else if (cmd[1] == '$') {
cmd += 2;
end = -1;
} else {
cmd++;
end = -2;
}
} else if (*cmd == '*')
end = -1, cmd++;
else
end = start;
}
tmp = history_arg_extract(start, end, aptr? aptr:ptr);
if (tmp == NULL) {
(void)fprintf(rl_outstream, "%s: Bad word specifier",
command + offs + idx);
if (aptr)
el_free(aptr);
return -1;
}
} else
tmp = strdup(aptr? aptr:ptr);
if (aptr)
el_free(aptr);
if (*cmd == '\0' || ((size_t)(cmd - (command + offs)) >= cmdlen)) {
*result = tmp;
return 1;
}
for (; *cmd; cmd++) {
switch (*cmd) {
case ':':
continue;
case 'h': /* remove trailing path */
if ((aptr = strrchr(tmp, '/')) != NULL)
*aptr = '\0';
continue;
case 't': /* remove leading path */
replace(&tmp, '/');
continue;
case 'r': /* remove trailing suffix */
if ((aptr = strrchr(tmp, '.')) != NULL)
*aptr = '\0';
continue;
case 'e': /* remove all but suffix */
replace(&tmp, '.');
continue;
case 'p': /* print only */
p_on = 1;
continue;
case 'g':
g_on = 2;
continue;
case '&':
if (from == NULL || to == NULL)
continue;
/*FALLTHROUGH*/
case 's':
ev = -1;
delim = *++cmd;
if (delim == '\0' || *++cmd == '\0')
goto out;
if ((ev = getfrom(&cmd, &from, search, delim)) != 1)
goto out;
if ((ev = getto(&cmd, &to, from, delim)) != 1)
goto out;
aptr = _rl_compat_sub(tmp, from, to, g_on);
if (aptr) {
el_free(tmp);
tmp = aptr;
}
g_on = 0;
cmd--;
continue;
}
}
*result = tmp;
return p_on ? 2 : 1;
out:
el_free(tmp);
return ev;
}
/*
* csh-style history expansion
*/
int
history_expand(char *str, char **output)
{
int ret = 0;
size_t idx, i, size;
char *tmp, *result;
if (h == NULL || e == NULL)
rl_initialize();
if (history_expansion_char == 0) {
*output = strdup(str);
return 0;
}