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