xref: /openbsd/lib/libedit/read.c (revision 404b540a)
1 /*	$OpenBSD: read.c,v 1.11 2003/11/25 20:12:38 otto Exp $	*/
2 /*	$NetBSD: read.c,v 1.30 2003/10/18 23:48:42 christos Exp $	*/
3 
4 /*-
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Christos Zoulas of Cornell University.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include "config.h"
37 #if !defined(lint) && !defined(SCCSID)
38 #if 0
39 static char sccsid[] = "@(#)read.c	8.1 (Berkeley) 6/4/93";
40 #else
41 static const char rcsid[] = "$OpenBSD: read.c,v 1.11 2003/11/25 20:12:38 otto Exp $";
42 #endif
43 #endif /* not lint && not SCCSID */
44 
45 /*
46  * read.c: Clean this junk up! This is horrible code.
47  *	   Terminal read functions
48  */
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <unistd.h>
52 #include <stdlib.h>
53 #include "el.h"
54 
55 #define	OKCMD	-1
56 
57 private int	read__fixio(int, int);
58 private int	read_preread(EditLine *);
59 private int	read_char(EditLine *, char *);
60 private int	read_getcmd(EditLine *, el_action_t *, char *);
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();
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 
306 /* el_getc():
307  *	Read a character
308  */
309 public int
310 el_getc(EditLine *el, char *cp)
311 {
312 	int num_read;
313 	c_macro_t *ma = &el->el_chared.c_macro;
314 
315 	term__flush();
316 	for (;;) {
317 		if (ma->level < 0) {
318 			if (!read_preread(el))
319 				break;
320 		}
321 		if (ma->level < 0)
322 			break;
323 
324 		if (ma->macro[ma->level][ma->offset] == '\0') {
325 			el_free(ma->macro[ma->level--]);
326 			ma->offset = 0;
327 			continue;
328 		}
329 		*cp = ma->macro[ma->level][ma->offset++] & 0377;
330 		if (ma->macro[ma->level][ma->offset] == '\0') {
331 			/* Needed for QuoteMode On */
332 			el_free(ma->macro[ma->level--]);
333 			ma->offset = 0;
334 		}
335 		return (1);
336 	}
337 
338 #ifdef DEBUG_READ
339 	(void) fprintf(el->el_errfile, "Turning raw mode on\n");
340 #endif /* DEBUG_READ */
341 	if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */
342 		return (0);
343 
344 #ifdef DEBUG_READ
345 	(void) fprintf(el->el_errfile, "Reading a character\n");
346 #endif /* DEBUG_READ */
347 	num_read = (*el->el_read.read_char)(el, cp);
348 #ifdef DEBUG_READ
349 	(void) fprintf(el->el_errfile, "Got it %c\n", *cp);
350 #endif /* DEBUG_READ */
351 	return (num_read);
352 }
353 
354 protected void
355 read_prepare(EditLine *el)
356 {
357 	if (el->el_flags & HANDLE_SIGNALS)
358 		sig_set(el);
359 	if (el->el_flags & NO_TTY)
360 		return;
361 	if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED)
362 		tty_rawmode(el);
363 
364 	/* This is relatively cheap, and things go terribly wrong if
365 	   we have the wrong size. */
366 	el_resize(el);
367 	re_clear_display(el);	/* reset the display stuff */
368 	ch_reset(el);
369 	re_refresh(el);		/* print the prompt */
370 }
371 
372 protected void
373 read_finish(EditLine *el)
374 {
375 	if ((el->el_flags & UNBUFFERED) == 0)
376 		(void) tty_cookedmode(el);
377 	if (el->el_flags & HANDLE_SIGNALS)
378 		sig_clr(el);
379 }
380 
381 public const char *
382 el_gets(EditLine *el, int *nread)
383 {
384 	int retval;
385 	el_action_t cmdnum = 0;
386 	int num;		/* how many chars we have read at NL */
387 	char ch;
388 	int crlf = 0;
389 #ifdef FIONREAD
390 	c_macro_t *ma = &el->el_chared.c_macro;
391 #endif /* FIONREAD */
392 
393 	if (el->el_flags & NO_TTY) {
394 		char *cp = el->el_line.buffer;
395 		size_t idx;
396 
397 		while ((*el->el_read.read_char)(el, cp) == 1) {
398 			/* make sure there is space for next character */
399 			if (cp + 1 >= el->el_line.limit) {
400 				idx = (cp - el->el_line.buffer);
401 				if (!ch_enlargebufs(el, 2))
402 					break;
403 				cp = &el->el_line.buffer[idx];
404 			}
405 			cp++;
406 			if (el->el_flags & UNBUFFERED)
407 				break;
408 			if (cp[-1] == '\r' || cp[-1] == '\n')
409 				break;
410 		}
411 
412 		el->el_line.cursor = el->el_line.lastchar = cp;
413 		*cp = '\0';
414 		if (nread)
415 			*nread = el->el_line.cursor - el->el_line.buffer;
416 		return (el->el_line.buffer);
417 	}
418 
419 
420 #ifdef FIONREAD
421 	if (el->el_tty.t_mode == EX_IO && ma->level < 0) {
422 		long chrs = 0;
423 
424 		(void) ioctl(el->el_infd, FIONREAD, (ioctl_t) & chrs);
425 		if (chrs == 0) {
426 			if (tty_rawmode(el) < 0) {
427 				if (nread)
428 					*nread = 0;
429 				return (NULL);
430 			}
431 		}
432 	}
433 #endif /* FIONREAD */
434 
435 	if ((el->el_flags & UNBUFFERED) == 0)
436 		read_prepare(el);
437 
438 	if (el->el_flags & EDIT_DISABLED) {
439 		char *cp = el->el_line.buffer;
440 		size_t idx;
441 
442 		term__flush();
443 
444 		while ((*el->el_read.read_char)(el, cp) == 1) {
445 			/* make sure there is space next character */
446 			if (cp + 1 >= el->el_line.limit) {
447 				idx = (cp - el->el_line.buffer);
448 				if (!ch_enlargebufs(el, 2))
449 					break;
450 				cp = &el->el_line.buffer[idx];
451 			}
452 			if (*cp == 4)	/* ought to be stty eof */
453 				break;
454 			cp++;
455 			crlf = cp[-1] == '\r' || cp[-1] == '\n';
456 			if (el->el_flags & UNBUFFERED)
457 				break;
458 			if (crlf)
459 				break;
460 		}
461 
462 		el->el_line.cursor = el->el_line.lastchar = cp;
463 		*cp = '\0';
464 		if (nread)
465 			*nread = el->el_line.cursor - el->el_line.buffer;
466 		return (el->el_line.buffer);
467 	}
468 
469 	for (num = OKCMD; num == OKCMD;) {	/* while still editing this
470 						 * line */
471 #ifdef DEBUG_EDIT
472 		read_debug(el);
473 #endif /* DEBUG_EDIT */
474 		/* if EOF or error */
475 		if ((num = read_getcmd(el, &cmdnum, &ch)) != OKCMD) {
476 #ifdef DEBUG_READ
477 			(void) fprintf(el->el_errfile,
478 			    "Returning from el_gets %d\n", num);
479 #endif /* DEBUG_READ */
480 			break;
481 		}
482 		if ((uint)cmdnum >= el->el_map.nfunc) {	/* BUG CHECK command */
483 #ifdef DEBUG_EDIT
484 			(void) fprintf(el->el_errfile,
485 			    "ERROR: illegal command from key 0%o\r\n", ch);
486 #endif /* DEBUG_EDIT */
487 			continue;	/* try again */
488 		}
489 		/* now do the real command */
490 #ifdef DEBUG_READ
491 		{
492 			el_bindings_t *b;
493 			for (b = el->el_map.help; b->name; b++)
494 				if (b->func == cmdnum)
495 					break;
496 			if (b->name)
497 				(void) fprintf(el->el_errfile,
498 				    "Executing %s\n", b->name);
499 			else
500 				(void) fprintf(el->el_errfile,
501 				    "Error command = %d\n", cmdnum);
502 		}
503 #endif /* DEBUG_READ */
504 		/* vi redo needs these way down the levels... */
505 		el->el_state.thiscmd = cmdnum;
506 		el->el_state.thisch = ch;
507 		if (el->el_map.type == MAP_VI &&
508 		    el->el_map.current == el->el_map.key &&
509 		    el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) {
510 			if (cmdnum == VI_DELETE_PREV_CHAR &&
511 			    el->el_chared.c_redo.pos != el->el_chared.c_redo.buf
512 			    && isprint(el->el_chared.c_redo.pos[-1]))
513 				el->el_chared.c_redo.pos--;
514 			else
515 				*el->el_chared.c_redo.pos++ = ch;
516 		}
517 		retval = (*el->el_map.func[cmdnum]) (el, ch);
518 #ifdef DEBUG_READ
519 		(void) fprintf(el->el_errfile,
520 			"Returned state %d\n", retval );
521 #endif /* DEBUG_READ */
522 
523 		/* save the last command here */
524 		el->el_state.lastcmd = cmdnum;
525 
526 		/* use any return value */
527 		switch (retval) {
528 		case CC_CURSOR:
529 			re_refresh_cursor(el);
530 			break;
531 
532 		case CC_REDISPLAY:
533 			re_clear_lines(el);
534 			re_clear_display(el);
535 			/* FALLTHROUGH */
536 
537 		case CC_REFRESH:
538 			re_refresh(el);
539 			break;
540 
541 		case CC_REFRESH_BEEP:
542 			re_refresh(el);
543 			term_beep(el);
544 			break;
545 
546 		case CC_NORM:	/* normal char */
547 			break;
548 
549 		case CC_ARGHACK:	/* Suggested by Rich Salz */
550 			/* <rsalz@pineapple.bbn.com> */
551 			continue;	/* keep going... */
552 
553 		case CC_EOF:	/* end of file typed */
554 			if ((el->el_flags & UNBUFFERED) == 0)
555 				num = 0;
556 			else if (num == -1) {
557 				*el->el_line.lastchar++ = CTRL('d');
558 				el->el_line.cursor = el->el_line.lastchar;
559 				num = 1;
560 			}
561 			break;
562 
563 		case CC_NEWLINE:	/* normal end of line */
564 			num = el->el_line.lastchar - el->el_line.buffer;
565 			break;
566 
567 		case CC_FATAL:	/* fatal error, reset to known state */
568 #ifdef DEBUG_READ
569 			(void) fprintf(el->el_errfile,
570 			    "*** editor fatal ERROR ***\r\n\n");
571 #endif /* DEBUG_READ */
572 			/* put (real) cursor in a known place */
573 			re_clear_display(el);	/* reset the display stuff */
574 			ch_reset(el);	/* reset the input pointers */
575 			re_refresh(el);	/* print the prompt again */
576 			break;
577 
578 		case CC_ERROR:
579 		default:	/* functions we don't know about */
580 #ifdef DEBUG_READ
581 			(void) fprintf(el->el_errfile,
582 			    "*** editor ERROR ***\r\n\n");
583 #endif /* DEBUG_READ */
584 			term_beep(el);
585 			term__flush();
586 			break;
587 		}
588 		el->el_state.argument = 1;
589 		el->el_state.doingarg = 0;
590 		el->el_chared.c_vcmd.action = NOP;
591 		if (el->el_flags & UNBUFFERED)
592 			break;
593 	}
594 
595 	term__flush();		/* flush any buffered output */
596 	/* make sure the tty is set up correctly */
597 	if ((el->el_flags & UNBUFFERED) == 0) {
598 		read_finish(el);
599 		if (nread)
600 			*nread = num;
601 	} else {
602 		if (nread)
603 			*nread = el->el_line.lastchar - el->el_line.buffer;
604 	}
605 	return (num ? el->el_line.buffer : NULL);
606 }
607