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