Robert P. Day removed 8 gazillion occurrences of "extern" on function
[oweals/busybox.git] / shell / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editing.
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 #include "../shell/cmdedit.h"
47
48
49 #ifdef CONFIG_LOCALE_SUPPORT
50 #define Isprint(c) isprint((c))
51 #else
52 #define Isprint(c) ( (c) >= ' ' && (c) != ((unsigned char)'\233') )
53 #endif
54
55 #ifdef TEST
56
57 /* pretect redefined for test */
58 #undef CONFIG_FEATURE_COMMAND_EDITING
59 #undef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
60 #undef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
61 #undef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
62 #undef CONFIG_FEATURE_CLEAN_UP
63
64 #define CONFIG_FEATURE_COMMAND_EDITING
65 #define CONFIG_FEATURE_COMMAND_TAB_COMPLETION
66 #define CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
67 #define CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
68 #define CONFIG_FEATURE_CLEAN_UP
69
70 #endif  /* TEST */
71
72 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
73 #include <dirent.h>
74 #include <sys/stat.h>
75 #endif
76
77 #ifdef CONFIG_FEATURE_COMMAND_EDITING
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 #include "pwd_.h"
85 #endif  /* advanced FEATURES */
86
87
88 /* Maximum length of the linked list for the command line history */
89 #ifndef CONFIG_FEATURE_COMMAND_HISTORY
90 #define MAX_HISTORY   15
91 #else
92 #define MAX_HISTORY   CONFIG_FEATURE_COMMAND_HISTORY
93 #endif
94
95 #if MAX_HISTORY < 1
96 #warning cmdedit: You set MAX_HISTORY < 1. The history algorithm switched off.
97 #else
98 static char *history[MAX_HISTORY+1]; /* history + current */
99 /* saved history lines */
100 static int n_history;
101 /* current pointer to history line */
102 static int cur_history;
103 #endif
104
105 #include <termios.h>
106 #define setTermSettings(fd,argp) tcsetattr(fd,TCSANOW,argp)
107 #define getTermSettings(fd,argp) tcgetattr(fd, argp);
108
109 /* Current termio and the previous termio before starting sh */
110 static struct termios initial_settings, new_settings;
111
112
113 static
114 volatile int cmdedit_termw = 80;        /* actual terminal width */
115 static
116 volatile int handlers_sets = 0; /* Set next bites: */
117
118 enum {
119         SET_ATEXIT = 1,         /* when atexit() has been called
120                                    and get euid,uid,gid to fast compare */
121         SET_WCHG_HANDLERS = 2,  /* winchg signal handler */
122         SET_RESET_TERM = 4,     /* if the terminal needs to be reset upon exit */
123 };
124
125
126 static int cmdedit_x;           /* real x terminal position */
127 static int cmdedit_y;           /* pseudoreal y terminal position */
128 static int cmdedit_prmt_len;    /* lenght prompt without colores string */
129
130 static int cursor;              /* required global for signal handler */
131 static int len;                 /* --- "" - - "" - -"- --""-- --""--- */
132 static char *command_ps;        /* --- "" - - "" - -"- --""-- --""--- */
133 static
134 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
135         const
136 #endif
137 char *cmdedit_prompt;           /* --- "" - - "" - -"- --""-- --""--- */
138
139 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
140 static char *user_buf = "";
141 static char *home_pwd_buf = "";
142 static int my_euid;
143 #endif
144
145 #ifdef CONFIG_FEATURE_SH_FANCY_PROMPT
146 static char *hostname_buf;
147 static int num_ok_lines = 1;
148 #endif
149
150
151 #ifdef  CONFIG_FEATURE_COMMAND_TAB_COMPLETION
152
153 #ifndef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
154 static int my_euid;
155 #endif
156
157 static int my_uid;
158 static int my_gid;
159
160 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
161
162 static void cmdedit_setwidth(int w, int redraw_flg);
163
164 static void win_changed(int nsig)
165 {
166         static sighandler_t previous_SIGWINCH_handler;  /* for reset */
167
168         /*   emulate      || signal call */
169         if (nsig == -SIGWINCH || nsig == SIGWINCH) {
170                 int width = 0;
171                 get_terminal_width_height(0, &width, NULL);
172                 cmdedit_setwidth(width, nsig == SIGWINCH);
173         }
174         /* Unix not all standart in recall signal */
175
176         if (nsig == -SIGWINCH)          /* save previous handler   */
177                 previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
178         else if (nsig == SIGWINCH)      /* signaled called handler */
179                 signal(SIGWINCH, win_changed);  /* set for next call       */
180         else                                            /* nsig == 0 */
181                 /* set previous handler    */
182                 signal(SIGWINCH, previous_SIGWINCH_handler);    /* reset    */
183 }
184
185 static void cmdedit_reset_term(void)
186 {
187         if ((handlers_sets & SET_RESET_TERM) != 0) {
188 /* sparc and other have broken termios support: use old termio handling. */
189                 setTermSettings(STDIN_FILENO, (void *) &initial_settings);
190                 handlers_sets &= ~SET_RESET_TERM;
191         }
192         if ((handlers_sets & SET_WCHG_HANDLERS) != 0) {
193                 /* reset SIGWINCH handler to previous (default) */
194                 win_changed(0);
195                 handlers_sets &= ~SET_WCHG_HANDLERS;
196         }
197         fflush(stdout);
198 }
199
200
201 /* special for recount position for scroll and remove terminal margin effect */
202 static void cmdedit_set_out_char(int next_char)
203 {
204
205         int c = (int)((unsigned char) command_ps[cursor]);
206
207         if (c == 0)
208                 c = ' ';        /* destroy end char? */
209 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
210         if (!Isprint(c)) {      /* Inverse put non-printable characters */
211                 if (c >= 128)
212                         c -= 128;
213                 if (c < ' ')
214                         c += '@';
215                 if (c == 127)
216                         c = '?';
217                 printf("\033[7m%c\033[0m", c);
218         } else
219 #endif
220                 putchar(c);
221         if (++cmdedit_x >= cmdedit_termw) {
222                 /* terminal is scrolled down */
223                 cmdedit_y++;
224                 cmdedit_x = 0;
225
226                 if (!next_char)
227                         next_char = ' ';
228                 /* destroy "(auto)margin" */
229                 putchar(next_char);
230                 putchar('\b');
231         }
232         cursor++;
233 }
234
235 /* Move to end line. Bonus: rewrite line from cursor */
236 static void input_end(void)
237 {
238         while (cursor < len)
239                 cmdedit_set_out_char(0);
240 }
241
242 /* Go to the next line */
243 static void goto_new_line(void)
244 {
245         input_end();
246         if (cmdedit_x)
247                 putchar('\n');
248 }
249
250
251 static inline void out1str(const char *s)
252 {
253         if ( s )
254                 fputs(s, stdout);
255 }
256
257 static inline void beep(void)
258 {
259         putchar('\007');
260 }
261
262 /* Move back one character */
263 /* special for slow terminal */
264 static void input_backward(int num)
265 {
266         if (num > cursor)
267                 num = cursor;
268         cursor -= num;          /* new cursor (in command, not terminal) */
269
270         if (cmdedit_x >= num) {         /* no to up line */
271                 cmdedit_x -= num;
272                 if (num < 4)
273                         while (num-- > 0)
274                                 putchar('\b');
275
276                 else
277                         printf("\033[%dD", num);
278         } else {
279                 int count_y;
280
281                 if (cmdedit_x) {
282                         putchar('\r');          /* back to first terminal pos.  */
283                         num -= cmdedit_x;       /* set previous backward        */
284                 }
285                 count_y = 1 + num / cmdedit_termw;
286                 printf("\033[%dA", count_y);
287                 cmdedit_y -= count_y;
288                 /*  require  forward  after  uping   */
289                 cmdedit_x = cmdedit_termw * count_y - num;
290                 printf("\033[%dC", cmdedit_x);  /* set term cursor   */
291         }
292 }
293
294 static void put_prompt(void)
295 {
296         out1str(cmdedit_prompt);
297         cmdedit_x = cmdedit_prmt_len;   /* count real x terminal position */
298         cursor = 0;
299         cmdedit_y = 0;                  /* new quasireal y */
300 }
301
302 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
303 static void parse_prompt(const char *prmt_ptr)
304 {
305         cmdedit_prompt = prmt_ptr;
306         cmdedit_prmt_len = strlen(prmt_ptr);
307         put_prompt();
308 }
309 #else
310 static void parse_prompt(const char *prmt_ptr)
311 {
312         int prmt_len = 0;
313         size_t cur_prmt_len = 0;
314         char  flg_not_length = '[';
315         char *prmt_mem_ptr = xcalloc(1, 1);
316         char *pwd_buf = xgetcwd(0);
317         char  buf2[PATH_MAX + 1];
318         char  buf[2];
319         char  c;
320         char *pbuf;
321
322         if (!pwd_buf) {
323                 pwd_buf=(char *)bb_msg_unknown;
324         }
325
326         while (*prmt_ptr) {
327                 pbuf    = buf;
328                 pbuf[1] = 0;
329                 c = *prmt_ptr++;
330                 if (c == '\\') {
331                         const char *cp = prmt_ptr;
332                         int l;
333
334                         c = bb_process_escape_sequence(&prmt_ptr);
335                         if(prmt_ptr==cp) {
336                           if (*cp == 0)
337                                 break;
338                           c = *prmt_ptr++;
339                           switch (c) {
340 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
341                           case 'u':
342                                 pbuf = user_buf;
343                                 break;
344 #endif
345                           case 'h':
346                                 pbuf = hostname_buf;
347                                 if (pbuf == 0) {
348                                         pbuf = xcalloc(256, 1);
349                                         if (gethostname(pbuf, 255) < 0) {
350                                                 strcpy(pbuf, "?");
351                                         } else {
352                                                 char *s = strchr(pbuf, '.');
353
354                                                 if (s)
355                                                         *s = 0;
356                                         }
357                                         hostname_buf = pbuf;
358                                 }
359                                 break;
360                           case '$':
361                                 c = my_euid == 0 ? '#' : '$';
362                                 break;
363 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
364                           case 'w':
365                                 pbuf = pwd_buf;
366                                 l = strlen(home_pwd_buf);
367                                 if (home_pwd_buf[0] != 0 &&
368                                     strncmp(home_pwd_buf, pbuf, l) == 0 &&
369                                     (pbuf[l]=='/' || pbuf[l]=='\0') &&
370                                     strlen(pwd_buf+l)<PATH_MAX) {
371                                         pbuf = buf2;
372                                         *pbuf = '~';
373                                         strcpy(pbuf+1, pwd_buf+l);
374                                         }
375                                 break;
376 #endif
377                           case 'W':
378                                 pbuf = pwd_buf;
379                                 cp = strrchr(pbuf,'/');
380                                 if ( (cp != NULL) && (cp != pbuf) )
381                                         pbuf += (cp-pbuf)+1;
382                                 break;
383                           case '!':
384                                 snprintf(pbuf = buf2, sizeof(buf2), "%d", num_ok_lines);
385                                 break;
386                           case 'e': case 'E':     /* \e \E = \033 */
387                                 c = '\033';
388                                 break;
389                           case 'x': case 'X':
390                                 for (l = 0; l < 3;) {
391                                         int h;
392                                         buf2[l++] = *prmt_ptr;
393                                         buf2[l] = 0;
394                                         h = strtol(buf2, &pbuf, 16);
395                                         if (h > UCHAR_MAX || (pbuf - buf2) < l) {
396                                                 l--;
397                                                 break;
398                                         }
399                                         prmt_ptr++;
400                                 }
401                                 buf2[l] = 0;
402                                 c = (char)strtol(buf2, 0, 16);
403                                 if(c==0)
404                                         c = '?';
405                                 pbuf = buf;
406                                 break;
407                           case '[': case ']':
408                                 if (c == flg_not_length) {
409                                         flg_not_length = flg_not_length == '[' ? ']' : '[';
410                                         continue;
411                                 }
412                                 break;
413                           }
414                         }
415                 }
416                 if(pbuf == buf)
417                         *pbuf = c;
418                 cur_prmt_len = strlen(pbuf);
419                 prmt_len += cur_prmt_len;
420                 if (flg_not_length != ']')
421                         cmdedit_prmt_len += cur_prmt_len;
422                 prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
423         }
424         if(pwd_buf!=(char *)bb_msg_unknown)
425                 free(pwd_buf);
426         cmdedit_prompt = prmt_mem_ptr;
427         put_prompt();
428 }
429 #endif
430
431
432 /* draw prompt, editor line, and clear tail */
433 static void redraw(int y, int back_cursor)
434 {
435         if (y > 0)                              /* up to start y */
436                 printf("\033[%dA", y);
437         putchar('\r');
438         put_prompt();
439         input_end();                            /* rewrite */
440         printf("\033[J");                       /* destroy tail after cursor */
441         input_backward(back_cursor);
442 }
443
444 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
445 static char delbuf[BUFSIZ];  /* a place to store deleted characters */
446 static char *delp = delbuf;
447 static int newdelflag;      /* whether delbuf should be reused yet */
448 #endif
449
450 /* Delete the char in front of the cursor, optionally saving it
451  * for later putback */
452 static void input_delete(int save)
453 {
454         int j = cursor;
455
456         if (j == len)
457                 return;
458
459 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
460         if (save) {
461                 if (newdelflag) {
462                         delp = delbuf;
463                         newdelflag = 0;
464                 }
465                 if (delp - delbuf < BUFSIZ)
466                         *delp++ = command_ps[j];
467         }
468 #endif
469
470         strcpy(command_ps + j, command_ps + j + 1);
471         len--;
472         input_end();                    /* rewrite new line */
473         cmdedit_set_out_char(0);        /* destroy end char */
474         input_backward(cursor - j);     /* back to old pos cursor */
475 }
476
477 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
478 static void put(void)
479 {
480         int ocursor, j = delp - delbuf;
481         if (j == 0)
482                 return;
483         ocursor = cursor;
484         /* open hole and then fill it */
485         memmove(command_ps + cursor + j, command_ps + cursor, len - cursor + 1);
486         strncpy(command_ps + cursor, delbuf, j);
487         len += j;
488         input_end();                    /* rewrite new line */
489         input_backward(cursor-ocursor-j+1); /* at end of new text */
490 }
491 #endif
492
493 /* Delete the char in back of the cursor */
494 static void input_backspace(void)
495 {
496         if (cursor > 0) {
497                 input_backward(1);
498                 input_delete(0);
499         }
500 }
501
502
503 /* Move forward one character */
504 static void input_forward(void)
505 {
506         if (cursor < len)
507                 cmdedit_set_out_char(command_ps[cursor + 1]);
508 }
509
510 static void cmdedit_setwidth(int w, int redraw_flg)
511 {
512         cmdedit_termw = cmdedit_prmt_len + 2;
513         if (w <= cmdedit_termw) {
514                 cmdedit_termw = cmdedit_termw % w;
515         }
516         if (w > cmdedit_termw) {
517                 cmdedit_termw = w;
518
519                 if (redraw_flg) {
520                         /* new y for current cursor */
521                         int new_y = (cursor + cmdedit_prmt_len) / w;
522
523                         /* redraw */
524                         redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), len - cursor);
525                         fflush(stdout);
526                 }
527         }
528 }
529
530 static void cmdedit_init(void)
531 {
532         cmdedit_prmt_len = 0;
533         if ((handlers_sets & SET_WCHG_HANDLERS) == 0) {
534                 /* emulate usage handler to set handler and call yours work */
535                 win_changed(-SIGWINCH);
536                 handlers_sets |= SET_WCHG_HANDLERS;
537         }
538
539         if ((handlers_sets & SET_ATEXIT) == 0) {
540 #ifdef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
541                 struct passwd *entry;
542
543                 my_euid = geteuid();
544                 entry = getpwuid(my_euid);
545                 if (entry) {
546                         user_buf = bb_xstrdup(entry->pw_name);
547                         home_pwd_buf = bb_xstrdup(entry->pw_dir);
548                 }
549 #endif
550
551 #ifdef  CONFIG_FEATURE_COMMAND_TAB_COMPLETION
552
553 #ifndef CONFIG_FEATURE_GETUSERNAME_AND_HOMEDIR
554                 my_euid = geteuid();
555 #endif
556                 my_uid = getuid();
557                 my_gid = getgid();
558 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
559                 handlers_sets |= SET_ATEXIT;
560                 atexit(cmdedit_reset_term);     /* be sure to do this only once */
561         }
562 }
563
564 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
565
566 static char **matches;
567 static int num_matches;
568 static char *add_char_to_match;
569
570 static void add_match(char *matched, int add_char)
571 {
572         int nm = num_matches;
573         int nm1 = nm + 1;
574
575         matches = xrealloc(matches, nm1 * sizeof(char *));
576         add_char_to_match = xrealloc(add_char_to_match, nm1);
577         matches[nm] = matched;
578         add_char_to_match[nm] = (char)add_char;
579         num_matches++;
580 }
581
582 static int is_execute(const struct stat *st)
583 {
584         if ((!my_euid && (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) ||
585                 (my_uid == st->st_uid && (st->st_mode & S_IXUSR)) ||
586                 (my_gid == st->st_gid && (st->st_mode & S_IXGRP)) ||
587                 (st->st_mode & S_IXOTH)) return TRUE;
588         return FALSE;
589 }
590
591 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
592
593 static void username_tab_completion(char *ud, char *with_shash_flg)
594 {
595         struct passwd *entry;
596         int userlen;
597
598         ud++;                           /* ~user/... to user/... */
599         userlen = strlen(ud);
600
601         if (with_shash_flg) {           /* "~/..." or "~user/..." */
602                 char *sav_ud = ud - 1;
603                 char *home = 0;
604                 char *temp;
605
606                 if (*ud == '/') {       /* "~/..."     */
607                         home = home_pwd_buf;
608                 } else {
609                         /* "~user/..." */
610                         temp = strchr(ud, '/');
611                         *temp = 0;              /* ~user\0 */
612                         entry = getpwnam(ud);
613                         *temp = '/';            /* restore ~user/... */
614                         ud = temp;
615                         if (entry)
616                                 home = entry->pw_dir;
617                 }
618                 if (home) {
619                         if ((userlen + strlen(home) + 1) < BUFSIZ) {
620                                 char temp2[BUFSIZ];     /* argument size */
621
622                                 /* /home/user/... */
623                                 sprintf(temp2, "%s%s", home, ud);
624                                 strcpy(sav_ud, temp2);
625                         }
626                 }
627         } else {
628                 /* "~[^/]*" */
629                 setpwent();
630
631                 while ((entry = getpwent()) != NULL) {
632                         /* Null usernames should result in all users as possible completions. */
633                         if ( /*!userlen || */ !strncmp(ud, entry->pw_name, userlen)) {
634                                 add_match(bb_xasprintf("~%s", entry->pw_name), '/');
635                         }
636                 }
637
638                 endpwent();
639         }
640 }
641 #endif  /* CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION */
642
643 enum {
644         FIND_EXE_ONLY = 0,
645         FIND_DIR_ONLY = 1,
646         FIND_FILE_ONLY = 2,
647 };
648
649 #ifdef CONFIG_ASH
650 const char *cmdedit_path_lookup;
651 #else
652 #define cmdedit_path_lookup getenv("PATH")
653 #endif
654
655 static int path_parse(char ***p, int flags)
656 {
657         int npth;
658         const char *tmp;
659         const char *pth;
660
661         /* if not setenv PATH variable, to search cur dir "." */
662         if (flags != FIND_EXE_ONLY || (pth = cmdedit_path_lookup) == 0 ||
663                 /* PATH=<empty> or PATH=:<empty> */
664                 *pth == 0 || (*pth == ':' && *(pth + 1) == 0)) {
665                 return 1;
666         }
667
668         tmp = pth;
669         npth = 0;
670
671         for (;;) {
672                 npth++;                 /* count words is + 1 count ':' */
673                 tmp = strchr(tmp, ':');
674                 if (tmp) {
675                         if (*++tmp == 0)
676                                 break;  /* :<empty> */
677                 } else
678                         break;
679         }
680
681         *p = xmalloc(npth * sizeof(char *));
682
683         tmp = pth;
684         (*p)[0] = bb_xstrdup(tmp);
685         npth = 1;                       /* count words is + 1 count ':' */
686
687         for (;;) {
688                 tmp = strchr(tmp, ':');
689                 if (tmp) {
690                         (*p)[0][(tmp - pth)] = 0;       /* ':' -> '\0' */
691                         if (*++tmp == 0)
692                                 break;                  /* :<empty> */
693                 } else
694                         break;
695                 (*p)[npth++] = &(*p)[0][(tmp - pth)];   /* p[next]=p[0][&'\0'+1] */
696         }
697
698         return npth;
699 }
700
701 static char *add_quote_for_spec_chars(char *found, int add)
702 {
703         int l = 0;
704         char *s = xmalloc((strlen(found) + 1) * 2);
705
706         while (*found) {
707                 if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
708                         s[l++] = '\\';
709                 s[l++] = *found++;
710         }
711         if(add)
712             s[l++] = (char)add;
713         s[l] = 0;
714         return s;
715 }
716
717 static void exe_n_cwd_tab_completion(char *command, int type)
718 {
719         DIR *dir;
720         struct dirent *next;
721         char dirbuf[BUFSIZ];
722         struct stat st;
723         char *path1[1];
724         char **paths = path1;
725         int npaths;
726         int i;
727         char *found;
728         char *pfind = strrchr(command, '/');
729
730         path1[0] = ".";
731
732         if (pfind == NULL) {
733                 /* no dir, if flags==EXE_ONLY - get paths, else "." */
734                 npaths = path_parse(&paths, type);
735                 pfind = command;
736         } else {
737                 /* with dir */
738                 /* save for change */
739                 strcpy(dirbuf, command);
740                 /* set dir only */
741                 dirbuf[(pfind - command) + 1] = 0;
742 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
743                 if (dirbuf[0] == '~')   /* ~/... or ~user/... */
744                         username_tab_completion(dirbuf, dirbuf);
745 #endif
746                 /* "strip" dirname in command */
747                 pfind++;
748
749                 paths[0] = dirbuf;
750                 npaths = 1;                             /* only 1 dir */
751         }
752
753         for (i = 0; i < npaths; i++) {
754
755                 dir = opendir(paths[i]);
756                 if (!dir)                       /* Don't print an error */
757                         continue;
758
759                 while ((next = readdir(dir)) != NULL) {
760                         char *str_found = next->d_name;
761                         int add_chr = 0;
762
763                         /* matched ? */
764                         if (strncmp(str_found, pfind, strlen(pfind)))
765                                 continue;
766                         /* not see .name without .match */
767                         if (*str_found == '.' && *pfind == 0) {
768                                 if (*paths[i] == '/' && paths[i][1] == 0
769                                         && str_found[1] == 0) str_found = "";   /* only "/" */
770                                 else
771                                         continue;
772                         }
773                         found = concat_path_file(paths[i], str_found);
774                         /* hmm, remover in progress? */
775                         if (stat(found, &st) < 0)
776                                 goto cont;
777                         /* find with dirs ? */
778                         if (paths[i] != dirbuf)
779                                 strcpy(found, next->d_name);    /* only name */
780                         if (S_ISDIR(st.st_mode)) {
781                                 /* name is directory      */
782                                 char *e = found + strlen(found) - 1;
783
784                                 add_chr = '/';
785                                 if(*e == '/')
786                                         *e = '\0';
787                         } else {
788                                 /* not put found file if search only dirs for cd */
789                                 if (type == FIND_DIR_ONLY)
790                                         goto cont;
791                                 if (type == FIND_FILE_ONLY ||
792                                         (type == FIND_EXE_ONLY && is_execute(&st)))
793                                         add_chr = ' ';
794                         }
795                         /* Add it to the list */
796                         add_match(found, add_chr);
797                         continue;
798 cont:
799                         free(found);
800                 }
801                 closedir(dir);
802         }
803         if (paths != path1) {
804                 free(paths[0]);                 /* allocated memory only in first member */
805                 free(paths);
806         }
807 }
808
809
810 #define QUOT    (UCHAR_MAX+1)
811
812 #define collapse_pos(is, in) { \
813         memmove(int_buf+(is), int_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); \
814         memmove(pos_buf+(is), pos_buf+(in), (BUFSIZ+1-(is)-(in))*sizeof(int)); }
815
816 static int find_match(char *matchBuf, int *len_with_quotes)
817 {
818         int i, j;
819         int command_mode;
820         int c, c2;
821         int int_buf[BUFSIZ + 1];
822         int pos_buf[BUFSIZ + 1];
823
824         /* set to integer dimension characters and own positions */
825         for (i = 0;; i++) {
826                 int_buf[i] = (int) ((unsigned char) matchBuf[i]);
827                 if (int_buf[i] == 0) {
828                         pos_buf[i] = -1;        /* indicator end line */
829                         break;
830                 } else
831                         pos_buf[i] = i;
832         }
833
834         /* mask \+symbol and convert '\t' to ' ' */
835         for (i = j = 0; matchBuf[i]; i++, j++)
836                 if (matchBuf[i] == '\\') {
837                         collapse_pos(j, j + 1);
838                         int_buf[j] |= QUOT;
839                         i++;
840 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
841                         if (matchBuf[i] == '\t')        /* algorithm equivalent */
842                                 int_buf[j] = ' ' | QUOT;
843 #endif
844                 }
845 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
846                 else if (matchBuf[i] == '\t')
847                         int_buf[j] = ' ';
848 #endif
849
850         /* mask "symbols" or 'symbols' */
851         c2 = 0;
852         for (i = 0; int_buf[i]; i++) {
853                 c = int_buf[i];
854                 if (c == '\'' || c == '"') {
855                         if (c2 == 0)
856                                 c2 = c;
857                         else {
858                                 if (c == c2)
859                                         c2 = 0;
860                                 else
861                                         int_buf[i] |= QUOT;
862                         }
863                 } else if (c2 != 0 && c != '$')
864                         int_buf[i] |= QUOT;
865         }
866
867         /* skip commands with arguments if line have commands delimiters */
868         /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
869         for (i = 0; int_buf[i]; i++) {
870                 c = int_buf[i];
871                 c2 = int_buf[i + 1];
872                 j = i ? int_buf[i - 1] : -1;
873                 command_mode = 0;
874                 if (c == ';' || c == '&' || c == '|') {
875                         command_mode = 1 + (c == c2);
876                         if (c == '&') {
877                                 if (j == '>' || j == '<')
878                                         command_mode = 0;
879                         } else if (c == '|' && j == '>')
880                                 command_mode = 0;
881                 }
882                 if (command_mode) {
883                         collapse_pos(0, i + command_mode);
884                         i = -1;                         /* hack incremet */
885                 }
886         }
887         /* collapse `command...` */
888         for (i = 0; int_buf[i]; i++)
889                 if (int_buf[i] == '`') {
890                         for (j = i + 1; int_buf[j]; j++)
891                                 if (int_buf[j] == '`') {
892                                         collapse_pos(i, j + 1);
893                                         j = 0;
894                                         break;
895                                 }
896                         if (j) {
897                                 /* not found close ` - command mode, collapse all previous */
898                                 collapse_pos(0, i + 1);
899                                 break;
900                         } else
901                                 i--;                    /* hack incremet */
902                 }
903
904         /* collapse (command...(command...)...) or {command...{command...}...} */
905         c = 0;                                          /* "recursive" level */
906         c2 = 0;
907         for (i = 0; int_buf[i]; i++)
908                 if (int_buf[i] == '(' || int_buf[i] == '{') {
909                         if (int_buf[i] == '(')
910                                 c++;
911                         else
912                                 c2++;
913                         collapse_pos(0, i + 1);
914                         i = -1;                         /* hack incremet */
915                 }
916         for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
917                 if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
918                         if (int_buf[i] == ')')
919                                 c--;
920                         else
921                                 c2--;
922                         collapse_pos(0, i + 1);
923                         i = -1;                         /* hack incremet */
924                 }
925
926         /* skip first not quote space */
927         for (i = 0; int_buf[i]; i++)
928                 if (int_buf[i] != ' ')
929                         break;
930         if (i)
931                 collapse_pos(0, i);
932
933         /* set find mode for completion */
934         command_mode = FIND_EXE_ONLY;
935         for (i = 0; int_buf[i]; i++)
936                 if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
937                         if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
938                                 && matchBuf[pos_buf[0]]=='c'
939                                 && matchBuf[pos_buf[1]]=='d' )
940                                 command_mode = FIND_DIR_ONLY;
941                         else {
942                                 command_mode = FIND_FILE_ONLY;
943                                 break;
944                         }
945                 }
946         /* "strlen" */
947         for (i = 0; int_buf[i]; i++);
948         /* find last word */
949         for (--i; i >= 0; i--) {
950                 c = int_buf[i];
951                 if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
952                         collapse_pos(0, i + 1);
953                         break;
954                 }
955         }
956         /* skip first not quoted '\'' or '"' */
957         for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++);
958         /* collapse quote or unquote // or /~ */
959         while ((int_buf[i] & ~QUOT) == '/' &&
960                         ((int_buf[i + 1] & ~QUOT) == '/'
961                          || (int_buf[i + 1] & ~QUOT) == '~')) {
962                 i++;
963         }
964
965         /* set only match and destroy quotes */
966         j = 0;
967         for (c = 0; pos_buf[i] >= 0; i++) {
968                 matchBuf[c++] = matchBuf[pos_buf[i]];
969                 j = pos_buf[i] + 1;
970         }
971         matchBuf[c] = 0;
972         /* old lenght matchBuf with quotes symbols */
973         *len_with_quotes = j ? j - pos_buf[0] : 0;
974
975         return command_mode;
976 }
977
978 /*
979    display by column original ideas from ls applet,
980    very optimize by my :)
981 */
982 static void showfiles(void)
983 {
984         int ncols, row;
985         int column_width = 0;
986         int nfiles = num_matches;
987         int nrows = nfiles;
988         char str_add_chr[2];
989         int l;
990
991         /* find the longest file name-  use that as the column width */
992         for (row = 0; row < nrows; row++) {
993                 l = strlen(matches[row]);
994                 if(add_char_to_match[row])
995                     l++;
996                 if (column_width < l)
997                         column_width = l;
998         }
999         column_width += 2;              /* min space for columns */
1000         ncols = cmdedit_termw / column_width;
1001
1002         if (ncols > 1) {
1003                 nrows /= ncols;
1004                 if(nfiles % ncols)
1005                         nrows++;        /* round up fractionals */
1006         } else {
1007                 ncols = 1;
1008         }
1009         str_add_chr[1] = 0;
1010         for (row = 0; row < nrows; row++) {
1011                 int n = row;
1012                 int nc;
1013                 int acol;
1014
1015                 for(nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
1016                         str_add_chr[0] = add_char_to_match[n];
1017                         acol = str_add_chr[0] ? column_width - 1 : column_width;
1018                         printf("%s%s", matches[n], str_add_chr);
1019                         l = strlen(matches[n]);
1020                         while(l < acol) {
1021                             putchar(' ');
1022                             l++;
1023                         }
1024                 }
1025                 str_add_chr[0] = add_char_to_match[n];
1026                 printf("%s%s\n", matches[n], str_add_chr);
1027         }
1028 }
1029
1030
1031 static void input_tab(int *lastWasTab)
1032 {
1033         /* Do TAB completion */
1034         if (lastWasTab == 0) {          /* free all memory */
1035                 if (matches) {
1036                         while (num_matches > 0)
1037                                 free(matches[--num_matches]);
1038                         free(matches);
1039                         matches = (char **) NULL;
1040                         free(add_char_to_match);
1041                         add_char_to_match = NULL;
1042                 }
1043                 return;
1044         }
1045         if (! *lastWasTab) {
1046
1047                 char *tmp, *tmp1;
1048                 int len_found;
1049                 char matchBuf[BUFSIZ];
1050                 int find_type;
1051                 int recalc_pos;
1052
1053                 *lastWasTab = TRUE;             /* flop trigger */
1054
1055                 /* Make a local copy of the string -- up
1056                  * to the position of the cursor */
1057                 tmp = strncpy(matchBuf, command_ps, cursor);
1058                 tmp[cursor] = 0;
1059
1060                 find_type = find_match(matchBuf, &recalc_pos);
1061
1062                 /* Free up any memory already allocated */
1063                 input_tab(0);
1064
1065 #ifdef CONFIG_FEATURE_COMMAND_USERNAME_COMPLETION
1066                 /* If the word starts with `~' and there is no slash in the word,
1067                  * then try completing this word as a username. */
1068
1069                 if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
1070                         username_tab_completion(matchBuf, NULL);
1071                 if (!matches)
1072 #endif
1073                 /* Try to match any executable in our path and everything
1074                  * in the current working directory that matches.  */
1075                         exe_n_cwd_tab_completion(matchBuf, find_type);
1076                 /* Remove duplicate found and sort */
1077                 if(matches) {
1078                         int i, j, n, srt;
1079                         /* bubble */
1080                         n = num_matches;
1081                         for(i=0; i<(n-1); i++)
1082                             for(j=i+1; j<n; j++)
1083                                 if(matches[i]!=NULL && matches[j]!=NULL) {
1084                                     srt = strcmp(matches[i], matches[j]);
1085                                     if(srt == 0) {
1086                                         free(matches[j]);
1087                                         matches[j]=0;
1088                                     } else if(srt > 0) {
1089                                         tmp1 = matches[i];
1090                                         matches[i] = matches[j];
1091                                         matches[j] = tmp1;
1092                                         srt = add_char_to_match[i];
1093                                         add_char_to_match[i] = add_char_to_match[j];
1094                                         add_char_to_match[j] = srt;
1095                                     }
1096                                 }
1097                         j = n;
1098                         n = 0;
1099                         for(i=0; i<j; i++)
1100                             if(matches[i]) {
1101                                 matches[n]=matches[i];
1102                                 add_char_to_match[n]=add_char_to_match[i];
1103                                 n++;
1104                             }
1105                         num_matches = n;
1106                 }
1107                 /* Did we find exactly one match? */
1108                 if (!matches || num_matches > 1) {
1109
1110                         beep();
1111                         if (!matches)
1112                                 return;         /* not found */
1113                         /* find minimal match */
1114                         tmp1 = bb_xstrdup(matches[0]);
1115                         for (tmp = tmp1; *tmp; tmp++)
1116                                 for (len_found = 1; len_found < num_matches; len_found++)
1117                                         if (matches[len_found][(tmp - tmp1)] != *tmp) {
1118                                                 *tmp = 0;
1119                                                 break;
1120                                         }
1121                         if (*tmp1 == 0) {        /* have unique */
1122                                 free(tmp1);
1123                                 return;
1124                         }
1125                         tmp = add_quote_for_spec_chars(tmp1, 0);
1126                         free(tmp1);
1127                 } else {                        /* one match */
1128                         tmp = add_quote_for_spec_chars(matches[0], add_char_to_match[0]);
1129                         /* for next completion current found */
1130                         *lastWasTab = FALSE;
1131                 }
1132                 len_found = strlen(tmp);
1133                 /* have space to placed match? */
1134                 if ((len_found - strlen(matchBuf) + len) < BUFSIZ) {
1135
1136                         /* before word for match   */
1137                         command_ps[cursor - recalc_pos] = 0;
1138                         /* save   tail line        */
1139                         strcpy(matchBuf, command_ps + cursor);
1140                         /* add    match            */
1141                         strcat(command_ps, tmp);
1142                         /* add    tail             */
1143                         strcat(command_ps, matchBuf);
1144                         /* back to begin word for match    */
1145                         input_backward(recalc_pos);
1146                         /* new pos                         */
1147                         recalc_pos = cursor + len_found;
1148                         /* new len                         */
1149                         len = strlen(command_ps);
1150                         /* write out the matched command   */
1151                         redraw(cmdedit_y, len - recalc_pos);
1152                 }
1153                 free(tmp);
1154         } else {
1155                 /* Ok -- the last char was a TAB.  Since they
1156                  * just hit TAB again, print a list of all the
1157                  * available choices... */
1158                 if (matches && num_matches > 0) {
1159                         int sav_cursor = cursor;        /* change goto_new_line() */
1160
1161                         /* Go to the next line */
1162                         goto_new_line();
1163                         showfiles();
1164                         redraw(0, len - sav_cursor);
1165                 }
1166         }
1167 }
1168 #endif  /* CONFIG_FEATURE_COMMAND_TAB_COMPLETION */
1169
1170 #if MAX_HISTORY >= 1
1171 static void get_previous_history(void)
1172 {
1173         if(command_ps[0] != 0 || history[cur_history] == 0) {
1174                 free(history[cur_history]);
1175                 history[cur_history] = bb_xstrdup(command_ps);
1176         }
1177         cur_history--;
1178 }
1179
1180 static int get_next_history(void)
1181 {
1182         int ch = cur_history;
1183
1184         if (ch < n_history) {
1185                 get_previous_history(); /* save the current history line */
1186                 return (cur_history = ch+1);
1187         } else {
1188                 beep();
1189                 return 0;
1190         }
1191 }
1192
1193 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1194 void load_history ( const char *fromfile )
1195 {
1196         FILE *fp;
1197         int hi;
1198
1199         /* cleanup old */
1200
1201         for(hi = n_history; hi > 0; ) {
1202                 hi--;
1203                 free ( history [hi] );
1204         }
1205
1206         if (( fp = fopen ( fromfile, "r" ))) {
1207
1208                 for ( hi = 0; hi < MAX_HISTORY; ) {
1209                         char * hl = bb_get_chomped_line_from_file(fp);
1210                         int l;
1211
1212                         if(!hl)
1213                                 break;
1214                         l = strlen(hl);
1215                         if(l >= BUFSIZ)
1216                                 hl[BUFSIZ-1] = 0;
1217                         if(l == 0 || hl[0] == ' ') {
1218                                 free(hl);
1219                                 continue;
1220                         }
1221                         history [hi++] = hl;
1222                 }
1223                 fclose ( fp );
1224         }
1225         cur_history = n_history = hi;
1226 }
1227
1228 void save_history ( const char *tofile )
1229 {
1230         FILE *fp = fopen ( tofile, "w" );
1231
1232         if ( fp ) {
1233                 int i;
1234
1235                 for ( i = 0; i < n_history; i++ ) {
1236                         fprintf(fp, "%s\n", history [i]);
1237                 }
1238                 fclose ( fp );
1239         }
1240 }
1241 #endif
1242
1243 #endif
1244
1245 enum {
1246         ESC = 27,
1247         DEL = 127,
1248 };
1249
1250
1251 /*
1252  * This function is used to grab a character buffer
1253  * from the input file descriptor and allows you to
1254  * a string with full command editing (sort of like
1255  * a mini readline).
1256  *
1257  * The following standard commands are not implemented:
1258  * ESC-b -- Move back one word
1259  * ESC-f -- Move forward one word
1260  * ESC-d -- Delete back one word
1261  * ESC-h -- Delete forward one word
1262  * CTL-t -- Transpose two characters
1263  *
1264  * Minimalist vi-style command line editing available if configured.
1265  *  vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
1266  *
1267  */
1268
1269 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
1270 static int vi_mode;
1271
1272 void setvimode ( int viflag )
1273 {
1274         vi_mode = viflag;
1275 }
1276
1277 static void
1278 vi_Word_motion(char *command, int eat)
1279 {
1280         while (cursor < len && !isspace(command[cursor]))
1281                 input_forward();
1282         if (eat) while (cursor < len && isspace(command[cursor]))
1283                 input_forward();
1284 }
1285
1286 static void
1287 vi_word_motion(char *command, int eat)
1288 {
1289         if (isalnum(command[cursor]) || command[cursor] == '_') {
1290                 while (cursor < len &&
1291                     (isalnum(command[cursor+1]) ||
1292                                 command[cursor+1] == '_'))
1293                         input_forward();
1294         } else if (ispunct(command[cursor])) {
1295                 while (cursor < len &&
1296                     (ispunct(command[cursor+1])))
1297                         input_forward();
1298         }
1299
1300         if (cursor < len)
1301                 input_forward();
1302
1303         if (eat && cursor < len && isspace(command[cursor]))
1304                 while (cursor < len && isspace(command[cursor]))
1305                         input_forward();
1306 }
1307
1308 static void
1309 vi_End_motion(char *command)
1310 {
1311         input_forward();
1312         while (cursor < len && isspace(command[cursor]))
1313                 input_forward();
1314         while (cursor < len-1 && !isspace(command[cursor+1]))
1315                 input_forward();
1316 }
1317
1318 static void
1319 vi_end_motion(char *command)
1320 {
1321         if (cursor >= len-1)
1322                 return;
1323         input_forward();
1324         while (cursor < len-1 && isspace(command[cursor]))
1325                 input_forward();
1326         if (cursor >= len-1)
1327                 return;
1328         if (isalnum(command[cursor]) || command[cursor] == '_') {
1329                 while (cursor < len-1 &&
1330                     (isalnum(command[cursor+1]) ||
1331                                 command[cursor+1] == '_'))
1332                         input_forward();
1333         } else if (ispunct(command[cursor])) {
1334                 while (cursor < len-1 &&
1335                     (ispunct(command[cursor+1])))
1336                         input_forward();
1337         }
1338 }
1339
1340 static void
1341 vi_Back_motion(char *command)
1342 {
1343         while (cursor > 0 && isspace(command[cursor-1]))
1344                 input_backward(1);
1345         while (cursor > 0 && !isspace(command[cursor-1]))
1346                 input_backward(1);
1347 }
1348
1349 static void
1350 vi_back_motion(char *command)
1351 {
1352         if (cursor <= 0)
1353                 return;
1354         input_backward(1);
1355         while (cursor > 0 && isspace(command[cursor]))
1356                 input_backward(1);
1357         if (cursor <= 0)
1358                 return;
1359         if (isalnum(command[cursor]) || command[cursor] == '_') {
1360                 while (cursor > 0 &&
1361                     (isalnum(command[cursor-1]) ||
1362                                 command[cursor-1] == '_'))
1363                         input_backward(1);
1364         } else if (ispunct(command[cursor])) {
1365                 while (cursor > 0 &&
1366                     (ispunct(command[cursor-1])))
1367                         input_backward(1);
1368         }
1369 }
1370 #endif
1371
1372 /*
1373  * the normal emacs mode and vi's insert mode are the same.
1374  * commands entered when in vi command mode ("escape mode") get
1375  * an extra bit added to distinguish them.  this lets them share
1376  * much of the code in the big switch and while loop.  i
1377  * experimented with an ugly macro to make the case labels for
1378  * these cases go away entirely when vi mode isn't configured, in
1379  * hopes of letting the jump tables get smaller:
1380  *  #define vcase(caselabel) caselabel
1381  * and then
1382  *      case CNTRL('A'):
1383  *      case vcase(VICMD('0'):)
1384  * but it didn't seem to make any difference in code size,
1385  * and the macro-ized code was too ugly.
1386  */
1387
1388 #define VI_cmdbit 0x100
1389 #define VICMD(somecmd) ((somecmd)|VI_cmdbit)
1390
1391 /* convert uppercase ascii to equivalent control char, for readability */
1392 #define CNTRL(uc_char) ((uc_char) - 0x40)
1393
1394
1395 int cmdedit_read_input(char *prompt, char command[BUFSIZ])
1396 {
1397
1398         int break_out = 0;
1399         int lastWasTab = FALSE;
1400         unsigned char c;
1401 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
1402         unsigned int ic, prevc;
1403         int vi_cmdmode = 0;
1404 #endif
1405         /* prepare before init handlers */
1406         cmdedit_y = 0;  /* quasireal y, not true work if line > xt*yt */
1407         len = 0;
1408         command_ps = command;
1409
1410         getTermSettings(0, (void *) &initial_settings);
1411         memcpy(&new_settings, &initial_settings, sizeof(struct termios));
1412         new_settings.c_lflag &= ~ICANON;        /* unbuffered input */
1413         /* Turn off echoing and CTRL-C, so we can trap it */
1414         new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
1415         /* Hmm, in linux c_cc[] not parsed if set ~ICANON */
1416         new_settings.c_cc[VMIN] = 1;
1417         new_settings.c_cc[VTIME] = 0;
1418         /* Turn off CTRL-C, so we can trap it */
1419 #       ifndef _POSIX_VDISABLE
1420 #               define _POSIX_VDISABLE '\0'
1421 #       endif
1422         new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
1423         command[0] = 0;
1424
1425         setTermSettings(0, (void *) &new_settings);
1426         handlers_sets |= SET_RESET_TERM;
1427
1428         /* Now initialize things */
1429         cmdedit_init();
1430         /* Print out the command prompt */
1431         parse_prompt(prompt);
1432
1433         while (1) {
1434
1435                 fflush(stdout);                 /* buffered out to fast */
1436
1437                 if (safe_read(0, &c, 1) < 1)
1438                         /* if we can't read input then exit */
1439                         goto prepare_to_die;
1440
1441 #ifdef CONFIG_FEATURE_COMMAND_EDITING_VI
1442                 newdelflag = 1;
1443                 ic = c;
1444                 if (vi_cmdmode)
1445                         ic |= VI_cmdbit;
1446                 switch (ic)
1447 #else
1448                 switch (c)
1449 #endif
1450                 {
1451                 case '\n':
1452                 case '\r':
1453                 case VICMD('\n'):
1454                 case VICMD('\r'):
1455                         /* Enter */
1456                         goto_new_line();
1457                         break_out = 1;
1458                         break;
1459                 case CNTRL('A'):
1460                 case VICMD('0'):
1461                         /* Control-a -- Beginning of line */
1462                         input_backward(cursor);
1463                         break;
1464                 case CNTRL('B'):
1465                 case VICMD('h'):
1466                 case VICMD('\b'):
1467                 case VICMD(DEL):
1468                         /* Control-b -- Move back one character */
1469                         input_backward(1);
1470                         break;
1471                 case CNTRL('C'):
1472                 case VICMD(CNTRL('C')):
1473                         /* Control-c -- stop gathering input */
1474                         goto_new_line();
1475 #ifndef CONFIG_ASH
1476                         command[0] = 0;
1477                         len = 0;
1478                         lastWasTab = FALSE;
1479                         put_prompt();
1480 #else
1481                         len = 0;
1482                         break_out = -1; /* to control traps */
1483 #endif
1484                         break;
1485                 case CNTRL('D'):
1486                         /* Control-d -- Delete one character, or exit
1487                          * if the len=0 and no chars to delete */
1488                         if (len == 0) {
1489                                         errno = 0;
1490 prepare_to_die:
1491 #if !defined(CONFIG_ASH)
1492                                 printf("exit");
1493                                 goto_new_line();
1494                                 /* cmdedit_reset_term() called in atexit */
1495                                 exit(EXIT_SUCCESS);
1496 #else
1497                                 /* to control stopped jobs */
1498                                 len = break_out = -1;
1499                                 break;
1500 #endif
1501                         } else {
1502                                 input_delete(0);
1503                         }
1504                         break;
1505                 case CNTRL('E'):
1506                 case VICMD('$'):
1507                         /* Control-e -- End of line */
1508                         input_end();
1509                         break;
1510                 case CNTRL('F'):
1511                 case VICMD('l'):
1512                 case VICMD(' '):
1513                         /* Control-f -- Move forward one character */
1514                         input_forward();
1515                         break;
1516                 case '\b':
1517                 case DEL:
1518                         /* Control-h and DEL */
1519                         input_backspace();
1520                         break;
1521                 case '\t':
1522 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
1523                         input_tab(&lastWasTab);
1524 #endif
1525                         break;
1526                 case CNTRL('K'):
1527                         /* Control-k -- clear to end of line */
1528                         *(command + cursor) = 0;
1529                         len = cursor;
1530                         printf("\033[J");
1531                         break;
1532                 case CNTRL('L'):
1533                 case VICMD(CNTRL('L')):
1534                         /* Control-l -- clear screen */
1535                         printf("\033[H");
1536                         redraw(0, len-cursor);
1537                         break;
1538 #if MAX_HISTORY >= 1
1539                 case CNTRL('N'):
1540                 case VICMD(CNTRL('N')):
1541                 case VICMD('j'):
1542                         /* Control-n -- Get next command in history */
1543                         if (get_next_history())
1544                                 goto rewrite_line;
1545                         break;
1546                 case CNTRL('P'):
1547                 case VICMD(CNTRL('P')):
1548                 case VICMD('k'):
1549                         /* Control-p -- Get previous command from history */
1550                         if (cur_history > 0) {
1551                                 get_previous_history();
1552                                 goto rewrite_line;
1553                         } else {
1554                                 beep();
1555                         }
1556                         break;
1557 #endif
1558                 case CNTRL('U'):
1559                 case VICMD(CNTRL('U')):
1560                         /* Control-U -- Clear line before cursor */
1561                         if (cursor) {
1562                                 strcpy(command, command + cursor);
1563                                 redraw(cmdedit_y, len -= cursor);
1564                         }
1565                         break;
1566                 case CNTRL('W'):
1567                 case VICMD(CNTRL('W')):
1568                         /* Control-W -- Remove the last word */
1569                         while (cursor > 0 && isspace(command[cursor-1]))
1570                                 input_backspace();
1571                         while (cursor > 0 &&!isspace(command[cursor-1]))
1572                                 input_backspace();
1573                         break;
1574 #if CONFIG_FEATURE_COMMAND_EDITING_VI
1575                 case VICMD('i'):
1576                         vi_cmdmode = 0;
1577                         break;
1578                 case VICMD('I'):
1579                         input_backward(cursor);
1580                         vi_cmdmode = 0;
1581                         break;
1582                 case VICMD('a'):
1583                         input_forward();
1584                         vi_cmdmode = 0;
1585                         break;
1586                 case VICMD('A'):
1587                         input_end();
1588                         vi_cmdmode = 0;
1589                         break;
1590                 case VICMD('x'):
1591                         input_delete(1);
1592                         break;
1593                 case VICMD('X'):
1594                         if (cursor > 0) {
1595                                 input_backward(1);
1596                                 input_delete(1);
1597                         }
1598                         break;
1599                 case VICMD('W'):
1600                         vi_Word_motion(command, 1);
1601                         break;
1602                 case VICMD('w'):
1603                         vi_word_motion(command, 1);
1604                         break;
1605                 case VICMD('E'):
1606                         vi_End_motion(command);
1607                         break;
1608                 case VICMD('e'):
1609                         vi_end_motion(command);
1610                         break;
1611                 case VICMD('B'):
1612                         vi_Back_motion(command);
1613                         break;
1614                 case VICMD('b'):
1615                         vi_back_motion(command);
1616                         break;
1617                 case VICMD('C'):
1618                         vi_cmdmode = 0;
1619                         /* fall through */
1620                 case VICMD('D'):
1621                         goto clear_to_eol;
1622
1623                 case VICMD('c'):
1624                         vi_cmdmode = 0;
1625                         /* fall through */
1626                 case VICMD('d'):
1627                         {
1628                         int nc, sc;
1629                         sc = cursor;
1630                         prevc = ic;
1631                         if (safe_read(0, &c, 1) < 1)
1632                                 goto prepare_to_die;
1633                         if (c == (prevc & 0xff)) {
1634                             /* "cc", "dd" */
1635                             input_backward(cursor);
1636                             goto clear_to_eol;
1637                             break;
1638                         }
1639                         switch(c) {
1640                         case 'w':
1641                         case 'W':
1642                         case 'e':
1643                         case 'E':
1644                             switch (c) {
1645                             case 'w':   /* "dw", "cw" */
1646                                     vi_word_motion(command, vi_cmdmode);
1647                                     break;
1648                             case 'W':   /* 'dW', 'cW' */
1649                                     vi_Word_motion(command, vi_cmdmode);
1650                                     break;
1651                             case 'e':   /* 'de', 'ce' */
1652                                     vi_end_motion(command);
1653                                     input_forward();
1654                                     break;
1655                             case 'E':   /* 'dE', 'cE' */
1656                                     vi_End_motion(command);
1657                                     input_forward();
1658                                     break;
1659                             }
1660                             nc = cursor;
1661                             input_backward(cursor - sc);
1662                             while (nc-- > cursor)
1663                                     input_delete(1);
1664                             break;
1665                         case 'b':  /* "db", "cb" */
1666                         case 'B':  /* implemented as B */
1667                             if (c == 'b')
1668                                     vi_back_motion(command);
1669                             else
1670                                     vi_Back_motion(command);
1671                             while (sc-- > cursor)
1672                                     input_delete(1);
1673                             break;
1674                         case ' ':  /* "d ", "c " */
1675                             input_delete(1);
1676                             break;
1677                         case '$':  /* "d$", "c$" */
1678                         clear_to_eol:
1679                             while (cursor < len)
1680                                     input_delete(1);
1681                             break;
1682                         }
1683                         }
1684                         break;
1685                 case VICMD('p'):
1686                         input_forward();
1687                         /* fallthrough */
1688                 case VICMD('P'):
1689                         put();
1690                         break;
1691                 case VICMD('r'):
1692                         if (safe_read(0, &c, 1) < 1)
1693                                 goto prepare_to_die;
1694                         if (c == 0)
1695                                 beep();
1696                         else {
1697                                 *(command + cursor) = c;
1698                                 putchar(c);
1699                                 putchar('\b');
1700                         }
1701                         break;
1702 #endif /* CONFIG_FEATURE_COMMAND_EDITING_VI */
1703                 case ESC:{
1704 #if CONFIG_FEATURE_COMMAND_EDITING_VI
1705                         if (vi_mode) {
1706                                 /* ESC: insert mode --> command mode */
1707                                 vi_cmdmode = 1;
1708                                 input_backward(1);
1709                                 break;
1710                         }
1711 #endif
1712                         /* escape sequence follows */
1713                         if (safe_read(0, &c, 1) < 1)
1714                                 goto prepare_to_die;
1715                         /* different vt100 emulations */
1716                         if (c == '[' || c == 'O') {
1717                 case VICMD('['):
1718                 case VICMD('O'):
1719                                 if (safe_read(0, &c, 1) < 1)
1720                                         goto prepare_to_die;
1721                         }
1722                         if (c >= '1' && c <= '9') {
1723                                 unsigned char dummy;
1724
1725                                 if (safe_read(0, &dummy, 1) < 1)
1726                                         goto prepare_to_die;
1727                                 if(dummy != '~')
1728                                         c = 0;
1729                         }
1730                         switch (c) {
1731 #ifdef CONFIG_FEATURE_COMMAND_TAB_COMPLETION
1732                         case '\t':                      /* Alt-Tab */
1733
1734                                 input_tab(&lastWasTab);
1735                                 break;
1736 #endif
1737 #if MAX_HISTORY >= 1
1738                         case 'A':
1739                                 /* Up Arrow -- Get previous command from history */
1740                                 if (cur_history > 0) {
1741                                         get_previous_history();
1742                                         goto rewrite_line;
1743                                 } else {
1744                                         beep();
1745                                 }
1746                                 break;
1747                         case 'B':
1748                                 /* Down Arrow -- Get next command in history */
1749                                 if (!get_next_history())
1750                                         break;
1751                                 /* Rewrite the line with the selected history item */
1752 rewrite_line:
1753                                 /* change command */
1754                                 len = strlen(strcpy(command, history[cur_history]));
1755                                 /* redraw and go to eol (bol, in vi */
1756 #if CONFIG_FEATURE_COMMAND_EDITING_VI
1757                                 redraw(cmdedit_y, vi_mode ? 9999:0);
1758 #else
1759                                 redraw(cmdedit_y, 0);
1760 #endif
1761                                 break;
1762 #endif
1763                         case 'C':
1764                                 /* Right Arrow -- Move forward one character */
1765                                 input_forward();
1766                                 break;
1767                         case 'D':
1768                                 /* Left Arrow -- Move back one character */
1769                                 input_backward(1);
1770                                 break;
1771                         case '3':
1772                                 /* Delete */
1773                                 input_delete(0);
1774                                 break;
1775                         case '1':
1776                         case 'H':
1777                                 /* <Home> */
1778                                 input_backward(cursor);
1779                                 break;
1780                         case '4':
1781                         case 'F':
1782                                 /* <End> */
1783                                 input_end();
1784                                 break;
1785                         default:
1786                                 c = 0;
1787                                 beep();
1788                         }
1789                         break;
1790                 }
1791
1792                 default:        /* If it's regular input, do the normal thing */
1793 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1794                         /* Control-V -- Add non-printable symbol */
1795                         if (c == CNTRL('V')) {
1796                                 if (safe_read(0, &c, 1) < 1)
1797                                         goto prepare_to_die;
1798                                 if (c == 0) {
1799                                         beep();
1800                                         break;
1801                                 }
1802                         } else
1803 #endif
1804                         {
1805 #if CONFIG_FEATURE_COMMAND_EDITING_VI
1806                                 if (vi_cmdmode)  /* don't self-insert */
1807                                         break;
1808 #endif
1809                                 if (!Isprint(c)) /* Skip non-printable characters */
1810                                         break;
1811                         }
1812
1813                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
1814                                 break;
1815
1816                         len++;
1817
1818                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
1819                                 *(command + cursor) = c;
1820                                 *(command + cursor + 1) = 0;
1821                                 cmdedit_set_out_char(0);
1822                         } else {                        /* Insert otherwise */
1823                                 int sc = cursor;
1824
1825                                 memmove(command + sc + 1, command + sc, len - sc);
1826                                 *(command + sc) = c;
1827                                 sc++;
1828                                 /* rewrite from cursor */
1829                                 input_end();
1830                                 /* to prev x pos + 1 */
1831                                 input_backward(cursor - sc);
1832                         }
1833
1834                         break;
1835                 }
1836                 if (break_out)                  /* Enter is the command terminator, no more input. */
1837                         break;
1838
1839                 if (c != '\t')
1840                         lastWasTab = FALSE;
1841         }
1842
1843         setTermSettings(0, (void *) &initial_settings);
1844         handlers_sets &= ~SET_RESET_TERM;
1845
1846 #if MAX_HISTORY >= 1
1847         /* Handle command history log */
1848         /* cleanup may be saved current command line */
1849         if (len> 0) {                                      /* no put empty line */
1850                 int i = n_history;
1851
1852                 free(history[MAX_HISTORY]);
1853                 history[MAX_HISTORY] = 0;
1854                         /* After max history, remove the oldest command */
1855                 if (i >= MAX_HISTORY) {
1856                         free(history[0]);
1857                         for(i = 0; i < (MAX_HISTORY-1); i++)
1858                                 history[i] = history[i+1];
1859                 }
1860                 history[i++] = bb_xstrdup(command);
1861                 cur_history = i;
1862                 n_history = i;
1863 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1864                 num_ok_lines++;
1865 #endif
1866         }
1867 #else  /* MAX_HISTORY < 1 */
1868 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1869         if (len > 0) {              /* no put empty line */
1870                 num_ok_lines++;
1871         }
1872 #endif
1873 #endif  /* MAX_HISTORY >= 1 */
1874         if (break_out > 0) {
1875                 command[len++] = '\n';          /* set '\n' */
1876                 command[len] = 0;
1877         }
1878 #if defined(CONFIG_FEATURE_CLEAN_UP) && defined(CONFIG_FEATURE_COMMAND_TAB_COMPLETION)
1879         input_tab(0);                           /* strong free */
1880 #endif
1881 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1882         free(cmdedit_prompt);
1883 #endif
1884         cmdedit_reset_term();
1885         return len;
1886 }
1887
1888
1889
1890 #endif  /* CONFIG_FEATURE_COMMAND_EDITING */
1891
1892
1893 #ifdef TEST
1894
1895 const char *bb_applet_name = "debug stuff usage";
1896
1897 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1898 #include <locale.h>
1899 #endif
1900
1901 int main(int argc, char **argv)
1902 {
1903         char buff[BUFSIZ];
1904         char *prompt =
1905 #if defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1906                 "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:\
1907 \\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] \
1908 \\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
1909 #else
1910                 "% ";
1911 #endif
1912
1913 #ifdef CONFIG_FEATURE_NONPRINTABLE_INVERSE_PUT
1914         setlocale(LC_ALL, "");
1915 #endif
1916         while(1) {
1917                 int l;
1918                 l = cmdedit_read_input(prompt, buff);
1919                 if(l > 0 && buff[l-1] == '\n') {
1920                         buff[l-1] = 0;
1921                         printf("*** cmdedit_read_input() returned line =%s=\n", buff);
1922                 } else {
1923                         break;
1924                 }
1925         }
1926         printf("*** cmdedit_read_input() detect ^D\n");
1927         return 0;
1928 }
1929
1930 #endif  /* TEST */