1
/* $NetBSD: readline.c,v 1.19 2001/01/10 08:10:45 jdolecek Exp $ */
4
* Copyright (c) 1997 The NetBSD Foundation, Inc.
7
* This code is derived from software contributed to The NetBSD Foundation
10
* Redistribution and use in source and binary forms, with or without
11
* modification, are permitted provided that the following conditions
13
* 1. Redistributions of source code must retain the above copyright
14
* notice, this list of conditions and the following disclaimer.
15
* 2. Redistributions in binary form must reproduce the above copyright
16
* notice, this list of conditions and the following disclaimer in the
17
* documentation and/or other materials provided with the distribution.
18
* 3. All advertising materials mentioning features or use of this software
19
* must display the following acknowledgement:
20
* This product includes software developed by the NetBSD
21
* Foundation, Inc. and its contributors.
22
* 4. Neither the name of The NetBSD Foundation nor the names of its
23
* contributors may be used to endorse or promote products derived
24
* from this software without specific prior written permission.
26
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36
* POSSIBILITY OF SUCH DAMAGE.
40
#if !defined(lint) && !defined(SCCSID)
41
__RCSID("$NetBSD: readline.c,v 1.19 2001/01/10 08:10:45 jdolecek Exp $");
42
#endif /* not lint && not SCCSID */
44
#include <sys/types.h>
55
#include "readline/readline.h"
58
#include "fcns.h" /* for EL_NUM_FCNS */
60
/* for rl_complete() */
63
/* see comment at the #ifdef for sense of this */
66
/* readline compatibility stuff - look at readline sources/documentation */
67
/* to see what these variables mean */
68
const char *rl_library_version = "EditLine wrapper";
69
const char *rl_readline_name = "";
70
FILE *rl_instream = NULL;
71
FILE *rl_outstream = NULL;
74
char *rl_line_buffer = NULL;
76
int history_base = 1; /* probably never subject to change */
77
int history_length = 0;
78
int max_input_history = 0;
79
char history_expansion_char = '!';
80
char history_subst_char = '^';
81
const char *history_no_expand_chars = " \t\n=(";
82
Function *history_inhibit_expansion_function = NULL;
84
int rl_inhibit_completion = 0;
85
int rl_attempted_completion_over = 0;
86
const char *rl_basic_word_break_characters = " \t\n\"\\'`@$><=;|&{(";
87
char *rl_completer_word_break_characters = NULL;
88
char *rl_completer_quote_characters = NULL;
89
CPFunction *rl_completion_entry_function = NULL;
90
CPPFunction *rl_attempted_completion_function = NULL;
93
* This is set to character indicating type of completion being done by
94
* rl_complete_internal(); this is available for application completion
97
int rl_completion_type = 0;
100
* If more than this number of items results from query for possible
101
* completions, we ask user if they are sure to really display the list.
103
int rl_completion_query_items = 100;
106
* List of characters which are word break characters, but should be left
107
* in the parsed text when it is passed to the completion function.
108
* Shell uses this to help determine what kind of completing to do.
110
char *rl_special_prefixes = (char *)NULL;
113
* This is the character appended to the completed words if at the end of
114
* the line. Default is ' ' (a space).
116
int rl_completion_append_character = ' ';
118
/* stuff below is used internally by libedit for readline emulation */
120
/* if not zero, non-unique completions always show list of possible matches */
121
static int _rl_complete_show_all = 0;
123
static History *h = NULL;
124
static EditLine *e = NULL;
125
static int el_rl_complete_cmdnum = 0;
127
/* internal functions */
128
static unsigned char _el_rl_complete(EditLine *, int);
129
static char *_get_prompt(EditLine *);
130
static HIST_ENTRY *_move_history(int);
131
static int _history_search_gen(const char *, int, int);
132
static int _history_expand_command(const char *, size_t, char **);
133
static char *_rl_compat_sub(const char *, const char *,
135
static int rl_complete_internal(int);
136
static int _rl_qsort_string_compare(const void *, const void *);
139
* needed for prompt switching in readline()
141
static char *el_rl_prompt = NULL;
146
_get_prompt(EditLine *el __attribute__((unused)))
148
return (el_rl_prompt);
153
* generic function for moving around history
156
_move_history(int op)
159
static HIST_ENTRY rl_he;
161
if (history(h, &ev, op) != 0)
162
return (HIST_ENTRY *) NULL;
172
* READLINE compatibility stuff
176
* initialize rl compat stuff
195
rl_outstream = stdout;
198
* See if we don't really want to run the editor
200
if (tcgetattr(fileno(rl_instream), &t) != -1 && (t.c_lflag & ECHO) == 0)
203
e = el_init(rl_readline_name, rl_instream, rl_outstream, stderr);
206
el_set(e, EL_EDITMODE, 0);
212
history(h, &ev, H_SETSIZE, INT_MAX); /* unlimited */
214
max_input_history = INT_MAX;
215
el_set(e, EL_HIST, history, h);
217
/* for proper prompt printing in readline() */
218
el_rl_prompt = strdup("");
219
el_set(e, EL_PROMPT, _get_prompt);
220
el_set(e, EL_SIGNAL, 1);
222
/* set default mode to "emacs"-style and read setting afterwards */
223
/* so this can be overriden */
224
el_set(e, EL_EDITOR, "emacs");
227
* Word completition - this has to go AFTER rebinding keys
230
el_set(e, EL_ADDFN, "rl_complete",
231
"ReadLine compatible completition function",
233
el_set(e, EL_BIND, "^I", "rl_complete", NULL);
236
* Find out where the rl_complete function was added; this is
237
* used later to detect that lastcmd was also rl_complete.
239
for(i=EL_NUM_FCNS; i < e->el_map.nfunc; i++) {
240
if (e->el_map.func[i] == _el_rl_complete) {
241
el_rl_complete_cmdnum = i;
246
/* read settings from configuration file */
250
* Unfortunately, some applications really do use rl_point
251
* and rl_line_buffer directly.
254
/* LINTED const cast */
255
rl_line_buffer = (char *) li->buffer;
256
rl_point = rl_end = 0;
263
* read one line from input stream and return it, chomping
264
* trailing newline (if there is any)
267
readline(const char *prompt)
273
if (e == NULL || h == NULL)
276
/* update prompt accordingly to what has been passed */
279
if (strcmp(el_rl_prompt, prompt) != 0) {
281
el_rl_prompt = strdup(prompt);
283
/* get one line from input stream */
284
ret = el_gets(e, &count);
286
if (ret && count > 0) {
292
if (foo[lastidx] == '\n')
299
history(h, &ev, H_GETSIZE);
300
history_length = ev.num;
302
/* LINTED const cast */
311
* is normally called before application starts to use
312
* history expansion functions
317
if (h == NULL || e == NULL)
323
* substitute ``what'' with ``with'', returning resulting string; if
324
* globally == 1, substitutes all occurences of what, otherwise only the
328
_rl_compat_sub(const char *str, const char *what, const char *with,
332
const char *temp, *new;
333
unsigned int len, with_len, what_len, add;
336
result = malloc((size = 16));
338
with_len = strlen(with);
339
what_len = strlen(what);
342
new = strstr(temp, what);
346
if (i + add + 1 >= size) {
348
result = realloc(result, size);
350
(void) strncpy(&result[len], temp, i);
352
(void) strcpy(&result[len], with); /* safe */
354
temp = new + what_len;
357
if (len + add + 1 >= size) {
359
result = realloc(result, size);
361
(void) strcpy(&result[len], temp); /* safe */
365
} while (temp && globally);
373
* the real function doing history expansion - takes as argument command
374
* to do and data upon which the command should be executed
375
* does expansion the way I've understood readline documentation
376
* word designator ``%'' isn't supported (yet ?)
378
* returns 0 if data was not modified, 1 if it was and 2 if the string
379
* should be only printed and not executed; in case of error,
380
* returns -1 and *result points to NULL
381
* it's callers responsibility to free() string returned in *result
384
_history_expand_command(const char *command, size_t cmdlen, char **result)
386
char **arr, *tempcmd, *line, *search = NULL, *cmd;
387
const char *event_data = NULL;
388
static char *from = NULL, *to = NULL;
389
int start = -1, end = -1, max, i, idx;
390
int h_on = 0, t_on = 0, r_on = 0, e_on = 0, p_on = 0, g_on = 0;
391
int event_num = 0, retval;
396
cmd = alloca(cmdlen + 1);
397
(void) strncpy(cmd, command, cmdlen);
401
/* find out which event to take */
402
if (cmd[idx] == history_expansion_char) {
403
event_num = history_length;
409
while (cmd[off] && !strchr(":^$*-%", cmd[off]))
411
num = atoi(&cmd[idx]);
415
event_num += history_length + 1;
417
int prefix = 1, curr_num;
421
if (cmd[idx] == '?') {
423
if (cmd[off - 1] == '?')
425
else if (cmd[off] != '\n' && cmd[off] != '\0')
429
search = alloca(len + 1);
430
(void) strncpy(search, &cmd[idx], len);
433
if (history(h, &ev, H_CURR) != 0)
438
retval = history_search_prefix(search, -1);
440
retval = history_search(search, -1);
443
fprintf(rl_outstream, "%s: Event not found\n",
447
if (history(h, &ev, H_CURR) != 0)
451
/* roll back to original position */
452
history(h, &ev, H_NEXT_EVENT, curr_num);
457
if (!event_data && event_num >= 0) {
459
rl_he = history_get(event_num);
462
event_data = rl_he->line;
472
start = end = 1, cmd++;
473
else if (*cmd == '$')
474
start = end = -1, cmd++;
475
else if (*cmd == '*')
476
start = 1, end = -1, cmd++;
477
else if (isdigit((unsigned char) *cmd)) {
483
for (; isdigit((unsigned char) *cmd); cmd++);
486
if (shifted && *cmd == '-') {
487
if (!isdigit((unsigned char) *(cmd + 1)))
491
for (; isdigit((unsigned char) *cmd); cmd++);
493
} else if (shifted && *cmd == '*')
501
line = strdup(event_data);
502
for (; *cmd; cmd++) {
505
else if (*cmd == 'h')
506
h_on = 1 | g_on, g_on = 0;
507
else if (*cmd == 't')
508
t_on = 1 | g_on, g_on = 0;
509
else if (*cmd == 'r')
510
r_on = 1 | g_on, g_on = 0;
511
else if (*cmd == 'e')
512
e_on = 1 | g_on, g_on = 0;
513
else if (*cmd == 'p')
514
p_on = 1 | g_on, g_on = 0;
515
else if (*cmd == 'g')
517
else if (*cmd == 's' || *cmd == '&') {
518
char *what, *with, delim;
519
size_t len, from_len;
522
if (*cmd == '&' && (from == NULL || to == NULL))
524
else if (*cmd == 's') {
525
delim = *(++cmd), cmd++;
527
what = realloc(from, size);
529
for (; *cmd && *cmd != delim; cmd++) {
531
&& *(cmd + 1) == delim)
543
from = strdup(search);
549
cmd++; /* shift after delim */
554
with = realloc(to, size);
556
from_len = strlen(from);
557
for (; *cmd && *cmd != delim; cmd++) {
558
if (len + from_len + 1 >= size) {
559
size += from_len + 1;
560
with = realloc(with, size);
564
(void) strcpy(&with[len], from);
569
&& (*(cmd + 1) == delim
570
|| *(cmd + 1) == '&'))
577
tempcmd = _rl_compat_sub(line, from, to,
586
arr = history_tokenize(line);
587
free(line); /* no more needed */
588
if (arr && *arr == NULL)
589
free(arr), arr = NULL;
593
/* find out max valid idx to array of array */
595
for (i = 0; arr[i]; i++)
599
/* set boundaries to something relevant */
603
end = max - ((end < -1) ? 1 : 0);
605
/* check boundaries ... */
606
if (start > max || end > max || start > end)
609
for (i = 0; i <= max; i++) {
611
if (h_on && (i == 1 || h_on > 1) &&
612
(temp = strrchr(arr[i], '/')))
614
if (t_on && (i == 1 || t_on > 1) &&
615
(temp = strrchr(arr[i], '/')))
616
(void) strcpy(arr[i], temp + 1);
617
if (r_on && (i == 1 || r_on > 1) &&
618
(temp = strrchr(arr[i], '.')))
620
if (e_on && (i == 1 || e_on > 1) &&
621
(temp = strrchr(arr[i], '.')))
622
(void) strcpy(arr[i], temp);
625
cmdsize = 1, cmdlen = 0;
626
tempcmd = malloc(cmdsize);
627
for (i = start; start <= i && i <= end; i++) {
630
arr_len = strlen(arr[i]);
631
if (cmdlen + arr_len + 1 >= cmdsize) {
632
cmdsize += arr_len + 1;
633
tempcmd = realloc(tempcmd, cmdsize);
635
(void) strcpy(&tempcmd[cmdlen], arr[i]); /* safe */
637
tempcmd[cmdlen++] = ' '; /* add a space */
639
while (cmdlen > 0 && isspace((unsigned char) tempcmd[cmdlen - 1]))
641
tempcmd[cmdlen] = '\0';
645
for (i = 0; i <= max; i++)
647
free(arr), arr = (char **) NULL;
648
return (p_on) ? 2 : 1;
653
* csh-style history expansion
656
history_expand(char *str, char **output)
658
int i, retval = 0, idx;
662
if (h == NULL || e == NULL)
665
*output = strdup(str); /* do it early */
667
if (str[0] == history_subst_char) {
668
/* ^foo^foo2^ is equivalent to !!:s^foo^foo2^ */
669
temp = alloca(4 + strlen(str) + 1);
670
temp[0] = temp[1] = history_expansion_char;
673
(void) strcpy(temp + 4, str);
676
#define ADD_STRING(what, len) \
678
if (idx + len + 1 > size) \
679
result = realloc(result, (size += len + 1)); \
680
(void)strncpy(&result[idx], what, len); \
682
result[idx] = '\0'; \
687
for (i = 0; str[i];) {
688
int start, j, loop_again;
694
for (; str[j]; j++) {
695
if (str[j] == '\\' &&
696
str[j + 1] == history_expansion_char) {
697
(void) strcpy(&str[j], &str[j + 1]);
702
while (str[j] && str[++j] != '?');
705
} else if (isspace((unsigned char) str[j]))
708
if (str[j] == history_expansion_char
709
&& !strchr(history_no_expand_chars, str[j + 1])
710
&& (!history_inhibit_expansion_function ||
711
(*history_inhibit_expansion_function)(str, j) == 0))
715
if (str[j] && str[j + 1] != '#' && loop_again) {
718
if (str[j] == history_expansion_char)
725
ADD_STRING(temp, len);
727
if (str[i] == '\0' || str[i] != history_expansion_char
728
|| str[i + 1] == '#') {
731
ADD_STRING(temp, len);
738
retval = _history_expand_command(&str[i], (size_t) (j - i),
742
ADD_STRING(temp, len);
750
/* gdb 4.11 has been shipped with readline, where */
751
/* history_expand() returned -1 when the line */
752
/* should not be executed; in readline 2.1+ */
753
/* it should return 2 in such a case */
765
* Parse the string into individual tokens, similarily to how shell would do it.
768
history_tokenize(const char *str)
770
int size = 1, result_idx = 0, i, start;
772
char **result = NULL, *temp, delim = '\0';
774
for (i = 0; str[i]; i++) {
775
while (isspace((unsigned char) str[i]))
778
for (; str[i]; i++) {
779
if (str[i] == '\\') {
780
if (str[i+1] != '\0')
782
} else if (str[i] == delim)
785
(isspace((unsigned char) str[i]) ||
786
strchr("()<>;&|$", str[i])))
788
else if (!delim && strchr("'`\"", str[i]))
792
if (result_idx + 2 >= size) {
794
result = realloc(result, size * sizeof(char *));
797
temp = malloc(len + 1);
798
(void) strncpy(temp, &str[start], len);
800
result[result_idx++] = temp;
801
result[result_idx] = NULL;
809
* limit size of history record to ``max'' events
812
stifle_history(int max)
816
if (h == NULL || e == NULL)
819
if (history(h, &ev, H_SETSIZE, max) == 0)
820
max_input_history = max;
825
* "unlimit" size of history - set the limit to maximum allowed int value
828
unstifle_history(void)
833
history(h, &ev, H_SETSIZE, INT_MAX);
834
omax = max_input_history;
835
max_input_history = INT_MAX;
836
return (omax); /* some value _must_ be returned */
841
history_is_stifled(void)
844
/* cannot return true answer */
845
return (max_input_history != INT_MAX);
850
* read history from a file given
853
read_history(const char *filename)
857
if (h == NULL || e == NULL)
859
return (history(h, &ev, H_LOAD, filename));
864
* write history to a file given
867
write_history(const char *filename)
871
if (h == NULL || e == NULL)
873
return (history(h, &ev, H_SAVE, filename));
878
* returns history ``num''th event
880
* returned pointer points to static variable
885
static HIST_ENTRY she;
889
if (h == NULL || e == NULL)
892
/* rewind to beginning */
893
if (history(h, &ev, H_CURR) != 0)
896
if (history(h, &ev, H_LAST) != 0)
897
return (NULL); /* error */
898
while (i < num && history(h, &ev, H_PREV) == 0)
901
return (NULL); /* not so many entries */
906
/* rewind history to the same event it was before */
907
(void) history(h, &ev, H_FIRST);
908
(void) history(h, &ev, H_NEXT_EVENT, curr_num);
915
* add the line to history table
918
add_history(const char *line)
922
if (h == NULL || e == NULL)
925
(void) history(h, &ev, H_ENTER, line);
926
if (history(h, &ev, H_GETSIZE) == 0)
927
history_length = ev.num;
929
return (!(history_length > 0)); /* return 0 if all is okay */
934
* clear the history list - delete all entries
941
history(h, &ev, H_CLEAR);
946
* returns offset of the current history event
954
if (history(h, &ev, H_CURR) != 0)
958
history(h, &ev, H_FIRST);
960
while (ev.num != curr_num && history(h, &ev, H_NEXT) == 0)
968
* returns current history event or NULL if there is no such event
971
current_history(void)
974
return (_move_history(H_CURR));
979
* returns total number of bytes history events' data are using
982
history_total_bytes(void)
987
if (history(h, &ev, H_CURR) != 0)
991
history(h, &ev, H_FIRST);
994
size += strlen(ev.str);
995
while (history(h, &ev, H_NEXT) == 0);
997
/* get to the same position as before */
998
history(h, &ev, H_PREV_EVENT, curr_num);
1005
* sets the position in the history list to ``pos''
1008
history_set_pos(int pos)
1013
if (pos > history_length || pos < 0)
1016
history(h, &ev, H_CURR);
1018
history(h, &ev, H_FIRST);
1020
while (off < pos && history(h, &ev, H_NEXT) == 0)
1023
if (off != pos) { /* do a rollback in case of error */
1024
history(h, &ev, H_FIRST);
1025
history(h, &ev, H_NEXT_EVENT, curr_num);
1033
* returns previous event in history and shifts pointer accordingly
1036
previous_history(void)
1039
return (_move_history(H_PREV));
1044
* returns next event in history and shifts pointer accordingly
1050
return (_move_history(H_NEXT));
1055
* generic history search function
1058
_history_search_gen(const char *str, int direction, int pos)
1064
if (history(h, &ev, H_CURR) != 0)
1069
strp = strstr(ev.str, str);
1070
if (strp && (pos < 0 || &ev.str[pos] == strp))
1071
return (int) (strp - ev.str);
1072
if (history(h, &ev, direction < 0 ? H_PREV : H_NEXT) != 0)
1076
history(h, &ev, direction < 0 ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1083
* searches for first history event containing the str
1086
history_search(const char *str, int direction)
1089
return (_history_search_gen(str, direction, -1));
1094
* searches for first history event beginning with str
1097
history_search_prefix(const char *str, int direction)
1100
return (_history_search_gen(str, direction, 0));
1105
* search for event in history containing str, starting at offset
1106
* abs(pos); continue backward, if pos<0, forward otherwise
1110
history_search_pos(const char *str,
1111
int direction __attribute__((unused)), int pos)
1116
off = (pos > 0) ? pos : -pos;
1117
pos = (pos > 0) ? 1 : -1;
1119
if (history(h, &ev, H_CURR) != 0)
1123
if (history_set_pos(off) != 0 || history(h, &ev, H_CURR) != 0)
1128
if (strstr(ev.str, str))
1130
if (history(h, &ev, (pos < 0) ? H_PREV : H_NEXT) != 0)
1134
/* set "current" pointer back to previous state */
1135
history(h, &ev, (pos < 0) ? H_NEXT_EVENT : H_PREV_EVENT, curr_num);
1141
/********************************/
1142
/* completition functions */
1145
* does tilde expansion of strings of type ``~user/foo''
1146
* if ``user'' isn't valid user name or ``txt'' doesn't start
1147
* w/ '~', returns pointer to strdup()ed copy of ``txt''
1149
* it's callers's responsibility to free() returned string
1152
tilde_expand(char *txt)
1154
struct passwd *pass;
1159
return (strdup(txt));
1161
temp = strchr(txt + 1, '/');
1163
temp = strdup(txt + 1);
1165
len = temp - txt + 1; /* text until string after slash */
1167
(void) strncpy(temp, txt + 1, len - 2);
1168
temp[len - 2] = '\0';
1170
pass = getpwnam(temp);
1171
free(temp); /* value no more needed */
1173
return (strdup(txt));
1175
/* update pointer txt to point at string immedially following */
1179
temp = malloc(strlen(pass->pw_dir) + 1 + strlen(txt) + 1);
1180
(void) sprintf(temp, "%s/%s", pass->pw_dir, txt);
1187
* return first found file name starting by the ``text'' or NULL if no
1188
* such file can be found
1189
* value of ``state'' is ignored
1191
* it's caller's responsibility to free returned string
1194
filename_completion_function(const char *text, int state)
1196
static DIR *dir = NULL;
1197
static char *filename = NULL, *dirname = NULL;
1198
static size_t filename_len = 0;
1199
struct dirent *entry;
1203
if (state == 0 || dir == NULL) {
1208
temp = strrchr(text, '/');
1211
filename = realloc(filename, strlen(temp) + 1);
1212
(void) strcpy(filename, temp);
1213
len = temp - text; /* including last slash */
1214
dirname = realloc(dirname, len + 1);
1215
(void) strncpy(dirname, text, len);
1216
dirname[len] = '\0';
1218
filename = strdup(text);
1222
/* support for ``~user'' syntax */
1223
if (dirname && *dirname == '~') {
1224
temp = tilde_expand(dirname);
1225
dirname = realloc(dirname, strlen(temp) + 1);
1226
(void) strcpy(dirname, temp); /* safe */
1227
free(temp); /* no longer needed */
1229
/* will be used in cycle */
1230
filename_len = strlen(filename);
1231
if (filename_len == 0)
1232
return (NULL); /* no expansion possible */
1234
dir = opendir(dirname ? dirname : ".");
1236
return (NULL); /* cannot open the directory */
1238
/* find the match */
1239
while ((entry = readdir(dir)) != NULL) {
1240
/* otherwise, get first entry where first */
1241
/* filename_len characters are equal */
1242
if (entry->d_name[0] == filename[0]
1243
#if defined(__SVR4) || defined(__linux__)
1244
&& strlen(entry->d_name) >= filename_len
1246
&& entry->d_namlen >= filename_len
1248
&& strncmp(entry->d_name, filename,
1253
if (entry) { /* match found */
1256
#if defined(__SVR4) || defined(__linux__)
1257
len = strlen(entry->d_name) +
1259
len = entry->d_namlen +
1261
((dirname) ? strlen(dirname) : 0) + 1 + 1;
1263
(void) sprintf(temp, "%s%s",
1264
dirname ? dirname : "", entry->d_name); /* safe */
1266
/* test, if it's directory */
1267
if (stat(temp, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
1268
strcat(temp, "/"); /* safe */
1277
* a completion generator for usernames; returns _first_ username
1278
* which starts with supplied text
1279
* text contains a partial username preceded by random character
1280
* (usually '~'); state is ignored
1281
* it's callers responsibility to free returned value
1284
username_completion_function(const char *text, int state)
1288
if (text[0] == '\0')
1297
while ((pwd = getpwent()) && text[0] == pwd->pw_name[0]
1298
&& strcmp(text, pwd->pw_name) == 0);
1304
return (strdup(pwd->pw_name));
1309
* el-compatible wrapper around rl_complete; needed for key binding
1312
static unsigned char
1313
_el_rl_complete(EditLine *el __attribute__((unused)), int ch)
1315
return (unsigned char) rl_complete(0, ch);
1320
* returns list of completitions for text given
1323
completion_matches(const char *text, CPFunction *genfunc)
1325
char **match_list = NULL, *retstr, *prevstr;
1326
size_t match_list_len, max_equal, which, i;
1327
unsigned int matches;
1329
if (h == NULL || e == NULL)
1334
while ((retstr = (*genfunc) (text, matches)) != NULL) {
1335
if (matches + 1 >= match_list_len) {
1336
match_list_len <<= 1;
1337
match_list = realloc(match_list,
1338
match_list_len * sizeof(char *));
1340
match_list[++matches] = retstr;
1344
return (char **) NULL; /* nothing found */
1346
/* find least denominator and insert it to match_list[0] */
1348
prevstr = match_list[1];
1349
max_equal = strlen(prevstr);
1350
for (; which <= matches; which++) {
1351
for (i = 0; i < max_equal &&
1352
prevstr[i] == match_list[which][i]; i++)
1357
retstr = malloc(max_equal + 1);
1358
(void) strncpy(retstr, match_list[1], max_equal);
1359
retstr[max_equal] = '\0';
1360
match_list[0] = retstr;
1362
/* add NULL as last pointer to the array */
1363
if (matches + 1 >= match_list_len)
1364
match_list = realloc(match_list,
1365
(match_list_len + 1) * sizeof(char *));
1366
match_list[matches + 1] = (char *) NULL;
1368
return (match_list);
1372
* Sort function for qsort(). Just wrapper around strcasecmp().
1375
_rl_qsort_string_compare(i1, i2)
1376
const void *i1, *i2;
1378
/*LINTED const castaway*/
1379
const char *s1 = ((const char **)i1)[0];
1380
/*LINTED const castaway*/
1381
const char *s2 = ((const char **)i2)[0];
1383
return strcasecmp(s1, s2);
1387
* Display list of strings in columnar format on readline's output stream.
1388
* 'matches' is list of strings, 'len' is number of strings in 'matches',
1389
* 'max' is maximum length of string in 'matches'.
1392
rl_display_match_list (matches, len, max)
1396
int i, idx, limit, count;
1397
int screenwidth = e->el_term.t_size.h;
1400
* Find out how many entries can be put on one line, count
1401
* with two spaces between strings.
1403
limit = screenwidth / (max + 2);
1407
/* how many lines of output */
1408
count = len / limit;
1409
if (count * limit < len)
1412
/* Sort the items if they are not already sorted. */
1413
qsort(&matches[1], (size_t)(len - 1), sizeof(char *),
1414
_rl_qsort_string_compare);
1417
for(; count > 0; count--) {
1418
for(i=0; i < limit && matches[idx]; i++, idx++)
1419
fprintf(e->el_outfile, "%-*s ", max, matches[idx]);
1420
fprintf(e->el_outfile, "\n");
1425
* Complete the word at or before point, called by rl_complete()
1426
* 'what_to_do' says what to do with the completion.
1427
* `?' means list the possible completions.
1428
* TAB means do standard completion.
1429
* `*' means insert all of the possible completions.
1430
* `!' means to do standard completion, and list all possible completions if
1431
* there is more than one.
1433
* Note: '*' support is not implemented
1436
rl_complete_internal(int what_to_do)
1438
CPFunction *complet_func;
1440
char *temp, **matches;
1444
rl_completion_type = what_to_do;
1446
if (h == NULL || e == NULL)
1449
complet_func = rl_completion_entry_function;
1451
complet_func = filename_completion_function;
1453
/* We now look backwards for the start of a filename/variable word */
1455
ctemp = (const char *) li->cursor;
1456
while (ctemp > li->buffer
1457
&& !strchr(rl_basic_word_break_characters, ctemp[-1])
1458
&& (!rl_special_prefixes
1459
|| !strchr(rl_special_prefixes, ctemp[-1]) ) )
1462
len = li->cursor - ctemp;
1463
temp = alloca(len + 1);
1464
(void) strncpy(temp, ctemp, len);
1467
/* these can be used by function called in completion_matches() */
1468
/* or (*rl_attempted_completion_function)() */
1469
rl_point = li->cursor - li->buffer;
1470
rl_end = li->lastchar - li->buffer;
1472
if (!rl_attempted_completion_function)
1473
matches = completion_matches(temp, complet_func);
1475
int end = li->cursor - li->buffer;
1476
matches = (*rl_attempted_completion_function) (temp, (int)
1481
int i, retval = CC_REFRESH;
1482
int matches_num, maxlen, match_len, match_display=1;
1485
* Only replace the completed string with common part of
1486
* possible matches if there is possible completion.
1488
if (matches[0][0] != '\0') {
1489
el_deletestr(e, (int) len);
1490
el_insertstr(e, matches[0]);
1493
if (what_to_do == '?')
1494
goto display_matches;
1496
if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) {
1498
* We found exact match. Add a space after
1499
* it, unless we do filename completition and the
1500
* object is a directory.
1502
size_t alen = strlen(matches[0]);
1503
if ((complet_func != filename_completion_function
1504
|| (alen > 0 && (matches[0])[alen - 1] != '/'))
1505
&& rl_completion_append_character) {
1507
buf[0] = rl_completion_append_character;
1509
el_insertstr(e, buf);
1511
} else if (what_to_do == '!') {
1514
* More than one match and requested to list possible
1518
for(i=1, maxlen=0; matches[i]; i++) {
1519
match_len = strlen(matches[i]);
1520
if (match_len > maxlen)
1523
matches_num = i - 1;
1525
/* newline to get on next line from command line */
1526
fprintf(e->el_outfile, "\n");
1529
* If there are too many items, ask user for display
1532
if (matches_num > rl_completion_query_items) {
1533
fprintf(e->el_outfile,
1534
"Display all %d possibilities? (y or n) ",
1536
fflush(e->el_outfile);
1537
if (getc(stdin) != 'y')
1539
fprintf(e->el_outfile, "\n");
1543
rl_display_match_list(matches, matches_num,
1545
retval = CC_REDISPLAY;
1546
} else if (matches[0][0]) {
1548
* There was some common match, but the name was
1549
* not complete enough. Next tab will print possible
1554
/* lcd is not a valid object - further specification */
1560
/* free elements of array and the array itself */
1561
for (i = 0; matches[i]; i++)
1563
free(matches), matches = NULL;
1572
* complete word at current point
1575
rl_complete(int ignore, int invoking_key)
1577
if (h == NULL || e == NULL)
1580
if (rl_inhibit_completion) {
1581
rl_insert(ignore, invoking_key);
1582
return (CC_REFRESH);
1583
} else if (e->el_state.lastcmd == el_rl_complete_cmdnum)
1584
return rl_complete_internal('?');
1585
else if (_rl_complete_show_all)
1586
return rl_complete_internal('!');
1588
return (rl_complete_internal(TAB));
1593
* misc other functions
1597
* bind key c to readline-type function func
1600
rl_bind_key(int c, int func(int, int))
1604
if (h == NULL || e == NULL)
1607
if (func == rl_insert) {
1608
/* XXX notice there is no range checking of ``c'' */
1609
e->el_map.key[c] = ED_INSERT;
1617
* read one key from input - handles chars pushed back
1618
* to input stream also
1623
char fooarr[2 * sizeof(int)];
1625
if (e == NULL || h == NULL)
1628
return (el_getc(e, fooarr));
1633
* reset the terminal
1637
rl_reset_terminal(const char *p __attribute__((unused)))
1640
if (h == NULL || e == NULL)
1647
* insert character ``c'' back into input stream, ``count'' times
1650
rl_insert(int count, int c)
1654
if (h == NULL || e == NULL)
1657
/* XXX - int -> char conversion can lose on multichars */
1661
for (; count > 0; count--)