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