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