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