Several features were hard coded on. Stop that. List tab completion
[oweals/busybox.git] / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting.
4  *
5  * Copyright (c) 1986-2001 may safely be consumed by a BSD or GPL license.
6  * Written by:   Vladimir Oleynik <vodz@usa.net>
7  *
8  * Used ideas:
9  *      Adam Rogoyski    <rogoyski@cs.utexas.edu>
10  *      Dave Cinege      <dcinege@psychosis.com>
11  *      Jakub Jelinek (c) 1995
12  *      Erik Andersen    <andersee@debian.org> (Majorly adjusted for busybox)
13  *
14  * This code is 'as is' with no warranty.
15  *
16  *
17  */
18
19 /*
20    Usage and Known bugs:
21    Terminal key codes are not extensive, and more will probably
22    need to be added. This version was created on Debian GNU/Linux 2.x.
23    Delete, Backspace, Home, End, and the arrow keys were tested
24    to work in an Xterm and console. Ctrl-A also works as Home.
25    Ctrl-E also works as End.
26
27    Small bugs (simple effect):
28    - not true viewing if terminal size (x*y symbols) less
29      size (prompt + editor`s line + 2 symbols)
30  */
31
32
33 //#define TEST
34
35
36 #ifndef TEST
37
38 #include "busybox.h"
39
40 #define D(x)
41
42 #else
43
44 //#define BB_FEATURE_NONPRINTABLE_INVERSE_PUT
45 //#define BB_FEATURE_BASH_STYLE_PROMT
46
47 #define TRUE  1
48 #define FALSE 0
49 #define D(x)  x
50
51 #endif                                                  /* TEST */
52
53 #ifdef BB_FEATURE_SH_COMMAND_EDITING
54
55 #ifndef BB_FEATURE_SH_TAB_COMPLETION
56 #undef  BB_FEATURE_SH_USERNAME_COMPLETION
57 #endif
58
59 #if defined(BB_FEATURE_SH_USERNAME_COMPLETION) || defined(BB_FEATURE_BASH_STYLE_PROMT)
60 #define BB_FEATURE_GETUSERNAME_AND_HOMEDIR
61 #endif
62
63 #include <stdio.h>
64 #include <errno.h>
65 #include <unistd.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <sys/ioctl.h>
69 #include <ctype.h>
70 #include <signal.h>
71 #include <limits.h>
72
73 #ifdef BB_FEATURE_SH_TAB_COMPLETION
74 #include <dirent.h>
75 #include <sys/stat.h>
76 #endif
77
78 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
79 #ifndef TEST
80 #include "pwd_grp/pwd.h"
81 #else
82 #include <pwd.h>
83 #endif                                                  /* TEST */
84 #endif                                                  /* advanced FEATURES */
85
86
87 #ifdef TEST
88 void *xrealloc(void *old, size_t size)
89 {
90         return realloc(old, size);
91 }
92
93 void *xmalloc(size_t size)
94 {
95         return malloc(size);
96 }
97 char *xstrdup(const char *s)
98 {
99         return strdup(s);
100 }
101
102 void *xcalloc(size_t size, size_t se)
103 {
104         return calloc(size, se);
105 }
106
107 #define error_msg(s, d)                   fprintf(stderr, s, d)
108 #endif
109
110
111 struct history {
112         char *s;
113         struct history *p;
114         struct history *n;
115 };
116
117 /* Maximum length of the linked list for the command line history */
118 static const int MAX_HISTORY = 15;
119
120 /* First element in command line list */
121 static struct history *his_front = NULL;
122
123 /* Last element in command line list */
124 static struct history *his_end = NULL;
125
126
127 /* ED: sparc termios is broken: revert back to old termio handling. */
128
129 #if #cpu(sparc)
130 #      include <termio.h>
131 #      define termios termio
132 #      define setTermSettings(fd,argp) ioctl(fd,TCSETAF,argp)
133 #      define getTermSettings(fd,argp) ioctl(fd,TCGETA,argp)
134 #else
135 #      include <termios.h>
136 #      define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
137 #      define getTermSettings(fd,argp) tcgetattr(fd, argp);
138 #endif
139
140 /* Current termio and the previous termio before starting sh */
141 static struct termios initial_settings, new_settings;
142
143
144 #ifndef _POSIX_VDISABLE
145 #define _POSIX_VDISABLE '\0'
146 #endif
147
148
149 static
150 volatile int cmdedit_termw = 80;        /* actual terminal width */
151 static int history_counter = 0; /* Number of commands in history list */
152 static
153 volatile int handlers_sets = 0; /* Set next bites: */
154
155 enum {
156         SET_ATEXIT = 1,                         /* when atexit() has been called and
157                                                                    get euid,uid,gid to fast compare  */
158         SET_TERM_HANDLERS = 2,          /* set many terminates signal handlers */
159         SET_WCHG_HANDLERS = 4,          /* winchg signal handler */
160         SET_RESET_TERM = 8,                     /* if the terminal needs to be reset upon exit */
161 };
162
163
164 static int cmdedit_x;                   /* real x terminal position */
165 static int cmdedit_y;                   /* pseudoreal y terminal position */
166 static int cmdedit_prmt_len;    /* lenght prompt without colores string */
167
168 static int cursor;                              /* required global for signal handler */
169 static int len;                                 /* --- "" - - "" - -"- --""-- --""--- */
170 static char *command_ps;                /* --- "" - - "" - -"- --""-- --""--- */
171 static
172 #ifndef BB_FEATURE_BASH_STYLE_PROMT
173         const
174 #endif
175 char *cmdedit_prompt;                   /* --- "" - - "" - -"- --""-- --""--- */
176
177 /* Link into lash to reset context to 0 on ^C and such */
178 extern unsigned int shell_context;
179
180
181 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
182 static char *user_buf = "";
183 static char *home_pwd_buf = "";
184 static int my_euid;
185 #endif
186
187 #ifdef BB_FEATURE_BASH_STYLE_PROMT
188 static char *hostname_buf = "";
189 static int num_ok_lines = 1;
190 #endif
191
192
193 #ifdef  BB_FEATURE_SH_TAB_COMPLETION
194
195 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
196 static int my_euid;
197 #endif
198
199 static int my_uid;
200 static int my_gid;
201
202 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
203
204
205 static void cmdedit_setwidth(int w, int redraw_flg);
206
207 static void win_changed(int nsig)
208 {
209         struct winsize win = { 0, 0, 0, 0 };
210         static __sighandler_t previous_SIGWINCH_handler;        /* for reset */
211
212         /*   emulate      || signal call */
213         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
214                 ioctl(0, TIOCGWINSZ, &win);
215                 if (win.ws_col > 0) {
216                         cmdedit_setwidth(win.ws_col, nsig == SIGWINCH);
217                 } 
218         }
219         /* Unix not all standart in recall signal */
220
221         if (nsig == -SIGWINCH)          /* save previous handler   */
222                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
223         else if (nsig == SIGWINCH)      /* signaled called handler */
224                 signal(SIGWINCH, win_changed);  /* set for next call       */
225         else                                            /* nsig == 0 */
226                 /* set previous handler    */
227                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
228 }
229
230 static void cmdedit_reset_term(void)
231 {
232         if ((handlers_sets & SET_RESET_TERM) != 0) {
233                 /* sparc and other have broken termios support: use old termio handling. */
234                 setTermSettings(fileno(stdin), (void *) &initial_settings);
235                 handlers_sets &= ~SET_RESET_TERM;
236         }
237         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
238                 /* reset SIGWINCH handler to previous (default) */
239                 win_changed(0);
240                 handlers_sets &= ~SET_WCHG_HANDLERS;
241         }
242         fflush(stdout);
243 #ifdef BB_FEATURE_CLEAN_UP
244         if (his_front) {
245                 struct history *n;
246
247                 //while(his_front!=his_end) {
248                 while (his_front != his_end) {
249                         n = his_front->n;
250                         free(his_front->s);
251                         free(his_front);
252                         his_front = n;
253                 }
254         }
255 #endif
256 }
257
258
259 /* special for recount position for scroll and remove terminal margin effect */
260 static void cmdedit_set_out_char(int next_char)
261 {
262
263         int c = command_ps[cursor];
264
265         if (c == 0)
266                 c = ' ';                                /* destroy end char? */
267 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
268         if (!isprint(c)) {                      /* Inverse put non-printable characters */
269                 if (((unsigned char) c) >= 128)
270                         c -= 128;
271                 if (((unsigned char) c) < ' ')
272                         c += '@';
273                 if (c == 127)
274                         c = '?';
275                 printf("\033[7m%c\033[0m", c);
276         } else
277 #endif
278                 putchar(c);
279         if (++cmdedit_x >= cmdedit_termw) {
280                 /* terminal is scrolled down */
281                 cmdedit_y++;
282                 cmdedit_x = 0;
283
284                 if (!next_char)
285                         next_char = ' ';
286                 /* destroy "(auto)margin" */
287                 putchar(next_char);
288                 putchar('\b');
289         }
290         cursor++;
291 }
292
293 /* Move to end line. Bonus: rewrite line from cursor */
294 static void input_end(void)
295 {
296         while (cursor < len)
297                 cmdedit_set_out_char(0);
298 }
299
300 /* Go to the next line */
301 static void goto_new_line(void)
302 {
303         input_end();
304         if (cmdedit_x)
305                 putchar('\n');
306 }
307
308
309 static inline void out1str(const char *s)
310 {
311         fputs(s, stdout);
312 }
313 static inline void beep(void)
314 {
315         putchar('\007');
316 }
317
318 /* Move back one charactor */
319 /* special for slow terminal */
320 static void input_backward(int num)
321 {
322         if (num > cursor)
323                 num = cursor;
324         cursor -= num;                          /* new cursor (in command, not terminal) */
325
326         if (cmdedit_x >= num) {         /* no to up line */
327                 cmdedit_x -= num;
328                 if (num < 4)
329                         while (num-- > 0)
330                                 putchar('\b');
331
332                 else
333                         printf("\033[%dD", num);
334         } else {
335                 int count_y;
336
337                 if (cmdedit_x) {
338                         putchar('\r');          /* back to first terminal pos.  */
339                         num -= cmdedit_x;       /* set previous backward        */
340                 }
341                 count_y = 1 + num / cmdedit_termw;
342                 printf("\033[%dA", count_y);
343                 cmdedit_y -= count_y;
344                 /*  require  forward  after  uping   */
345                 cmdedit_x = cmdedit_termw * count_y - num;
346                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
347         }
348 }
349
350 static void put_prompt(void)
351 {
352         out1str(cmdedit_prompt);
353         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
354         cursor = 0;
355 }
356
357 #ifdef BB_FEATURE_BASH_STYLE_PROMT
358 static void
359 add_to_prompt(char **prmt_mem_ptr, int *alm, int *prmt_len,
360                           const char *addb)
361 {
362         int l = strlen(addb);
363
364         *prmt_len += l;
365         if (*alm < (*prmt_len) + 1) {
366                 *alm = (*prmt_len) + 1;
367                 *prmt_mem_ptr = xrealloc(*prmt_mem_ptr, *alm);
368         }
369         strcat(*prmt_mem_ptr, addb);
370 }
371 #endif
372
373 static void parse_prompt(const char *prmt_ptr)
374 {
375 #ifdef BB_FEATURE_BASH_STYLE_PROMT
376         int alm = strlen(prmt_ptr) + 1; /* supposedly require memory */
377         int prmt_len = 0;
378         int sub_len = 0;
379         int flg_not_length = '[';
380         char *prmt_mem_ptr = xstrdup(prmt_ptr);
381         char pwd_buf[PATH_MAX + 1];
382         char buf[16];
383         int c;
384
385         pwd_buf[0] = 0;
386         *prmt_mem_ptr = 0;
387
388         while (*prmt_ptr) {
389                 c = *prmt_ptr++;
390                 if (c == '\\') {
391                         c = *prmt_ptr;
392                         if (c == 0)
393                                 break;
394                         prmt_ptr++;
395                         switch (c) {
396                         case 'u':
397                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, user_buf);
398                                 continue;
399                         case 'h':
400                                 if (hostname_buf[0] == 0) {
401                                         hostname_buf = xcalloc(256, 1);
402                                         if (gethostname(hostname_buf, 255) < 0) {
403                                                 strcpy(hostname_buf, "?");
404                                         } else {
405                                                 char *s = strchr(hostname_buf, '.');
406
407                                                 if (s)
408                                                         *s = 0;
409                                         }
410                                 }
411                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len,
412                                                           hostname_buf);
413                                 continue;
414                         case '$':
415                                 c = my_euid == 0 ? '#' : '$';
416                                 break;
417                         case 'w':
418                                 if (pwd_buf[0] == 0) {
419                                         int l;
420
421                                         getcwd(pwd_buf, PATH_MAX);
422                                         l = strlen(home_pwd_buf);
423                                         if (home_pwd_buf[0] != 0 &&
424                                                 strncmp(home_pwd_buf, pwd_buf, l) == 0) {
425                                                 strcpy(pwd_buf + 1, pwd_buf + l);
426                                                 pwd_buf[0] = '~';
427                                         }
428                                 }
429                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, pwd_buf);
430                                 continue;
431                         case '!':
432                                 snprintf(buf, sizeof(buf), "%d", num_ok_lines);
433                                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
434                                 continue;
435                         case 'e':
436                         case 'E':                       /* \e \E = \033 */
437                                 c = '\033';
438                                 break;
439                         case 'x':
440                         case 'X':
441                         case '0':
442                         case '1':
443                         case '2':
444                         case '3':
445                         case '4':
446                         case '5':
447                         case '6':
448                         case '7':{
449                                 int l;
450                                 int ho = 0;
451                                 char *eho;
452
453                                 if (c == 'X')
454                                         c = 'x';
455
456                                 for (l = 0; l < 3;) {
457
458                                         buf[l++] = *prmt_ptr;
459                                         buf[l] = 0;
460                                         ho = strtol(buf, &eho, c == 'x' ? 16 : 8);
461                                         if (ho > UCHAR_MAX || (eho - buf) < l) {
462                                                 l--;
463                                                 break;
464                                         }
465                                         prmt_ptr++;
466                                 }
467                                 buf[l] = 0;
468                                 ho = strtol(buf, 0, c == 'x' ? 16 : 8);
469                                 c = ho == 0 ? '?' : (char) ho;
470                                 break;
471                         }
472                         case '[':
473                         case ']':
474                                 if (c == flg_not_length) {
475                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
476                                         continue;
477                                 }
478                                 break;
479                         }
480                 }
481                 buf[0] = c;
482                 buf[1] = 0;
483                 add_to_prompt(&prmt_mem_ptr, &alm, &prmt_len, buf);
484                 if (flg_not_length == ']')
485                         sub_len++;
486         }
487         cmdedit_prmt_len = prmt_len - sub_len;
488         cmdedit_prompt = prmt_mem_ptr;
489 #else
490         cmdedit_prompt = prmt_ptr;
491         cmdedit_prmt_len = strlen(prmt_ptr);
492 #endif
493         put_prompt();
494 }
495
496
497 /* draw promt, editor line, and clear tail */
498 static void redraw(int y, int back_cursor)
499 {
500         if (y > 0)                                      /* up to start y */
501                 printf("\033[%dA", y);
502         cmdedit_y = 0;                          /* new quasireal y */
503         putchar('\r');
504         put_prompt();
505         input_end();                            /* rewrite */
506         printf("\033[J");                       /* destroy tail after cursor */
507         input_backward(back_cursor);
508 }
509
510 /* Delete the char in front of the cursor */
511 static void input_delete(void)
512 {
513         int j = cursor;
514
515         if (j == len)
516                 return;
517
518         strcpy(command_ps + j, command_ps + j + 1);
519         len--;
520         input_end();                            /* rewtite new line */
521         cmdedit_set_out_char(0);        /* destroy end char */
522         input_backward(cursor - j);     /* back to old pos cursor */
523 }
524
525 /* Delete the char in back of the cursor */
526 static void input_backspace(void)
527 {
528         if (cursor > 0) {
529                 input_backward(1);
530                 input_delete();
531         }
532 }
533
534
535 /* Move forward one charactor */
536 static void input_forward(void)
537 {
538         if (cursor < len)
539                 cmdedit_set_out_char(command_ps[cursor + 1]);
540 }
541
542
543 static void clean_up_and_die(int sig)
544 {
545         goto_new_line();
546         if (sig != SIGINT)
547                 exit(EXIT_SUCCESS);             /* cmdedit_reset_term() called in atexit */
548         cmdedit_reset_term();
549 }
550
551 static void cmdedit_setwidth(int w, int redraw_flg)
552 {
553         cmdedit_termw = cmdedit_prmt_len + 2;
554         if (w <= cmdedit_termw) {
555                 cmdedit_termw = cmdedit_termw % w;
556         }
557         if (w > cmdedit_termw) {
558
559                 cmdedit_termw = w;
560
561                 if (redraw_flg) {
562                         /* new y for current cursor */
563                         int new_y = (cursor + cmdedit_prmt_len) / w;
564
565                         /* redraw */
566                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
567                         fflush(stdout);
568                 }
569         } 
570 }
571
572 extern void cmdedit_init(void)
573 {
574         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
575                 /* emulate usage handler to set handler and call yours work */
576                 win_changed(-SIGWINCH);
577                 handlers_sets |= SET_WCHG_HANDLERS;
578         }
579
580         if ((handlers_sets & SET_ATEXIT) == 0) {
581 #ifdef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
582                 struct passwd *entry;
583
584                 my_euid = geteuid();
585                 entry = getpwuid(my_euid);
586                 if (entry) {
587                         user_buf = xstrdup(entry->pw_name);
588                         home_pwd_buf = xstrdup(entry->pw_dir);
589                 }
590 #endif
591
592 #ifdef  BB_FEATURE_SH_TAB_COMPLETION
593
594 #ifndef BB_FEATURE_GETUSERNAME_AND_HOMEDIR
595                 my_euid = geteuid();
596 #endif
597                 my_uid = getuid();
598                 my_gid = getgid();
599 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
600                 handlers_sets |= SET_ATEXIT;
601                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
602         }
603
604         if ((handlers_sets & SET_TERM_HANDLERS) == 0) {
605                 signal(SIGKILL, clean_up_and_die);
606                 signal(SIGINT, clean_up_and_die);
607                 signal(SIGQUIT, clean_up_and_die);
608                 signal(SIGTERM, clean_up_and_die);
609                 handlers_sets |= SET_TERM_HANDLERS;
610         }
611
612 }
613
614 #ifdef BB_FEATURE_SH_TAB_COMPLETION
615
616 static int is_execute(const struct stat *st)
617 {
618         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
619                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
620                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
621                 (st->st_mode & S_IXOTH)) return TRUE;
622         return FALSE;
623 }
624
625 #ifdef BB_FEATURE_SH_USERNAME_COMPLETION
626
627 static char **username_tab_completion(char *ud, int *num_matches)
628 {
629         struct passwd *entry;
630         int userlen;
631         char *temp;
632
633
634         ud++;                                           /* ~user/... to user/... */
635         userlen = strlen(ud);
636
637         if (num_matches == 0) {         /* "~/..." or "~user/..." */
638                 char *sav_ud = ud - 1;
639                 char *home = 0;
640
641                 if (*ud == '/') {               /* "~/..."     */
642                         home = home_pwd_buf;
643                 } else {
644                         /* "~user/..." */
645                         temp = strchr(ud, '/');
646                         *temp = 0;                      /* ~user\0 */
647                         entry = getpwnam(ud);
648                         *temp = '/';            /* restore ~user/... */
649                         ud = temp;
650                         if (entry)
651                                 home = entry->pw_dir;
652                 }
653                 if (home) {
654                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
655                                 char temp2[BUFSIZ];     /* argument size */
656
657                                 /* /home/user/... */
658                                 sprintf(temp2, "%s%s", home, ud);
659                                 strcpy(sav_ud, temp2);
660                         }
661                 }
662                 return 0;                               /* void, result save to argument :-) */
663         } else {
664                 /* "~[^/]*" */
665                 char **matches = (char **) NULL;
666                 int nm = 0;
667
668                 setpwent();
669
670                 while ((entry = getpwent()) != NULL) {
671                         /* Null usernames should result in all users as possible completions. */
672                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
673
674                                 temp = xmalloc(3 + strlen(entry->pw_name));
675                                 sprintf(temp, "~%s/", entry->pw_name);
676                                 matches = xrealloc(matches, (nm + 1) * sizeof(char *));
677
678                                 matches[nm++] = temp;
679                         }
680                 }
681
682                 endpwent();
683                 (*num_matches) = nm;
684                 return (matches);
685         }
686 }
687 #endif                                                  /* BB_FEATURE_SH_USERNAME_COMPLETION */
688
689 enum {
690         FIND_EXE_ONLY = 0,
691         FIND_DIR_ONLY = 1,
692         FIND_FILE_ONLY = 2,
693 };
694
695 static int path_parse(char ***p, int flags)
696 {
697         int npth;
698         char *tmp;
699         char *pth;
700
701         /* if not setenv PATH variable, to search cur dir "." */
702         if (flags != FIND_EXE_ONLY || (pth = getenv("PATH")) == 0 ||
703                 /* PATH=<empty> or PATH=:<empty> */
704                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
705                 return 1;
706         }
707
708         tmp = pth;
709         npth = 0;
710
711         for (;;) {
712                 npth++;                                 /* count words is + 1 count ':' */
713                 tmp = strchr(tmp, ':');
714                 if (tmp) {
715                         if (*++tmp == 0)
716                                 break;                  /* :<empty> */
717                 } else
718                         break;
719         }
720
721         *p = xmalloc(npth * sizeof(char *));
722
723         tmp = pth;
724         (*p)[0] = xstrdup(tmp);
725         npth = 1;                                       /* count words is + 1 count ':' */
726
727         for (;;) {
728                 tmp = strchr(tmp, ':');
729                 if (tmp) {
730                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
731                         if (*++tmp == 0)
732                                 break;                  /* :<empty> */
733                 } else
734                         break;
735                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
736         }
737
738         return npth;
739 }
740
741 static char *add_quote_for_spec_chars(char *found)
742 {
743         int l = 0;
744         char *s = xmalloc((strlen(found) + 1) * 2);
745
746         while (*found) {
747                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
748                         s[l++] = '\\';
749                 s[l++] = *found++;
750         }
751         s[l] = 0;
752         return s;
753 }
754
755 static char **exe_n_cwd_tab_completion(char *command, int *num_matches,
756                                                                            int type)
757 {
758
759         char **matches = 0;
760         DIR *dir;
761         struct dirent *next;
762         char dirbuf[BUFSIZ];
763         int nm = *num_matches;
764         struct stat st;
765         char *path1[1];
766         char **paths = path1;
767         int npaths;
768         int i;
769         char found[BUFSIZ + 4 + PATH_MAX];
770         char *pfind = strrchr(command, '/');
771
772         path1[0] = ".";
773
774         if (pfind == NULL) {
775                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
776                 npaths = path_parse(&paths, type);
777                 pfind = command;
778         } else {
779                 /* with dir */
780                 /* save for change */
781                 strcpy(dirbuf, command);
782                 /* set dir only */
783                 dirbuf[(pfind - command) + 1] = 0;
784 #ifdef BB_FEATURE_SH_USERNAME_COMPLETION
785                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
786                         username_tab_completion(dirbuf, 0);
787 #endif
788                 /* "strip" dirname in command */
789                 pfind++;
790
791                 paths[0] = dirbuf;
792                 npaths = 1;                             /* only 1 dir */
793         }
794
795         for (i = 0; i < npaths; i++) {
796
797                 dir = opendir(paths[i]);
798                 if (!dir)                               /* Don't print an error */
799                         continue;
800
801                 while ((next = readdir(dir)) != NULL) {
802                         const char *str_merge = "%s/%s";
803                         char *str_found = next->d_name;
804
805                         /* matched ? */
806                         if (strncmp(str_found, pfind, strlen(pfind)))
807                                 continue;
808                         /* not see .name without .match */
809                         if (*str_found == '.' && *pfind == 0) {
810                                 if (*paths[i] == '/' && paths[i][1] == 0
811                                         && str_found[1] == 0) str_found = "";   /* only "/" */
812                                 else
813                                         continue;
814                         }
815                         if (paths[i][strlen(paths[i]) - 1] == '/')
816                                 str_merge = "%s%s";
817                         sprintf(found, str_merge, paths[i], str_found);
818                         /* hmm, remover in progress? */
819                         if (stat(found, &st) < 0)
820                                 continue;
821                         /* find with dirs ? */
822                         if (paths[i] != dirbuf)
823                                 strcpy(found, next->d_name);    /* only name */
824                         if (S_ISDIR(st.st_mode)) {
825                                 /* name is directory      */
826                                 /* algorithmic only "/" ? */
827                                 if (*str_found)
828                                         strcat(found, "/");
829                                 str_found = add_quote_for_spec_chars(found);
830                         } else {
831                                 /* not put found file if search only dirs for cd */
832                                 if (type == FIND_DIR_ONLY)
833                                         continue;
834                                 str_found = add_quote_for_spec_chars(found);
835                                 if (type == FIND_FILE_ONLY ||
836                                         (type == FIND_EXE_ONLY && is_execute(&st) == TRUE))
837                                         strcat(str_found, " ");
838                         }
839                         /* Add it to the list */
840                         matches = xrealloc(matches, (nm + 1) * sizeof(char *));
841
842                         matches[nm++] = str_found;
843                 }
844                 closedir(dir);
845         }
846         if (paths != path1) {
847                 free(paths[0]);                 /* allocated memory only in first member */
848                 free(paths);
849         }
850         *num_matches = nm;
851         return (matches);
852 }
853
854 static int match_compare(const void *a, const void *b)
855 {
856         return strcmp(*(char **) a, *(char **) b);
857 }
858
859
860
861 #define QUOT    (UCHAR_MAX+1)
862
863 #define collapse_pos(is, in) { \
864         memcpy(int_buf+is, int_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); \
865         memcpy(pos_buf+is, pos_buf+in, (BUFSIZ+1-is-in)*sizeof(int)); }
866
867 static int find_match(char *matchBuf, int *len_with_quotes)
868 {
869         int i, j;
870         int command_mode;
871         int c, c2;
872         int int_buf[BUFSIZ + 1];
873         int pos_buf[BUFSIZ + 1];
874
875         /* set to integer dimension characters and own positions */
876         for (i = 0;; i++) {
877                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
878                 if (int_buf[i] == 0) {
879                         pos_buf[i] = -1;        /* indicator end line */
880                         break;
881                 } else
882                         pos_buf[i] = i;
883         }
884
885         /* mask \+symbol and convert '\t' to ' ' */
886         for (i = j = 0; matchBuf[i]; i++, j++)
887                 if (matchBuf[i] == '\\') {
888                         collapse_pos(j, j + 1);
889                         int_buf[j] |= QUOT;
890                         i++;
891 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
892                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
893                                 int_buf[j] = ' ' | QUOT;
894 #endif
895                 }
896 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
897                 else if (matchBuf[i] == '\t')
898                         int_buf[j] = ' ';
899 #endif
900
901         /* mask "symbols" or 'symbols' */
902         c2 = 0;
903         for (i = 0; int_buf[i]; i++) {
904                 c = int_buf[i];
905                 if (c == '\'' || c == '"') {
906                         if (c2 == 0)
907                                 c2 = c;
908                         else {
909                                 if (c == c2)
910                                         c2 = 0;
911                                 else
912                                         int_buf[i] |= QUOT;
913                         }
914                 } else if (c2 != 0 && c != '$')
915                         int_buf[i] |= QUOT;
916         }
917
918         /* skip commands with arguments if line have commands delimiters */
919         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
920         for (i = 0; int_buf[i]; i++) {
921                 c = int_buf[i];
922                 c2 = int_buf[i + 1];
923                 j = i ? int_buf[i - 1] : -1;
924                 command_mode = 0;
925                 if (c == ';' || c == '&' || c == '|') {
926                         command_mode = 1 + (c == c2);
927                         if (c == '&') {
928                                 if (j == '>' || j == '<')
929                                         command_mode = 0;
930                         } else if (c == '|' && j == '>')
931                                 command_mode = 0;
932                 }
933                 if (command_mode) {
934                         collapse_pos(0, i + command_mode);
935                         i = -1;                         /* hack incremet */
936                 }
937         }
938         /* collapse `command...` */
939         for (i = 0; int_buf[i]; i++)
940                 if (int_buf[i] == '`') {
941                         for (j = i + 1; int_buf[j]; j++)
942                                 if (int_buf[j] == '`') {
943                                         collapse_pos(i, j + 1);
944                                         j = 0;
945                                         break;
946                                 }
947                         if (j) {
948                                 /* not found close ` - command mode, collapse all previous */
949                                 collapse_pos(0, i + 1);
950                                 break;
951                         } else
952                                 i--;                    /* hack incremet */
953                 }
954
955         /* collapse (command...(command...)...) or {command...{command...}...} */
956         c = 0;                                          /* "recursive" level */
957         c2 = 0;
958         for (i = 0; int_buf[i]; i++)
959                 if (int_buf[i] == '(' || int_buf[i] == '{') {
960                         if (int_buf[i] == '(')
961                                 c++;
962                         else
963                                 c2++;
964                         collapse_pos(0, i + 1);
965                         i = -1;                         /* hack incremet */
966                 }
967         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
968                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
969                         if (int_buf[i] == ')')
970                                 c--;
971                         else
972                                 c2--;
973                         collapse_pos(0, i + 1);
974                         i = -1;                         /* hack incremet */
975                 }
976
977         /* skip first not quote space */
978         for (i = 0; int_buf[i]; i++)
979                 if (int_buf[i] != ' ')
980                         break;
981         if (i)
982                 collapse_pos(0, i);
983
984         /* set find mode for completion */
985         command_mode = FIND_EXE_ONLY;
986         for (i = 0; int_buf[i]; i++)
987                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
988                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
989                                 && strncmp(&matchBuf[pos_buf[0]], "cd", 2) == 0)
990                                 command_mode = FIND_DIR_ONLY;
991                         else {
992                                 command_mode = FIND_FILE_ONLY;
993                                 break;
994                         }
995                 }
996         /* "strlen" */
997         for (i = 0; int_buf[i]; i++);
998         /* find last word */
999         for (--i; i >= 0; i--) {
1000                 c = int_buf[i];
1001                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
1002                         collapse_pos(0, i + 1);
1003                         break;
1004                 }
1005         }
1006         /* skip first not quoted '\'' or '"' */
1007         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
1008         /* collapse quote or unquote // or /~ */
1009         while ((int_buf[i] & ~QUOT) == '/' && (
1010                                                                                    (int_buf[i + 1] & ~QUOT) == '/'
1011                                                                                    || (int_buf[i + 1] & ~QUOT) ==
1012                                                                                    '~')) i++;
1013         if (i)
1014                 collapse_pos(0, i);
1015
1016         /* set only match and destroy quotes */
1017         j = 0;
1018         for (i = 0; pos_buf[i] >= 0; i++) {
1019                 matchBuf[i] = matchBuf[pos_buf[i]];
1020                 j = pos_buf[i] + 1;
1021         }
1022         matchBuf[i] = 0;
1023         /* old lenght matchBuf with quotes symbols */
1024         *len_with_quotes = j ? j - pos_buf[0] : 0;
1025
1026         return command_mode;
1027 }
1028
1029
1030 static void input_tab(int *lastWasTab)
1031 {
1032         /* Do TAB completion */
1033         static int num_matches;
1034         static char **matches;
1035
1036         if (lastWasTab == 0) {          /* free all memory */
1037                 if (matches) {
1038                         while (num_matches > 0)
1039                                 free(matches[--num_matches]);
1040                         free(matches);
1041                         matches = (char **) NULL;
1042                 }
1043                 return;
1044         }
1045         if (*lastWasTab == FALSE) {
1046
1047                 char *tmp;
1048                 int len_found;
1049                 char matchBuf[BUFSIZ];
1050                 int find_type;
1051                 int recalc_pos;
1052
1053                 *lastWasTab = TRUE;             /* flop trigger */
1054
1055                 /* Make a local copy of the string -- up
1056                  * to the position of the cursor */
1057                 tmp = strncpy(matchBuf, command_ps, cursor);
1058                 tmp[cursor] = 0;
1059
1060                 find_type = find_match(matchBuf, &recalc_pos);
1061
1062                 /* Free up any memory already allocated */
1063                 input_tab(0);
1064
1065 #ifdef BB_FEATURE_SH_USERNAME_COMPLETION
1066                 /* If the word starts with `~' and there is no slash in the word,
1067                  * then try completing this word as a username. */
1068
1069                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1070                         matches = username_tab_completion(matchBuf, &num_matches);
1071 #endif
1072                 /* Try to match any executable in our path and everything
1073                  * in the current working directory that matches.  */
1074                 if (!matches)
1075                         matches =
1076                                 exe_n_cwd_tab_completion(matchBuf, &num_matches,
1077                                                                                  find_type);
1078
1079                 /* Did we find exactly one match? */
1080                 if (!matches || num_matches > 1) {
1081                         char *tmp1;
1082
1083                         beep();
1084                         if (!matches)
1085                                 return;                 /* not found */
1086                         /* sort */
1087                         qsort(matches, num_matches, sizeof(char *), match_compare);
1088
1089                         /* find minimal match */
1090                         tmp = xstrdup(matches[0]);
1091                         for (tmp1 = tmp; *tmp1; tmp1++)
1092                                 for (len_found = 1; len_found < num_matches; len_found++)
1093                                         if (matches[len_found][(tmp1 - tmp)] != *tmp1) {
1094                                                 *tmp1 = 0;
1095                                                 break;
1096                                         }
1097                         if (*tmp == 0) {        /* have unique */
1098                                 free(tmp);
1099                                 return;
1100                         }
1101                 } else {                                /* one match */
1102                         tmp = matches[0];
1103                         /* for next completion current found */
1104                         *lastWasTab = FALSE;
1105                 }
1106
1107                 len_found = strlen(tmp);
1108                 /* have space to placed match? */
1109                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1110
1111                         /* before word for match   */
1112                         command_ps[cursor - recalc_pos] = 0;
1113                         /* save   tail line        */
1114                         strcpy(matchBuf, command_ps + cursor);
1115                         /* add    match            */
1116                         strcat(command_ps, tmp);
1117                         /* add    tail             */
1118                         strcat(command_ps, matchBuf);
1119                         /* back to begin word for match    */
1120                         input_backward(recalc_pos);
1121                         /* new pos                         */
1122                         recalc_pos = cursor + len_found;
1123                         /* new len                         */
1124                         len = strlen(command_ps);
1125                         /* write out the matched command   */
1126                         input_end();
1127                         input_backward(cursor - recalc_pos);
1128                 }
1129                 if (tmp != matches[0])
1130                         free(tmp);
1131         } else {
1132                 /* Ok -- the last char was a TAB.  Since they
1133                  * just hit TAB again, print a list of all the
1134                  * available choices... */
1135                 if (matches && num_matches > 0) {
1136                         int i, col, l;
1137                         int sav_cursor = cursor;        /* change goto_new_line() */
1138
1139                         /* Go to the next line */
1140                         goto_new_line();
1141                         for (i = 0, col = 0; i < num_matches; i++) {
1142                                 l = strlen(matches[i]);
1143                                 if (l < 14)
1144                                         l = 14;
1145                                 printf("%-14s  ", matches[i]);
1146                                 if ((l += 2) > 16)
1147                                         while (l % 16) {
1148                                                 putchar(' ');
1149                                                 l++;
1150                                         }
1151                                 col += l;
1152                                 col -= (col / cmdedit_termw) * cmdedit_termw;
1153                                 if (col > 60 && matches[i + 1] != NULL) {
1154                                         putchar('\n');
1155                                         col = 0;
1156                                 }
1157                         }
1158                         /* Go to the next line and rewrite */
1159                         putchar('\n');
1160                         redraw(0, len - sav_cursor);
1161                 }
1162         }
1163 }
1164 #endif                                                  /* BB_FEATURE_SH_TAB_COMPLETION */
1165
1166 static void get_previous_history(struct history **hp, struct history *p)
1167 {
1168         if ((*hp)->s)
1169                 free((*hp)->s);
1170         (*hp)->s = xstrdup(command_ps);
1171         *hp = p;
1172 }
1173
1174 static inline void get_next_history(struct history **hp)
1175 {
1176         get_previous_history(hp, (*hp)->n);
1177 }
1178
1179 enum {
1180         ESC = 27,
1181         DEL = 127,
1182 };
1183
1184
1185 /*
1186  * This function is used to grab a character buffer
1187  * from the input file descriptor and allows you to
1188  * a string with full command editing (sortof like
1189  * a mini readline).
1190  *
1191  * The following standard commands are not implemented:
1192  * ESC-b -- Move back one word
1193  * ESC-f -- Move forward one word
1194  * ESC-d -- Delete back one word
1195  * ESC-h -- Delete forward one word
1196  * CTL-t -- Transpose two characters
1197  *
1198  * Furthermore, the "vi" command editing keys are not implemented.
1199  *
1200  */
1201 extern void cmdedit_read_input(char *prompt, char command[BUFSIZ])
1202 {
1203
1204         int inputFd = fileno(stdin);
1205
1206         int break_out = 0;
1207         int lastWasTab = FALSE;
1208         char c = 0;
1209         struct history *hp = his_end;
1210
1211         /* prepare before init handlers */
1212         cmdedit_y = 0;                          /* quasireal y, not true work if line > xt*yt */
1213         len = 0;
1214         command_ps = command;
1215
1216         if (new_settings.c_cc[VMIN] == 0) {     /* first call */
1217
1218                 getTermSettings(inputFd, (void *) &initial_settings);
1219                 memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1220
1221                 new_settings.c_cc[VMIN] = 1;
1222                 new_settings.c_cc[VTIME] = 0;
1223                 new_settings.c_cc[VINTR] = _POSIX_VDISABLE;     /* Turn off CTRL-C, so we can trap it */
1224                 new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1225                 new_settings.c_lflag &= ~(ECHO | ECHOCTL | ECHONL);     /* Turn off echoing */
1226         }
1227
1228         command[0] = 0;
1229
1230         setTermSettings(inputFd, (void *) &new_settings);
1231         handlers_sets |= SET_RESET_TERM;
1232
1233         /* Print out the command prompt */
1234         parse_prompt(prompt);
1235         /* Now initialize things */
1236         cmdedit_init();
1237
1238         while (1) {
1239
1240                 fflush(stdout);                 /* buffered out to fast */
1241
1242                 if (read(inputFd, &c, 1) < 1)
1243                         return;
1244
1245                 switch (c) {
1246                 case '\n':
1247                 case '\r':
1248                         /* Enter */
1249                         goto_new_line();
1250                         break_out = 1;
1251                         break;
1252                 case 1:
1253                         /* Control-a -- Beginning of line */
1254                         input_backward(cursor);
1255                         break;
1256                 case 2:
1257                         /* Control-b -- Move back one character */
1258                         input_backward(1);
1259                         break;
1260                 case 3:
1261                         /* Control-c -- stop gathering input */
1262
1263                         /* Link into lash to reset context to 0 on ^C and such */
1264                         shell_context = 0;
1265
1266                         /* Go to the next line */
1267                         goto_new_line();
1268                         command[0] = 0;
1269
1270                         return;
1271                 case 4:
1272                         /* Control-d -- Delete one character, or exit
1273                          * if the len=0 and no chars to delete */
1274                         if (len == 0) {
1275                                 printf("exit");
1276                                 clean_up_and_die(0);
1277                         } else {
1278                                 input_delete();
1279                         }
1280                         break;
1281                 case 5:
1282                         /* Control-e -- End of line */
1283                         input_end();
1284                         break;
1285                 case 6:
1286                         /* Control-f -- Move forward one character */
1287                         input_forward();
1288                         break;
1289                 case '\b':
1290                 case DEL:
1291                         /* Control-h and DEL */
1292                         input_backspace();
1293                         break;
1294                 case '\t':
1295 #ifdef BB_FEATURE_SH_TAB_COMPLETION
1296                         input_tab(&lastWasTab);
1297 #endif
1298                         break;
1299                 case 14:
1300                         /* Control-n -- Get next command in history */
1301                         if (hp && hp->n && hp->n->s) {
1302                                 get_next_history(&hp);
1303                                 goto rewrite_line;
1304                         } else {
1305                                 beep();
1306                         }
1307                         break;
1308                 case 16:
1309                         /* Control-p -- Get previous command from history */
1310                         if (hp && hp->p) {
1311                                 get_previous_history(&hp, hp->p);
1312                                 goto rewrite_line;
1313                         } else {
1314                                 beep();
1315                         }
1316                         break;
1317                 case 21:
1318                         /* Control-U -- Clear line before cursor */
1319                         if (cursor) {
1320                                 strcpy(command, command + cursor);
1321                                 redraw(cmdedit_y, len -= cursor);
1322                         }
1323                         break;
1324
1325                 case ESC:{
1326                         /* escape sequence follows */
1327                         if (read(inputFd, &c, 1) < 1)
1328                                 return;
1329                         /* different vt100 emulations */
1330                         if (c == '[' || c == 'O') {
1331                                 if (read(inputFd, &c, 1) < 1)
1332                                         return;
1333                         }
1334                         switch (c) {
1335 #ifdef BB_FEATURE_SH_TAB_COMPLETION
1336                         case '\t':                      /* Alt-Tab */
1337
1338                                 input_tab(&lastWasTab);
1339                                 break;
1340 #endif
1341                         case 'A':
1342                                 /* Up Arrow -- Get previous command from history */
1343                                 if (hp && hp->p) {
1344                                         get_previous_history(&hp, hp->p);
1345                                         goto rewrite_line;
1346                                 } else {
1347                                         beep();
1348                                 }
1349                                 break;
1350                         case 'B':
1351                                 /* Down Arrow -- Get next command in history */
1352                                 if (hp && hp->n && hp->n->s) {
1353                                         get_next_history(&hp);
1354                                         goto rewrite_line;
1355                                 } else {
1356                                         beep();
1357                                 }
1358                                 break;
1359
1360                                 /* Rewrite the line with the selected history item */
1361                           rewrite_line:
1362                                 /* change command */
1363                                 len = strlen(strcpy(command, hp->s));
1364                                 /* redraw and go to end line */
1365                                 redraw(cmdedit_y, 0);
1366                                 break;
1367                         case 'C':
1368                                 /* Right Arrow -- Move forward one character */
1369                                 input_forward();
1370                                 break;
1371                         case 'D':
1372                                 /* Left Arrow -- Move back one character */
1373                                 input_backward(1);
1374                                 break;
1375                         case '3':
1376                                 /* Delete */
1377                                 input_delete();
1378                                 break;
1379                         case '1':
1380                         case 'H':
1381                                 /* Home (Ctrl-A) */
1382                                 input_backward(cursor);
1383                                 break;
1384                         case '4':
1385                         case 'F':
1386                                 /* End (Ctrl-E) */
1387                                 input_end();
1388                                 break;
1389                         default:
1390                                 if (!(c >= '1' && c <= '9'))
1391                                         c = 0;
1392                                 beep();
1393                         }
1394                         if (c >= '1' && c <= '9')
1395                                 do
1396                                         if (read(inputFd, &c, 1) < 1)
1397                                                 return;
1398                                 while (c != '~');
1399                         break;
1400                 }
1401
1402                 default:                                /* If it's regular input, do the normal thing */
1403 #ifdef BB_FEATURE_NONPRINTABLE_INVERSE_PUT
1404                         /* Control-V -- Add non-printable symbol */
1405                         if (c == 22) {
1406                                 if (read(inputFd, &c, 1) < 1)
1407                                         return;
1408                                 if (c == 0) {
1409                                         beep();
1410                                         break;
1411                                 }
1412                         } else
1413 #endif
1414                         if (!isprint(c))        /* Skip non-printable characters */
1415                                 break;
1416
1417                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
1418                                 break;
1419
1420                         len++;
1421
1422                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
1423                                 *(command + cursor) = c;
1424                                 *(command + cursor + 1) = 0;
1425                                 cmdedit_set_out_char(0);
1426                         } else {                        /* Insert otherwise */
1427                                 int sc = cursor;
1428
1429                                 memmove(command + sc + 1, command + sc, len - sc);
1430                                 *(command + sc) = c;
1431                                 sc++;
1432                                 /* rewrite from cursor */
1433                                 input_end();
1434                                 /* to prev x pos + 1 */
1435                                 input_backward(cursor - sc);
1436                         }
1437
1438                         break;
1439                 }
1440                 if (break_out)                  /* Enter is the command terminator, no more input. */
1441                         break;
1442
1443                 if (c != '\t')
1444                         lastWasTab = FALSE;
1445         }
1446
1447         setTermSettings(inputFd, (void *) &initial_settings);
1448         handlers_sets &= ~SET_RESET_TERM;
1449
1450         /* Handle command history log */
1451         if (len) {                                      /* no put empty line */
1452
1453                 struct history *h = his_end;
1454                 char *ss;
1455
1456                 ss = xstrdup(command);  /* duplicate */
1457
1458                 if (h == 0) {
1459                         /* No previous history -- this memory is never freed */
1460                         h = his_front = xmalloc(sizeof(struct history));
1461                         h->n = xmalloc(sizeof(struct history));
1462
1463                         h->p = NULL;
1464                         h->s = ss;
1465                         h->n->p = h;
1466                         h->n->n = NULL;
1467                         h->n->s = NULL;
1468                         his_end = h->n;
1469                         history_counter++;
1470                 } else {
1471                         /* Add a new history command -- this memory is never freed */
1472                         h->n = xmalloc(sizeof(struct history));
1473
1474                         h->n->p = h;
1475                         h->n->n = NULL;
1476                         h->n->s = NULL;
1477                         h->s = ss;
1478                         his_end = h->n;
1479
1480                         /* After max history, remove the oldest command */
1481                         if (history_counter >= MAX_HISTORY) {
1482
1483                                 struct history *p = his_front->n;
1484
1485                                 p->p = NULL;
1486                                 free(his_front->s);
1487                                 free(his_front);
1488                                 his_front = p;
1489                         } else {
1490                                 history_counter++;
1491                         }
1492                 }
1493 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1494                 num_ok_lines++;
1495 #endif
1496         }
1497         command[len++] = '\n';          /* set '\n' */
1498         command[len] = 0;
1499 #if defined(BB_FEATURE_CLEAN_UP) && defined(BB_FEATURE_SH_TAB_COMPLETION)
1500         input_tab(0);                           /* strong free */
1501 #endif
1502 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1503         free(cmdedit_prompt);
1504 #endif
1505         return;
1506 }
1507
1508
1509 /* Undo the effects of cmdedit_init(). */
1510 extern void cmdedit_terminate(void)
1511 {
1512         cmdedit_reset_term();
1513         if ((handlers_sets & SET_TERM_HANDLERS) != 0) {
1514                 signal(SIGKILL, SIG_DFL);
1515                 signal(SIGINT, SIG_DFL);
1516                 signal(SIGQUIT, SIG_DFL);
1517                 signal(SIGTERM, SIG_DFL);
1518                 signal(SIGWINCH, SIG_DFL);
1519                 handlers_sets &= ~SET_TERM_HANDLERS;
1520         }
1521 }
1522
1523 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */
1524
1525
1526 #ifdef TEST
1527
1528 unsigned int shell_context;
1529
1530 int main(int argc, char **argv)
1531 {
1532         char buff[BUFSIZ];
1533         char *prompt =
1534 #if defined(BB_FEATURE_BASH_STYLE_PROMT)
1535                 "\\[\\033[32;1m\\]\\u@\\[\\033[33;1m\\]\\h:\
1536 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1537 \\!\\[\\033[36;1m\\]\\$ \\[\\033[0m\\]";
1538 #else
1539                 "% ";
1540 #endif
1541
1542         shell_context = 1;
1543         do {
1544                 cmdedit_read_input(prompt, buff);
1545                 printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1546         } while (shell_context);
1547         printf("*** cmdedit_read_input() detect ^C\n");
1548         return 0;
1549 }
1550
1551 #endif                                                  /* TEST */