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