9800dd1c6c235936490670b0edb6c8a92b97a649
[platform/upstream/busybox.git] / shell / cmdedit.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Termios command line History and Editting for NetBSD sh (ash)
4  * Copyright (c) 1999
5  *      Main code:            Adam Rogoyski <rogoyski@cs.utexas.edu> 
6  *      Etc:                  Dave Cinege <dcinege@psychosis.com>
7  *      Adjusted for busybox: Erik Andersen <andersee@debian.org>
8  *
9  * You may use this code as you wish, so long as the original author(s)
10  * are attributed in any redistributions of the source code.
11  * This code is 'as is' with no warranty.
12  * This code may safely be consumed by a BSD or GPL license.
13  *
14  * v 0.5  19990328      Initial release 
15  *
16  * Future plans: Simple file and path name completion. (like BASH)
17  *
18  */
19
20 /*
21    Usage and Known bugs:
22    Terminal key codes are not extensive, and more will probably
23    need to be added. This version was created on Debian GNU/Linux 2.x.
24    Delete, Backspace, Home, End, and the arrow keys were tested
25    to work in an Xterm and console. Ctrl-A also works as Home.
26    Ctrl-E also works as End. The binary size increase is <3K.
27
28    Editting will not display correctly for lines greater then the 
29    terminal width. (more then one line.) However, history will.
30  */
31
32 #include "internal.h"
33 #ifdef BB_FEATURE_SH_COMMAND_EDITING
34
35 #include <stdio.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <termio.h>
41 #include <ctype.h>
42 #include <signal.h>
43
44
45 #define  MAX_HISTORY   15               /* Maximum length of the linked list for the command line history */
46
47 #define ESC     27
48 #define DEL     127
49 #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
50 #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
51
52 static struct history *his_front = NULL;        /* First element in command line list */
53 static struct history *his_end = NULL;  /* Last element in command line list */
54 static struct termio old_term, new_term;        /* Current termio and the previous termio before starting ash */
55
56 static int cmdedit_termw = 80;  /* actual terminal width */
57 static int cmdedit_scroll = 27; /* width of EOL scrolling region */
58 static int history_counter = 0; /* Number of commands in history list */
59 static int reset_term = 0;              /* Set to true if the terminal needs to be reset upon exit */
60
61 struct history {
62         char *s;
63         struct history *p;
64         struct history *n;
65 };
66
67 #define xwrite write
68
69 void
70 cmdedit_setwidth(int w)
71 {
72     if (w > 20) {
73                 cmdedit_termw = w;
74                 cmdedit_scroll = w / 3;
75     } else {
76                 errorMsg("\n*** Error: minimum screen width is 21\n");
77     }
78 }
79
80 void cmdedit_reset_term(void)
81 {
82         if (reset_term)
83                 ioctl(fileno(stdin), TCSETA, (void *) &old_term);
84 }
85
86 void clean_up_and_die(int sig)
87 {
88         cmdedit_reset_term();
89         fprintf(stdout, "\n");
90         exit(TRUE);
91 }
92
93 /* Go to HOME position */
94 void input_home(int outputFd, int *cursor)
95 {
96         while (*cursor > 0) {
97                 xwrite(outputFd, "\b", 1);
98                 --*cursor;
99         }
100 }
101
102 /* Go to END position */
103 void input_end(int outputFd, int *cursor, int len)
104 {
105         while (*cursor < len) {
106                 xwrite(outputFd, "\033[C", 3);
107                 ++*cursor;
108         }
109 }
110
111 /* Delete the char in back of the cursor */
112 void input_backspace(char* command, int outputFd, int *cursor, int *len)
113 {
114         int j = 0;
115
116         if (*cursor > 0) {
117                 xwrite(outputFd, "\b \b", 3);
118                 --*cursor;
119                 memmove(command + *cursor, command + *cursor + 1,
120                                 BUFSIZ - *cursor + 1);
121
122                 for (j = *cursor; j < (BUFSIZ - 1); j++) {
123                         if (!*(command + j))
124                                 break;
125                         else
126                                 xwrite(outputFd, (command + j), 1);
127                 }
128
129                 xwrite(outputFd, " \b", 2);
130
131                 while (j-- > *cursor)
132                         xwrite(outputFd, "\b", 1);
133
134                 --*len;
135         }
136 }
137
138 /* Delete the char in front of the cursor */
139 void input_delete(char* command, int outputFd, int cursor, int *len)
140 {
141         int j = 0;
142
143         if (cursor == *len)
144                 return;
145         
146         memmove(command + cursor, command + cursor + 1,
147                         BUFSIZ - cursor - 1);
148         for (j = cursor; j < (BUFSIZ - 1); j++) {
149                 if (!*(command + j))
150                         break;
151                 else
152                         xwrite(outputFd, (command + j), 1);
153         }
154
155         xwrite(outputFd, " \b", 2);
156
157         while (j-- > cursor)
158                 xwrite(outputFd, "\b", 1);
159         --*len;
160 }
161
162 /* Move forward one charactor */
163 void input_forward(int outputFd, int *cursor, int len)
164 {
165         if (*cursor < len) {
166                 xwrite(outputFd, "\033[C", 3);
167                 ++*cursor;
168         }
169 }
170
171 /* Move back one charactor */
172 void input_backward(int outputFd, int *cursor)
173 {
174         if (*cursor > 0) {
175                 xwrite(outputFd, "\033[D", 3);
176                 --*cursor;
177         }
178 }
179
180
181
182 #ifdef BB_FEATURE_SH_TAB_COMPLETION
183 char** username_tab_completion(char* command, int *num_matches)
184 {
185         char **matches = (char **) NULL;
186         *num_matches=0;
187         fprintf(stderr, "\nin username_tab_completion\n");
188         return (matches);
189 }
190
191 #include <dirent.h>
192 char** exe_n_cwd_tab_completion(char* command, int *num_matches)
193 {
194         char *dirName;
195         char **matches = (char **) NULL;
196         DIR *dir;
197         struct dirent *next;
198                         
199         matches = malloc( sizeof(char*)*50);
200
201         /* Stick a wildcard onto the command, for later use */
202         strcat( command, "*");
203
204         /* Now wall the current directory */
205         dirName = get_current_dir_name();
206         dir = opendir(dirName);
207         if (!dir) {
208                 /* Don't print an error, just shut up and return */
209                 *num_matches=0;
210                 return (matches);
211         }
212         while ((next = readdir(dir)) != NULL) {
213
214                 /* Some quick sanity checks */
215                 if ((strcmp(next->d_name, "..") == 0)
216                         || (strcmp(next->d_name, ".") == 0)) {
217                         continue;
218                 } 
219                 /* See if this matches */
220                 if (check_wildcard_match(next->d_name, command) == TRUE) {
221                         /* Cool, found a match.  Add it to the list */
222                         matches[*num_matches] = malloc(strlen(next->d_name)+1);
223                         strcpy( matches[*num_matches], next->d_name);
224                         ++*num_matches;
225                         //matches = realloc( matches, sizeof(char*)*(*num_matches));
226                 }
227         }
228
229         return (matches);
230 }
231
232 void input_tab(char* command, int outputFd, int *cursor, int *len)
233 {
234         /* Do TAB completion */
235         static int num_matches=0;
236         static char **matches = (char **) NULL;
237         int pos = cursor;
238
239
240         if (lastWasTab == FALSE) {
241                 char *tmp, *tmp1, *matchBuf;
242
243                 /* For now, we will not bother with trying to distinguish
244                  * whether the cursor is in/at a command extression -- we
245                  * will always try all possable matches.  If you don't like
246                  * that then feel free to fix it.
247                  */
248
249                 /* Make a local copy of the string -- up 
250                  * to the position of the cursor */
251                 matchBuf = (char *) calloc(BUFSIZ, sizeof(char));
252                 strncpy(matchBuf, command, cursor);
253                 tmp=matchBuf;
254
255                 /* skip past any command seperator tokens */
256                 while (*tmp && (tmp1=strpbrk(tmp, ";|&{(`")) != NULL) {
257                         tmp=++tmp1;
258                         /* skip any leading white space */
259                         while (*tmp && isspace(*tmp)) 
260                                 ++tmp;
261                 }
262
263                 /* skip any leading white space */
264                 while (*tmp && isspace(*tmp)) 
265                         ++tmp;
266
267                 /* Free up any memory already allocated */
268                 if (matches) {
269                         free(matches);
270                         matches = (char **) NULL;
271                 }
272
273                 /* If the word starts with `~' and there is no slash in the word, 
274                  * then try completing this word as a username. */
275
276                 /* FIXME -- this check is broken! */
277                 if (*tmp == '~' && !strchr(tmp, '/'))
278                         matches = username_tab_completion(tmp, &num_matches);
279
280                 /* Try to match any executable in our path and everything 
281                  * in the current working directory that matches.  */
282                 if (!matches)
283                         matches = exe_n_cwd_tab_completion(tmp, &num_matches);
284
285                 /* Don't leak memory */
286                 free( matchBuf);
287
288                 /* Did we find exactly one match? */
289                 if (matches && num_matches==1) {
290                         /* write out the matched command */
291                         strncpy(command+pos, matches[0]+pos, strlen(matches[0])-pos);
292                         len=strlen(command);
293                         cursor=len;
294                         xwrite(outputFd, matches[0]+pos, strlen(matches[0])-pos);
295                         break;
296                 }
297         } else {
298                 /* Ok -- the last char was a TAB.  Since they
299                  * just hit TAB again, print a list of all the
300                  * available choices... */
301                 if ( matches && num_matches>0 ) {
302                         int i, col;
303
304                         /* Go to the next line */
305                         xwrite(outputFd, "\n", 1);
306                         /* Print the list of matches */
307                         for (i=0,col=0; i<num_matches; i++) {
308                                 char foo[17];
309                                 sprintf(foo, "%-14s  ", matches[i]);
310                                 col += xwrite(outputFd, foo, strlen(foo));
311                                 if (col > 60 && matches[i+1] != NULL) {
312                                         xwrite(outputFd, "\n", 1);
313                                         col = 0;
314                                 }
315                         }
316                         /* Go to the next line */
317                         xwrite(outputFd, "\n", 1);
318                         /* Rewrite the prompt */
319                         xwrite(outputFd, prompt, strlen(prompt));
320                         /* Rewrite the command */
321                         xwrite(outputFd, command, len);
322                         /* Put the cursor back to where it used to be */
323                         for (cursor=len; cursor > pos; cursor--)
324                                 xwrite(outputFd, "\b", 1);
325                 }
326         }
327 }
328 #endif
329
330 void get_previous_history(struct history **hp, char* command)
331 {
332         free((*hp)->s);
333         (*hp)->s = strdup(command);
334         *hp = (*hp)->p;
335 }
336
337 void get_next_history(struct history **hp, char* command)
338 {
339         free((*hp)->s);
340         (*hp)->s = strdup(command);
341         *hp = (*hp)->n;
342
343         cmdedit_redraw( NULL, hp->s, -2, -2); 
344 }
345
346 #if 0
347 /* prompt : if !=NULL, print the prompt
348  * command: the command line to be displayed
349  * where  : where to display changes from.
350  *          -1 for no change, -2 for new line
351  * cursor : desired location for the cursor.
352  *          -1 for Beginning of line.
353  *          -2 for End of Line, 
354  */
355 static void
356 cmdedit_redraw(char* prompt, char* command, int where, int cursor)
357 {
358         static char* last_command;
359         int cmdedit_width;
360
361         if (where == -2) {
362                 /* Rewrite the prompt and clean up static variables */
363                 xwrite(outputFd, "\n", 1);
364                 if (prompt) {
365                         strcpy(last_command, prompt);
366                         xwrite(outputFd, prompt, strlen(prompt));
367                 } else {
368                         last_command[0] = '\0';
369                         xwrite(outputFd, "# ", 2);
370                 }
371                 cmdedit_width = cmdedit_termw - cmdedit_strlen(prompt);
372         } else if (strcmp(command, last_command) != 0) {
373                 strcpy(last_command, prompt);
374         }
375
376         /* erase old command from command line */
377         len = strlen(command)-strlen(last_command);
378         while (len>0)
379                 input_backspace(command, outputFd, &cursor, &len);
380         input_home(outputFd, &cursor);
381
382         /* Rewrite the command */
383         xwrite(outputFd, command+where, len);
384
385         /* Put the where it is supposed to be */
386         for (cursor=len; cursor > where; cursor--)
387                 xwrite(outputFd, "\b", 1);
388
389         /* write new command */
390         strcpy(command, hp->s);
391         len = strlen(hp->s);
392         xwrite(outputFd, command+where, len);
393         cursor = len;
394 }
395 #endif
396
397 /*
398  * This function is used to grab a character buffer
399  * from the input file descriptor and allows you to
400  * a string with full command editing (sortof like
401  * a mini readline).
402  *
403  * The following standard commands are not implemented:
404  * ESC-b -- Move back one word
405  * ESC-f -- Move forward one word
406  * ESC-d -- Delete back one word
407  * ESC-h -- Delete forward one word
408  * CTL-t -- Transpose two characters
409  *
410  * Furthermore, the "vi" command editing keys are not implemented.
411  *
412  * TODO: implement TAB command completion. :)
413  */
414 extern void cmdedit_read_input(char* prompt, char command[BUFSIZ])
415 {
416
417         int inputFd=fileno(stdin);
418         int outputFd=fileno(stdout);
419         int nr = 0;
420         int len = 0;
421         int j = 0;
422         int cursor = 0;
423         int break_out = 0;
424         int ret = 0;
425         int lastWasTab = FALSE;
426         char c = 0;
427         struct history *hp = his_end;
428
429         memset(command, 0, sizeof(command));
430         if (!reset_term) {
431                 ioctl(inputFd, TCGETA, (void *) &old_term);
432                 memcpy(&new_term, &old_term, sizeof(struct termio));
433
434                 new_term.c_cc[VMIN] = 1;
435                 new_term.c_cc[VTIME] = 0;
436                 new_term.c_lflag &= ~ICANON;    /* unbuffered input */
437                 new_term.c_lflag &= ~ECHO;
438                 reset_term = 1;
439                 ioctl(inputFd, TCSETA, (void *) &new_term);
440         } else {
441                 ioctl(inputFd, TCSETA, (void *) &new_term);
442         }
443
444         memset(command, 0, BUFSIZ);
445
446         while (1) {
447
448                 if ((ret = read(inputFd, &c, 1)) < 1)
449                         return;
450
451                 switch (c) {
452                 case '\n':
453                 case '\r':
454                         /* Enter */
455                         *(command + len++ + 1) = c;
456                         xwrite(outputFd, &c, 1);
457                         break_out = 1;
458                         break;
459                 case 1:
460                         /* Control-a -- Beginning of line */
461                         input_home(outputFd, &cursor);
462                 case 2:
463                         /* Control-b -- Move back one character */
464                         input_backward(outputFd, &cursor);
465                         break;
466                 case 4:
467                         /* Control-d -- Delete one character, or exit 
468                          * if the len=0 and no chars to delete */
469                         if (len == 0) {
470                                 xwrite(outputFd, "exit", 4);
471                                 clean_up_and_die(0);
472                         } else {
473                                 input_delete(command, outputFd, cursor, &len);
474                         }
475                         break;
476                 case 5:
477                         /* Control-e -- End of line */
478                         input_end(outputFd, &cursor, len);
479                         break;
480                 case 6:
481                         /* Control-f -- Move forward one character */
482                         input_forward(outputFd, &cursor, len);
483                         break;
484                 case '\b':
485                 case DEL:
486                         /* control-h and DEL */
487                         input_backspace(command, outputFd, &cursor, &len);
488                         break;
489                 case '\t':
490 #ifdef BB_FEATURE_SH_TAB_COMPLETION
491                         input_tab(command, outputFd, &cursor, &len);
492 #endif
493                         break;
494                 case 14:
495                         /* Control-n -- Get next command in history */
496                         if (hp && hp->n && hp->n->s) {
497                                 get_next_history(&hp, command);
498                                 goto rewrite_line;
499                         } else {
500                                 xwrite(outputFd, "\007", 1);
501                         }
502                         break;
503                 case 16:
504                         /* Control-p -- Get previous command from history */
505                         if (hp && hp->p) {
506                                 get_previous_history(&hp, command);
507                                 goto rewrite_line;
508                         } else {
509                                 xwrite(outputFd, "\007", 1);
510                         }
511                         break;
512                 case ESC:{
513                                 /* escape sequence follows */
514                                 if ((ret = read(inputFd, &c, 1)) < 1)
515                                         return;
516
517                                 if (c == '[') { /* 91 */
518                                         if ((ret = read(inputFd, &c, 1)) < 1)
519                                                 return;
520
521                                         switch (c) {
522                                         case 'A':
523                                                 /* Up Arrow -- Get previous command from history */
524                                                 if (hp && hp->p) {
525                                                         get_previous_history(&hp, command);
526                                                         goto rewrite_line;
527                                                 } else {
528                                                         xwrite(outputFd, "\007", 1);
529                                                 }
530                                                 break;
531                                         case 'B':
532                                                 /* Down Arrow -- Get next command in history */
533                                                 if (hp && hp->n && hp->n->s) {
534                                                         get_next_history(&hp, command);
535                                                         goto rewrite_line;
536                                                 } else {
537                                                         xwrite(outputFd, "\007", 1);
538                                                 }
539                                                 break;
540
541                                                 /* Rewrite the line with the selected history item */
542                                           rewrite_line:
543                                                 /* erase old command from command line */
544                                                 len = strlen(command)-strlen(hp->s);
545                                                 while (len>0)
546                                                         input_backspace(command, outputFd, &cursor, &len);
547                                                 input_home(outputFd, &cursor);
548                                                 
549                                                 /* write new command */
550                                                 strcpy(command, hp->s);
551                                                 len = strlen(hp->s);
552                                                 xwrite(outputFd, command, len);
553                                                 cursor = len;
554                                                 break;
555                                         case 'C':
556                                                 /* Right Arrow -- Move forward one character */
557                                                 input_forward(outputFd, &cursor, len);
558                                                 break;
559                                         case 'D':
560                                                 /* Left Arrow -- Move back one character */
561                                                 input_backward(outputFd, &cursor);
562                                                 break;
563                                         case '3':
564                                                 /* Delete */
565                                                 input_delete(command, outputFd, cursor, &len);
566                                                 break;
567                                         case '1':
568                                                 /* Home (Ctrl-A) */
569                                                 input_home(outputFd, &cursor);
570                                                 break;
571                                         case '4':
572                                                 /* End (Ctrl-E) */
573                                                 input_end(outputFd, &cursor, len);
574                                                 break;
575                                         default:
576                                                 xwrite(outputFd, "\007", 1);
577                                         }
578                                         if (c == '1' || c == '3' || c == '4')
579                                                 if ((ret = read(inputFd, &c, 1)) < 1)
580                                                         return; /* read 126 (~) */
581                                 }
582                                 if (c == 'O') {
583                                         /* 79 */
584                                         if ((ret = read(inputFd, &c, 1)) < 1)
585                                                 return;
586                                         switch (c) {
587                                         case 'H':
588                                                 /* Home (xterm) */
589                                                 input_home(outputFd, &cursor);
590                                                 break;
591                                         case 'F':
592                                                 /* End (xterm) */
593                                                 input_end(outputFd, &cursor, len);
594                                                 break;
595                                         default:
596                                                 xwrite(outputFd, "\007", 1);
597                                         }
598                                 }
599                                 c = 0;
600                                 break;
601                         }
602
603                 default:                                /* If it's regular input, do the normal thing */
604
605                         if (!isprint(c)) {      /* Skip non-printable characters */
606                                 break;
607                         }
608
609                         if (len >= (BUFSIZ - 2))        /* Need to leave space for enter */
610                                 break;
611
612                         len++;
613
614                         if (cursor == (len - 1)) {      /* Append if at the end of the line */
615                                 *(command + cursor) = c;
616                         } else {                        /* Insert otherwise */
617                                 memmove(command + cursor + 1, command + cursor,
618                                                 len - cursor - 1);
619
620                                 *(command + cursor) = c;
621
622                                 for (j = cursor; j < len; j++)
623                                         xwrite(outputFd, command + j, 1);
624                                 for (; j > cursor; j--)
625                                         xwrite(outputFd, "\033[D", 3);
626                         }
627
628                         cursor++;
629                         xwrite(outputFd, &c, 1);
630                         break;
631                 }
632                 if (c == '\t')
633                         lastWasTab = TRUE;
634                 else
635                         lastWasTab = FALSE;
636
637                 if (break_out)                  /* Enter is the command terminator, no more input. */
638                         break;
639         }
640
641         nr = len + 1;
642         ioctl(inputFd, TCSETA, (void *) &old_term);
643         reset_term = 0;
644
645
646         /* Handle command history log */
647         if (*(command)) {
648
649                 struct history *h = his_end;
650
651                 if (!h) {
652                         /* No previous history */
653                         h = his_front = malloc(sizeof(struct history));
654                         h->n = malloc(sizeof(struct history));
655
656                         h->p = NULL;
657                         h->s = strdup(command);
658                         h->n->p = h;
659                         h->n->n = NULL;
660                         h->n->s = NULL;
661                         his_end = h->n;
662                         history_counter++;
663                 } else {
664                         /* Add a new history command */
665                         h->n = malloc(sizeof(struct history));
666
667                         h->n->p = h;
668                         h->n->n = NULL;
669                         h->n->s = NULL;
670                         h->s = strdup(command);
671                         his_end = h->n;
672
673                         /* After max history, remove the oldest command */
674                         if (history_counter >= MAX_HISTORY) {
675
676                                 struct history *p = his_front->n;
677
678                                 p->p = NULL;
679                                 free(his_front->s);
680                                 free(his_front);
681                                 his_front = p;
682                         } else {
683                                 history_counter++;
684                         }
685                 }
686         }
687
688         return;
689 }
690
691 extern void cmdedit_init(void)
692 {
693         atexit(cmdedit_reset_term);
694         signal(SIGINT, clean_up_and_die);
695         signal(SIGQUIT, clean_up_and_die);
696         signal(SIGTERM, clean_up_and_die);
697 }
698 #endif                                                  /* BB_FEATURE_SH_COMMAND_EDITING */