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