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