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