xref: /netbsd-src/lib/libedit/read.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: read.c,v 1.41 2008/09/10 15:45:37 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Christos Zoulas of Cornell University.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include "config.h"
36 #if !defined(lint) && !defined(SCCSID)
37 #if 0
38 static char sccsid[] = "@(#)read.c	8.1 (Berkeley) 6/4/93";
39 #else
40 __RCSID("$NetBSD: read.c,v 1.41 2008/09/10 15:45:37 christos Exp $");
41 #endif
42 #endif /* not lint && not SCCSID */
43 
44 /*
45  * read.c: Clean this junk up! This is horrible code.
46  *	   Terminal read functions
47  */
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <unistd.h>
51 #include <stdlib.h>
52 #include "el.h"
53 
54 #define	OKCMD	-1
55 
56 private int	read__fixio(int, int);
57 private int	read_preread(EditLine *);
58 private int	read_char(EditLine *, char *);
59 private int	read_getcmd(EditLine *, el_action_t *, char *);
60 private void	read_pop(c_macro_t *);
61 
62 /* read_init():
63  *	Initialize the read stuff
64  */
65 protected int
66 read_init(EditLine *el)
67 {
68 	/* builtin read_char */
69 	el->el_read.read_char = read_char;
70 	return 0;
71 }
72 
73 
74 /* el_read_setfn():
75  *	Set the read char function to the one provided.
76  *	If it is set to EL_BUILTIN_GETCFN, then reset to the builtin one.
77  */
78 protected int
79 el_read_setfn(EditLine *el, el_rfunc_t rc)
80 {
81 	el->el_read.read_char = (rc == EL_BUILTIN_GETCFN) ? read_char : rc;
82 	return 0;
83 }
84 
85 
86 /* el_read_getfn():
87  *	return the current read char function, or EL_BUILTIN_GETCFN
88  *	if it is the default one
89  */
90 protected el_rfunc_t
91 el_read_getfn(EditLine *el)
92 {
93        return (el->el_read.read_char == read_char) ?
94 	    EL_BUILTIN_GETCFN : el->el_read.read_char;
95 }
96 
97 
98 #ifndef MIN
99 #define MIN(A,B) ((A) < (B) ? (A) : (B))
100 #endif
101 
102 #ifdef DEBUG_EDIT
103 private void
104 read_debug(EditLine *el)
105 {
106 
107 	if (el->el_line.cursor > el->el_line.lastchar)
108 		(void) fprintf(el->el_errfile, "cursor > lastchar\r\n");
109 	if (el->el_line.cursor < el->el_line.buffer)
110 		(void) fprintf(el->el_errfile, "cursor < buffer\r\n");
111 	if (el->el_line.cursor > el->el_line.limit)
112 		(void) fprintf(el->el_errfile, "cursor > limit\r\n");
113 	if (el->el_line.lastchar > el->el_line.limit)
114 		(void) fprintf(el->el_errfile, "lastchar > limit\r\n");
115 	if (el->el_line.limit != &el->el_line.buffer[EL_BUFSIZ - 2])
116 		(void) fprintf(el->el_errfile, "limit != &buffer[EL_BUFSIZ-2]\r\n");
117 }
118 #endif /* DEBUG_EDIT */
119 
120 
121 /* read__fixio():
122  *	Try to recover from a read error
123  */
124 /* ARGSUSED */
125 private int
126 read__fixio(int fd __attribute__((__unused__)), int e)
127 {
128 
129 	switch (e) {
130 	case -1:		/* Make sure that the code is reachable */
131 
132 #ifdef EWOULDBLOCK
133 	case EWOULDBLOCK:
134 #ifndef TRY_AGAIN
135 #define	TRY_AGAIN
136 #endif
137 #endif /* EWOULDBLOCK */
138 
139 #if defined(POSIX) && defined(EAGAIN)
140 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
141 	case EAGAIN:
142 #ifndef TRY_AGAIN
143 #define	TRY_AGAIN
144 #endif
145 #endif /* EWOULDBLOCK && EWOULDBLOCK != EAGAIN */
146 #endif /* POSIX && EAGAIN */
147 
148 		e = 0;
149 #ifdef TRY_AGAIN
150 #if defined(F_SETFL) && defined(O_NDELAY)
151 		if ((e = fcntl(fd, F_GETFL, 0)) == -1)
152 			return (-1);
153 
154 		if (fcntl(fd, F_SETFL, e & ~O_NDELAY) == -1)
155 			return (-1);
156 		else
157 			e = 1;
158 #endif /* F_SETFL && O_NDELAY */
159 
160 #ifdef FIONBIO
161 		{
162 			int zero = 0;
163 
164 			if (ioctl(fd, FIONBIO, (ioctl_t) & zero) == -1)
165 				return (-1);
166 			else
167 				e = 1;
168 		}
169 #endif /* FIONBIO */
170 
171 #endif /* TRY_AGAIN */
172 		return (e ? 0 : -1);
173 
174 	case EINTR:
175 		return (0);
176 
177 	default:
178 		return (-1);
179 	}
180 }
181 
182 
183 /* read_preread():
184  *	Try to read the stuff in the input queue;
185  */
186 private int
187 read_preread(EditLine *el)
188 {
189 	int chrs = 0;
190 
191 	if (el->el_tty.t_mode == ED_IO)
192 		return (0);
193 
194 #ifdef FIONREAD
195 	(void) ioctl(el->el_infd, FIONREAD, (ioctl_t) & chrs);
196 	if (chrs > 0) {
197 		char buf[EL_BUFSIZ];
198 
199 		chrs = read(el->el_infd, buf,
200 		    (size_t) MIN(chrs, EL_BUFSIZ - 1));
201 		if (chrs > 0) {
202 			buf[chrs] = '\0';
203 			el_push(el, buf);
204 		}
205 	}
206 #endif /* FIONREAD */
207 
208 	return (chrs > 0);
209 }
210 
211 
212 /* el_push():
213  *	Push a macro
214  */
215 public void
216 el_push(EditLine *el, char *str)
217 {
218 	c_macro_t *ma = &el->el_chared.c_macro;
219 
220 	if (str != NULL && ma->level + 1 < EL_MAXMACRO) {
221 		ma->level++;
222 		if ((ma->macro[ma->level] = el_strdup(str)) != NULL)
223 			return;
224 		ma->level--;
225 	}
226 	term_beep(el);
227 	term__flush(el);
228 }
229 
230 
231 /* read_getcmd():
232  *	Return next command from the input stream.
233  */
234 private int
235 read_getcmd(EditLine *el, el_action_t *cmdnum, char *ch)
236 {
237 	el_action_t cmd;
238 	int num;
239 
240 	do {
241 		if ((num = el_getc(el, ch)) != 1)	/* if EOF or error */
242 			return (num);
243 
244 #ifdef	KANJI
245 		if ((*ch & 0200)) {
246 			el->el_state.metanext = 0;
247 			cmd = CcViMap[' '];
248 			break;
249 		} else
250 #endif /* KANJI */
251 
252 		if (el->el_state.metanext) {
253 			el->el_state.metanext = 0;
254 			*ch |= 0200;
255 		}
256 		cmd = el->el_map.current[(unsigned char) *ch];
257 		if (cmd == ED_SEQUENCE_LEAD_IN) {
258 			key_value_t val;
259 			switch (key_get(el, ch, &val)) {
260 			case XK_CMD:
261 				cmd = val.cmd;
262 				break;
263 			case XK_STR:
264 				el_push(el, val.str);
265 				break;
266 #ifdef notyet
267 			case XK_EXE:
268 				/* XXX: In the future to run a user function */
269 				RunCommand(val.str);
270 				break;
271 #endif
272 			default:
273 				EL_ABORT((el->el_errfile, "Bad XK_ type \n"));
274 				break;
275 			}
276 		}
277 		if (el->el_map.alt == NULL)
278 			el->el_map.current = el->el_map.key;
279 	} while (cmd == ED_SEQUENCE_LEAD_IN);
280 	*cmdnum = cmd;
281 	return (OKCMD);
282 }
283 
284 
285 /* read_char():
286  *	Read a character from the tty.
287  */
288 private int
289 read_char(EditLine *el, char *cp)
290 {
291 	int num_read;
292 	int tried = 0;
293 
294 	while ((num_read = read(el->el_infd, cp, 1)) == -1)
295 		if (!tried && read__fixio(el->el_infd, errno) == 0)
296 			tried = 1;
297 		else {
298 			*cp = '\0';
299 			return (-1);
300 		}
301 
302 	return (num_read);
303 }
304 
305 /* read_pop():
306  *	Pop a macro from the stack
307  */
308 private void
309 read_pop(c_macro_t *ma)
310 {
311 	int i;
312 
313 	el_free(ma->macro[0]);
314 	for (i = ma->level--; i > 0; i--)
315 		ma->macro[i - 1] = ma->macro[i];
316 	ma->offset = 0;
317 }
318 
319 /* el_getc():
320  *	Read a character
321  */
322 public int
323 el_getc(EditLine *el, char *cp)
324 {
325 	int num_read;
326 	c_macro_t *ma = &el->el_chared.c_macro;
327 
328 	term__flush(el);
329 	for (;;) {
330 		if (ma->level < 0) {
331 			if (!read_preread(el))
332 				break;
333 		}
334 
335 		if (ma->level < 0)
336 			break;
337 
338 		if (ma->macro[0][ma->offset] == '\0') {
339 			read_pop(ma);
340 			continue;
341 		}
342 
343 		*cp = ma->macro[0][ma->offset++] & 0377;
344 
345 		if (ma->macro[0][ma->offset] == '\0') {
346 			/* Needed for QuoteMode On */
347 			read_pop(ma);
348 		}
349 
350 		return (1);
351 	}
352 
353 #ifdef DEBUG_READ
354 	(void) fprintf(el->el_errfile, "Turning raw mode on\n");
355 #endif /* DEBUG_READ */
356 	if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */
357 		return (0);
358 
359 #ifdef DEBUG_READ
360 	(void) fprintf(el->el_errfile, "Reading a character\n");
361 #endif /* DEBUG_READ */
362 	num_read = (*el->el_read.read_char)(el, cp);
363 #ifdef DEBUG_READ
364 	(void) fprintf(el->el_errfile, "Got it %c\n", *cp);
365 #endif /* DEBUG_READ */
366 	return (num_read);
367 }
368 
369 protected void
370 read_prepare(EditLine *el)
371 {
372 	if (el->el_flags & HANDLE_SIGNALS)
373 		sig_set(el);
374 	if (el->el_flags & NO_TTY)
375 		return;
376 	if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED)
377 		tty_rawmode(el);
378 
379 	/* This is relatively cheap, and things go terribly wrong if
380 	   we have the wrong size. */
381 	el_resize(el);
382 	re_clear_display(el);	/* reset the display stuff */
383 	ch_reset(el, 0);
384 	re_refresh(el);		/* print the prompt */
385 
386 	if (el->el_flags & UNBUFFERED)
387 		term__flush(el);
388 }
389 
390 protected void
391 read_finish(EditLine *el)
392 {
393 	if ((el->el_flags & UNBUFFERED) == 0)
394 		(void) tty_cookedmode(el);
395 	if (el->el_flags & HANDLE_SIGNALS)
396 		sig_clr(el);
397 }
398 
399 public const char *
400 el_gets(EditLine *el, int *nread)
401 {
402 	int retval;
403 	el_action_t cmdnum = 0;
404 	int num;		/* how many chars we have read at NL */
405 	char ch;
406 	int crlf = 0;
407 #ifdef FIONREAD
408 	c_macro_t *ma = &el->el_chared.c_macro;
409 #endif /* FIONREAD */
410 
411 	if (el->el_flags & NO_TTY) {
412 		char *cp = el->el_line.buffer;
413 		size_t idx;
414 
415 		while ((*el->el_read.read_char)(el, cp) == 1) {
416 			/* make sure there is space for next character */
417 			if (cp + 1 >= el->el_line.limit) {
418 				idx = (cp - el->el_line.buffer);
419 				if (!ch_enlargebufs(el, 2))
420 					break;
421 				cp = &el->el_line.buffer[idx];
422 			}
423 			cp++;
424 			if (el->el_flags & UNBUFFERED)
425 				break;
426 			if (cp[-1] == '\r' || cp[-1] == '\n')
427 				break;
428 		}
429 
430 		el->el_line.cursor = el->el_line.lastchar = cp;
431 		*cp = '\0';
432 		if (nread)
433 			*nread = el->el_line.cursor - el->el_line.buffer;
434 		return (el->el_line.buffer);
435 	}
436 
437 
438 #ifdef FIONREAD
439 	if (el->el_tty.t_mode == EX_IO && ma->level < 0) {
440 		long chrs = 0;
441 
442 		(void) ioctl(el->el_infd, FIONREAD, (ioctl_t) & chrs);
443 		if (chrs == 0) {
444 			if (tty_rawmode(el) < 0) {
445 				if (nread)
446 					*nread = 0;
447 				return (NULL);
448 			}
449 		}
450 	}
451 #endif /* FIONREAD */
452 
453 	if ((el->el_flags & UNBUFFERED) == 0)
454 		read_prepare(el);
455 
456 	if (el->el_flags & EDIT_DISABLED) {
457 		char *cp;
458 		size_t idx;
459 		if ((el->el_flags & UNBUFFERED) == 0)
460 			cp = el->el_line.buffer;
461 		else
462 			cp = el->el_line.lastchar;
463 
464 		term__flush(el);
465 
466 		while ((*el->el_read.read_char)(el, cp) == 1) {
467 			/* make sure there is space next character */
468 			if (cp + 1 >= el->el_line.limit) {
469 				idx = (cp - el->el_line.buffer);
470 				if (!ch_enlargebufs(el, 2))
471 					break;
472 				cp = &el->el_line.buffer[idx];
473 			}
474 			if (*cp == 4)	/* ought to be stty eof */
475 				break;
476 			cp++;
477 			crlf = cp[-1] == '\r' || cp[-1] == '\n';
478 			if (el->el_flags & UNBUFFERED)
479 				break;
480 			if (crlf)
481 				break;
482 		}
483 
484 		el->el_line.cursor = el->el_line.lastchar = cp;
485 		*cp = '\0';
486 		if (nread)
487 			*nread = el->el_line.cursor - el->el_line.buffer;
488 		return (el->el_line.buffer);
489 	}
490 
491 	for (num = OKCMD; num == OKCMD;) {	/* while still editing this
492 						 * line */
493 #ifdef DEBUG_EDIT
494 		read_debug(el);
495 #endif /* DEBUG_EDIT */
496 		/* if EOF or error */
497 		if ((num = read_getcmd(el, &cmdnum, &ch)) != OKCMD) {
498 #ifdef DEBUG_READ
499 			(void) fprintf(el->el_errfile,
500 			    "Returning from el_gets %d\n", num);
501 #endif /* DEBUG_READ */
502 			break;
503 		}
504 		if ((unsigned int)cmdnum >= el->el_map.nfunc) {	/* BUG CHECK command */
505 #ifdef DEBUG_EDIT
506 			(void) fprintf(el->el_errfile,
507 			    "ERROR: illegal command from key 0%o\r\n", ch);
508 #endif /* DEBUG_EDIT */
509 			continue;	/* try again */
510 		}
511 		/* now do the real command */
512 #ifdef DEBUG_READ
513 		{
514 			el_bindings_t *b;
515 			for (b = el->el_map.help; b->name; b++)
516 				if (b->func == cmdnum)
517 					break;
518 			if (b->name)
519 				(void) fprintf(el->el_errfile,
520 				    "Executing %s\n", b->name);
521 			else
522 				(void) fprintf(el->el_errfile,
523 				    "Error command = %d\n", cmdnum);
524 		}
525 #endif /* DEBUG_READ */
526 		/* vi redo needs these way down the levels... */
527 		el->el_state.thiscmd = cmdnum;
528 		el->el_state.thisch = ch;
529 		if (el->el_map.type == MAP_VI &&
530 		    el->el_map.current == el->el_map.key &&
531 		    el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) {
532 			if (cmdnum == VI_DELETE_PREV_CHAR &&
533 			    el->el_chared.c_redo.pos != el->el_chared.c_redo.buf
534 			    && isprint((unsigned char)el->el_chared.c_redo.pos[-1]))
535 				el->el_chared.c_redo.pos--;
536 			else
537 				*el->el_chared.c_redo.pos++ = ch;
538 		}
539 		retval = (*el->el_map.func[cmdnum]) (el, ch);
540 #ifdef DEBUG_READ
541 		(void) fprintf(el->el_errfile,
542 			"Returned state %d\n", retval );
543 #endif /* DEBUG_READ */
544 
545 		/* save the last command here */
546 		el->el_state.lastcmd = cmdnum;
547 
548 		/* use any return value */
549 		switch (retval) {
550 		case CC_CURSOR:
551 			re_refresh_cursor(el);
552 			break;
553 
554 		case CC_REDISPLAY:
555 			re_clear_lines(el);
556 			re_clear_display(el);
557 			/* FALLTHROUGH */
558 
559 		case CC_REFRESH:
560 			re_refresh(el);
561 			break;
562 
563 		case CC_REFRESH_BEEP:
564 			re_refresh(el);
565 			term_beep(el);
566 			break;
567 
568 		case CC_NORM:	/* normal char */
569 			break;
570 
571 		case CC_ARGHACK:	/* Suggested by Rich Salz */
572 			/* <rsalz@pineapple.bbn.com> */
573 			continue;	/* keep going... */
574 
575 		case CC_EOF:	/* end of file typed */
576 			if ((el->el_flags & UNBUFFERED) == 0)
577 				num = 0;
578 			else if (num == -1) {
579 				*el->el_line.lastchar++ = CONTROL('d');
580 				el->el_line.cursor = el->el_line.lastchar;
581 				num = 1;
582 			}
583 			break;
584 
585 		case CC_NEWLINE:	/* normal end of line */
586 			num = el->el_line.lastchar - el->el_line.buffer;
587 			break;
588 
589 		case CC_FATAL:	/* fatal error, reset to known state */
590 #ifdef DEBUG_READ
591 			(void) fprintf(el->el_errfile,
592 			    "*** editor fatal ERROR ***\r\n\n");
593 #endif /* DEBUG_READ */
594 			/* put (real) cursor in a known place */
595 			re_clear_display(el);	/* reset the display stuff */
596 			ch_reset(el, 1);	/* reset the input pointers */
597 			re_refresh(el);	/* print the prompt again */
598 			break;
599 
600 		case CC_ERROR:
601 		default:	/* functions we don't know about */
602 #ifdef DEBUG_READ
603 			(void) fprintf(el->el_errfile,
604 			    "*** editor ERROR ***\r\n\n");
605 #endif /* DEBUG_READ */
606 			term_beep(el);
607 			term__flush(el);
608 			break;
609 		}
610 		el->el_state.argument = 1;
611 		el->el_state.doingarg = 0;
612 		el->el_chared.c_vcmd.action = NOP;
613 		if (el->el_flags & UNBUFFERED)
614 			break;
615 	}
616 
617 	term__flush(el);		/* flush any buffered output */
618 	/* make sure the tty is set up correctly */
619 	if ((el->el_flags & UNBUFFERED) == 0) {
620 		read_finish(el);
621 		if (nread)
622 			*nread = num;
623 	} else {
624 		if (nread)
625 			*nread = el->el_line.lastchar - el->el_line.buffer;
626 	}
627 	return (num ? el->el_line.buffer : NULL);
628 }
629