2 Copyright (C) 2006-2010 by Jonas Kramer
3 Published under the terms of the GNU General Public License (GPL).
15 #include "interface.h"
17 static void delete(unsigned);
19 char * readline(struct prompt
* setup
) {
20 int eoln
= 0, seq
= 0, histsize
= 0, index
= -1, changed
= !0;
21 static char line
[1024];
24 assert(setup
!= NULL
);
26 /* Print prompt if present. */
28 fputs(setup
->prompt
, stderr
);
30 /* Initialize line (empty or with preset text if given). */
31 memset(line
, 0, sizeof(line
));
33 strncpy(line
, setup
->line
, sizeof(line
) - 1);
34 length
= strlen(line
);
38 /* Count items in history. */
39 for(histsize
= 0; setup
->history
&& setup
->history
[histsize
]; ++histsize
);
43 int key
= fgetc(stdin
);
46 case 8: /* Backspace. */
47 case 127: /* Delete. */
48 /* We don't support moving the cursor from the end of the line
49 * so handle these the same. */
58 /* Call the callback function for completion if present. */
59 if(setup
->callback
!= NULL
) {
60 if(setup
->callback(line
, sizeof(line
), changed
)) {
62 length
= strlen(line
);
63 memset(line
+ length
, 0, sizeof(line
) - length
);
64 fprintf(stderr
, "\r%s%s", setup
->prompt
, line
);
70 case 4: /* EOF (^D) */
71 case 10: /* Line break. */
72 case 13: /* Carriage return (who knows...) */
83 int alpha
= isalpha(line
[length
- 1]);
84 while(length
> 0 && isalpha(line
[length
- 1]) == alpha
) {
93 case 27: /* Escape. */
109 if(key
== 66 && index
< histsize
- 1)
112 if(key
== 65 && index
> -1)
116 memset(line
, 0, length
);
119 if(index
> -1 && index
< histsize
) {
122 setup
->history
[index
],
126 length
= strlen(line
);
136 if(length
< sizeof(line
)) {
137 line
[length
++] = key
;
149 void canon(int enable
) {
151 tcgetattr(fileno(stdin
), & term
);
153 term
.c_lflag
= enable
154 ? term
.c_lflag
| ICANON
| ECHO
155 : term
.c_lflag
& ~(ICANON
| ECHO
);
157 tcsetattr(fileno(stdin
), TCSANOW
, & term
);
160 static void delete(unsigned n
) {
162 fputs("\b \b", stderr
);