Home | History | Annotate | Line # | Download | only in libedit
read.c revision 1.31
      1 /*	$NetBSD: read.c,v 1.31 2004/01/17 17:57:40 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.31 2004/01/17 17:57:40 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 
     61 /* read_init():
     62  *	Initialize the read stuff
     63  */
     64 protected int
     65 read_init(EditLine *el)
     66 {
     67 	/* builtin read_char */
     68 	el->el_read.read_char = read_char;
     69 	return 0;
     70 }
     71 
     72 
     73 /* el_read_setfn():
     74  *	Set the read char function to the one provided.
     75  *	If it is set to EL_BUILTIN_GETCFN, then reset to the builtin one.
     76  */
     77 protected int
     78 el_read_setfn(EditLine *el, el_rfunc_t rc)
     79 {
     80 	el->el_read.read_char = (rc == EL_BUILTIN_GETCFN) ? read_char : rc;
     81 	return 0;
     82 }
     83 
     84 
     85 /* el_read_getfn():
     86  *	return the current read char function, or EL_BUILTIN_GETCFN
     87  *	if it is the default one
     88  */
     89 protected el_rfunc_t
     90 el_read_getfn(EditLine *el)
     91 {
     92        return (el->el_read.read_char == read_char) ?
     93 	    EL_BUILTIN_GETCFN : el->el_read.read_char;
     94 }
     95 
     96 
     97 #ifndef MIN
     98 #define MIN(A,B) ((A) < (B) ? (A) : (B))
     99 #endif
    100 
    101 #ifdef DEBUG_EDIT
    102 private void
    103 read_debug(EditLine *el)
    104 {
    105 
    106 	if (el->el_line.cursor > el->el_line.lastchar)
    107 		(void) fprintf(el->el_errfile, "cursor > lastchar\r\n");
    108 	if (el->el_line.cursor < el->el_line.buffer)
    109 		(void) fprintf(el->el_errfile, "cursor < buffer\r\n");
    110 	if (el->el_line.cursor > el->el_line.limit)
    111 		(void) fprintf(el->el_errfile, "cursor > limit\r\n");
    112 	if (el->el_line.lastchar > el->el_line.limit)
    113 		(void) fprintf(el->el_errfile, "lastchar > limit\r\n");
    114 	if (el->el_line.limit != &el->el_line.buffer[EL_BUFSIZ - 2])
    115 		(void) fprintf(el->el_errfile, "limit != &buffer[EL_BUFSIZ-2]\r\n");
    116 }
    117 #endif /* DEBUG_EDIT */
    118 
    119 
    120 /* read__fixio():
    121  *	Try to recover from a read error
    122  */
    123 /* ARGSUSED */
    124 private int
    125 read__fixio(int fd __attribute__((__unused__)), int e)
    126 {
    127 
    128 	switch (e) {
    129 	case -1:		/* Make sure that the code is reachable */
    130 
    131 #ifdef EWOULDBLOCK
    132 	case EWOULDBLOCK:
    133 #ifndef TRY_AGAIN
    134 #define	TRY_AGAIN
    135 #endif
    136 #endif /* EWOULDBLOCK */
    137 
    138 #if defined(POSIX) && defined(EAGAIN)
    139 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
    140 	case EAGAIN:
    141 #ifndef TRY_AGAIN
    142 #define	TRY_AGAIN
    143 #endif
    144 #endif /* EWOULDBLOCK && EWOULDBLOCK != EAGAIN */
    145 #endif /* POSIX && EAGAIN */
    146 
    147 		e = 0;
    148 #ifdef TRY_AGAIN
    149 #if defined(F_SETFL) && defined(O_NDELAY)
    150 		if ((e = fcntl(fd, F_GETFL, 0)) == -1)
    151 			return (-1);
    152 
    153 		if (fcntl(fd, F_SETFL, e & ~O_NDELAY) == -1)
    154 			return (-1);
    155 		else
    156 			e = 1;
    157 #endif /* F_SETFL && O_NDELAY */
    158 
    159 #ifdef FIONBIO
    160 		{
    161 			int zero = 0;
    162 
    163 			if (ioctl(fd, FIONBIO, (ioctl_t) & zero) == -1)
    164 				return (-1);
    165 			else
    166 				e = 1;
    167 		}
    168 #endif /* FIONBIO */
    169 
    170 #endif /* TRY_AGAIN */
    171 		return (e ? 0 : -1);
    172 
    173 	case EINTR:
    174 		return (0);
    175 
    176 	default:
    177 		return (-1);
    178 	}
    179 }
    180 
    181 
    182 /* read_preread():
    183  *	Try to read the stuff in the input queue;
    184  */
    185 private int
    186 read_preread(EditLine *el)
    187 {
    188 	int chrs = 0;
    189 
    190 	if (el->el_tty.t_mode == ED_IO)
    191 		return (0);
    192 
    193 #ifdef FIONREAD
    194 	(void) ioctl(el->el_infd, FIONREAD, (ioctl_t) & chrs);
    195 	if (chrs > 0) {
    196 		char buf[EL_BUFSIZ];
    197 
    198 		chrs = read(el->el_infd, buf,
    199 		    (size_t) MIN(chrs, EL_BUFSIZ - 1));
    200 		if (chrs > 0) {
    201 			buf[chrs] = '\0';
    202 			el_push(el, buf);
    203 		}
    204 	}
    205 #endif /* FIONREAD */
    206 
    207 	return (chrs > 0);
    208 }
    209 
    210 
    211 /* el_push():
    212  *	Push a macro
    213  */
    214 public void
    215 el_push(EditLine *el, char *str)
    216 {
    217 	c_macro_t *ma = &el->el_chared.c_macro;
    218 
    219 	if (str != NULL && ma->level + 1 < EL_MAXMACRO) {
    220 		ma->level++;
    221 		if ((ma->macro[ma->level] = el_strdup(str)) != NULL)
    222 			return;
    223 		ma->level--;
    224 	}
    225 	term_beep(el);
    226 	term__flush();
    227 }
    228 
    229 
    230 /* read_getcmd():
    231  *	Return next command from the input stream.
    232  */
    233 private int
    234 read_getcmd(EditLine *el, el_action_t *cmdnum, char *ch)
    235 {
    236 	el_action_t cmd;
    237 	int num;
    238 
    239 	do {
    240 		if ((num = el_getc(el, ch)) != 1)	/* if EOF or error */
    241 			return (num);
    242 
    243 #ifdef	KANJI
    244 		if ((*ch & 0200)) {
    245 			el->el_state.metanext = 0;
    246 			cmd = CcViMap[' '];
    247 			break;
    248 		} else
    249 #endif /* KANJI */
    250 
    251 		if (el->el_state.metanext) {
    252 			el->el_state.metanext = 0;
    253 			*ch |= 0200;
    254 		}
    255 		cmd = el->el_map.current[(unsigned char) *ch];
    256 		if (cmd == ED_SEQUENCE_LEAD_IN) {
    257 			key_value_t val;
    258 			switch (key_get(el, ch, &val)) {
    259 			case XK_CMD:
    260 				cmd = val.cmd;
    261 				break;
    262 			case XK_STR:
    263 				el_push(el, val.str);
    264 				break;
    265 #ifdef notyet
    266 			case XK_EXE:
    267 				/* XXX: In the future to run a user function */
    268 				RunCommand(val.str);
    269 				break;
    270 #endif
    271 			default:
    272 				EL_ABORT((el->el_errfile, "Bad XK_ type \n"));
    273 				break;
    274 			}
    275 		}
    276 		if (el->el_map.alt == NULL)
    277 			el->el_map.current = el->el_map.key;
    278 	} while (cmd == ED_SEQUENCE_LEAD_IN);
    279 	*cmdnum = cmd;
    280 	return (OKCMD);
    281 }
    282 
    283 
    284 /* read_char():
    285  *	Read a character from the tty.
    286  */
    287 private int
    288 read_char(EditLine *el, char *cp)
    289 {
    290 	int num_read;
    291 	int tried = 0;
    292 
    293 	while ((num_read = read(el->el_infd, cp, 1)) == -1)
    294 		if (!tried && read__fixio(el->el_infd, errno) == 0)
    295 			tried = 1;
    296 		else {
    297 			*cp = '\0';
    298 			return (-1);
    299 		}
    300 
    301 	return (num_read);
    302 }
    303 
    304 
    305 /* el_getc():
    306  *	Read a character
    307  */
    308 public int
    309 el_getc(EditLine *el, char *cp)
    310 {
    311 	int num_read;
    312 	c_macro_t *ma = &el->el_chared.c_macro;
    313 
    314 	term__flush();
    315 	for (;;) {
    316 		if (ma->level < 0) {
    317 			if (!read_preread(el))
    318 				break;
    319 		}
    320 		if (ma->level < 0)
    321 			break;
    322 
    323 		if (ma->macro[ma->level][ma->offset] == '\0') {
    324 			el_free(ma->macro[ma->level--]);
    325 			ma->offset = 0;
    326 			continue;
    327 		}
    328 		*cp = ma->macro[ma->level][ma->offset++] & 0377;
    329 		if (ma->macro[ma->level][ma->offset] == '\0') {
    330 			/* Needed for QuoteMode On */
    331 			el_free(ma->macro[ma->level--]);
    332 			ma->offset = 0;
    333 		}
    334 		return (1);
    335 	}
    336 
    337 #ifdef DEBUG_READ
    338 	(void) fprintf(el->el_errfile, "Turning raw mode on\n");
    339 #endif /* DEBUG_READ */
    340 	if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */
    341 		return (0);
    342 
    343 #ifdef DEBUG_READ
    344 	(void) fprintf(el->el_errfile, "Reading a character\n");
    345 #endif /* DEBUG_READ */
    346 	num_read = (*el->el_read.read_char)(el, cp);
    347 #ifdef DEBUG_READ
    348 	(void) fprintf(el->el_errfile, "Got it %c\n", *cp);
    349 #endif /* DEBUG_READ */
    350 	return (num_read);
    351 }
    352 
    353 protected void
    354 read_prepare(EditLine *el)
    355 {
    356 	if (el->el_flags & HANDLE_SIGNALS)
    357 		sig_set(el);
    358 	if (el->el_flags & NO_TTY)
    359 		return;
    360 	if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED)
    361 		tty_rawmode(el);
    362 
    363 	/* This is relatively cheap, and things go terribly wrong if
    364 	   we have the wrong size. */
    365 	el_resize(el);
    366 	re_clear_display(el);	/* reset the display stuff */
    367 	ch_reset(el);
    368 	re_refresh(el);		/* print the prompt */
    369 }
    370 
    371 protected void
    372 read_finish(EditLine *el)
    373 {
    374 	if ((el->el_flags & UNBUFFERED) == 0)
    375 		(void) tty_cookedmode(el);
    376 	if (el->el_flags & HANDLE_SIGNALS)
    377 		sig_clr(el);
    378 }
    379 
    380 public const char *
    381 el_gets(EditLine *el, int *nread)
    382 {
    383 	int retval;
    384 	el_action_t cmdnum = 0;
    385 	int num;		/* how many chars we have read at NL */
    386 	char ch;
    387 	int crlf = 0;
    388 #ifdef FIONREAD
    389 	c_macro_t *ma = &el->el_chared.c_macro;
    390 #endif /* FIONREAD */
    391 
    392 	if (el->el_flags & NO_TTY) {
    393 		char *cp = el->el_line.buffer;
    394 		size_t idx;
    395 
    396 		while ((*el->el_read.read_char)(el, cp) == 1) {
    397 			/* make sure there is space for next character */
    398 			if (cp + 1 >= el->el_line.limit) {
    399 				idx = (cp - el->el_line.buffer);
    400 				if (!ch_enlargebufs(el, 2))
    401 					break;
    402 				cp = &el->el_line.buffer[idx];
    403 			}
    404 			cp++;
    405 			if (el->el_flags & UNBUFFERED)
    406 				break;
    407 			if (cp[-1] == '\r' || cp[-1] == '\n')
    408 				break;
    409 		}
    410 
    411 		el->el_line.cursor = el->el_line.lastchar = cp;
    412 		*cp = '\0';
    413 		if (nread)
    414 			*nread = el->el_line.cursor - el->el_line.buffer;
    415 		return (el->el_line.buffer);
    416 	}
    417 
    418 
    419 #ifdef FIONREAD
    420 	if (el->el_tty.t_mode == EX_IO && ma->level < 0) {
    421 		long chrs = 0;
    422 
    423 		(void) ioctl(el->el_infd, FIONREAD, (ioctl_t) & chrs);
    424 		if (chrs == 0) {
    425 			if (tty_rawmode(el) < 0) {
    426 				if (nread)
    427 					*nread = 0;
    428 				return (NULL);
    429 			}
    430 		}
    431 	}
    432 #endif /* FIONREAD */
    433 
    434 	if ((el->el_flags & UNBUFFERED) == 0)
    435 		read_prepare(el);
    436 
    437 	if (el->el_flags & EDIT_DISABLED) {
    438 		char *cp = el->el_line.buffer;
    439 		size_t idx;
    440 
    441 		term__flush();
    442 
    443 		while ((*el->el_read.read_char)(el, cp) == 1) {
    444 			/* make sure there is space next character */
    445 			if (cp + 1 >= el->el_line.limit) {
    446 				idx = (cp - el->el_line.buffer);
    447 				if (!ch_enlargebufs(el, 2))
    448 					break;
    449 				cp = &el->el_line.buffer[idx];
    450 			}
    451 			if (*cp == 4)	/* ought to be stty eof */
    452 				break;
    453 			cp++;
    454 			crlf = cp[-1] == '\r' || cp[-1] == '\n';
    455 			if (el->el_flags & UNBUFFERED)
    456 				break;
    457 			if (crlf)
    458 				break;
    459 		}
    460 
    461 		el->el_line.cursor = el->el_line.lastchar = cp;
    462 		*cp = '\0';
    463 		if (nread)
    464 			*nread = el->el_line.cursor - el->el_line.buffer;
    465 		return (el->el_line.buffer);
    466 	}
    467 
    468 	for (num = OKCMD; num == OKCMD;) {	/* while still editing this
    469 						 * line */
    470 #ifdef DEBUG_EDIT
    471 		read_debug(el);
    472 #endif /* DEBUG_EDIT */
    473 		/* if EOF or error */
    474 		if ((num = read_getcmd(el, &cmdnum, &ch)) != OKCMD) {
    475 #ifdef DEBUG_READ
    476 			(void) fprintf(el->el_errfile,
    477 			    "Returning from el_gets %d\n", num);
    478 #endif /* DEBUG_READ */
    479 			break;
    480 		}
    481 		if ((uint)cmdnum >= el->el_map.nfunc) {	/* BUG CHECK command */
    482 #ifdef DEBUG_EDIT
    483 			(void) fprintf(el->el_errfile,
    484 			    "ERROR: illegal command from key 0%o\r\n", ch);
    485 #endif /* DEBUG_EDIT */
    486 			continue;	/* try again */
    487 		}
    488 		/* now do the real command */
    489 #ifdef DEBUG_READ
    490 		{
    491 			el_bindings_t *b;
    492 			for (b = el->el_map.help; b->name; b++)
    493 				if (b->func == cmdnum)
    494 					break;
    495 			if (b->name)
    496 				(void) fprintf(el->el_errfile,
    497 				    "Executing %s\n", b->name);
    498 			else
    499 				(void) fprintf(el->el_errfile,
    500 				    "Error command = %d\n", cmdnum);
    501 		}
    502 #endif /* DEBUG_READ */
    503 		/* vi redo needs these way down the levels... */
    504 		el->el_state.thiscmd = cmdnum;
    505 		el->el_state.thisch = ch;
    506 		if (el->el_map.type == MAP_VI &&
    507 		    el->el_map.current == el->el_map.key &&
    508 		    el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) {
    509 			if (cmdnum == VI_DELETE_PREV_CHAR &&
    510 			    el->el_chared.c_redo.pos != el->el_chared.c_redo.buf
    511 			    && isprint((unsigned char)el->el_chared.c_redo.pos[-1]))
    512 				el->el_chared.c_redo.pos--;
    513 			else
    514 				*el->el_chared.c_redo.pos++ = ch;
    515 		}
    516 		retval = (*el->el_map.func[cmdnum]) (el, ch);
    517 #ifdef DEBUG_READ
    518 		(void) fprintf(el->el_errfile,
    519 			"Returned state %d\n", retval );
    520 #endif /* DEBUG_READ */
    521 
    522 		/* save the last command here */
    523 		el->el_state.lastcmd = cmdnum;
    524 
    525 		/* use any return value */
    526 		switch (retval) {
    527 		case CC_CURSOR:
    528 			re_refresh_cursor(el);
    529 			break;
    530 
    531 		case CC_REDISPLAY:
    532 			re_clear_lines(el);
    533 			re_clear_display(el);
    534 			/* FALLTHROUGH */
    535 
    536 		case CC_REFRESH:
    537 			re_refresh(el);
    538 			break;
    539 
    540 		case CC_REFRESH_BEEP:
    541 			re_refresh(el);
    542 			term_beep(el);
    543 			break;
    544 
    545 		case CC_NORM:	/* normal char */
    546 			break;
    547 
    548 		case CC_ARGHACK:	/* Suggested by Rich Salz */
    549 			/* <rsalz (at) pineapple.bbn.com> */
    550 			continue;	/* keep going... */
    551 
    552 		case CC_EOF:	/* end of file typed */
    553 			if ((el->el_flags & UNBUFFERED) == 0)
    554 				num = 0;
    555 			else if (num == -1) {
    556 				*el->el_line.lastchar++ = CONTROL('d');
    557 				el->el_line.cursor = el->el_line.lastchar;
    558 				num = 1;
    559 			}
    560 			break;
    561 
    562 		case CC_NEWLINE:	/* normal end of line */
    563 			num = el->el_line.lastchar - el->el_line.buffer;
    564 			break;
    565 
    566 		case CC_FATAL:	/* fatal error, reset to known state */
    567 #ifdef DEBUG_READ
    568 			(void) fprintf(el->el_errfile,
    569 			    "*** editor fatal ERROR ***\r\n\n");
    570 #endif /* DEBUG_READ */
    571 			/* put (real) cursor in a known place */
    572 			re_clear_display(el);	/* reset the display stuff */
    573 			ch_reset(el);	/* reset the input pointers */
    574 			re_refresh(el);	/* print the prompt again */
    575 			break;
    576 
    577 		case CC_ERROR:
    578 		default:	/* functions we don't know about */
    579 #ifdef DEBUG_READ
    580 			(void) fprintf(el->el_errfile,
    581 			    "*** editor ERROR ***\r\n\n");
    582 #endif /* DEBUG_READ */
    583 			term_beep(el);
    584 			term__flush();
    585 			break;
    586 		}
    587 		el->el_state.argument = 1;
    588 		el->el_state.doingarg = 0;
    589 		el->el_chared.c_vcmd.action = NOP;
    590 		if (el->el_flags & UNBUFFERED)
    591 			break;
    592 	}
    593 
    594 	term__flush();		/* flush any buffered output */
    595 	/* make sure the tty is set up correctly */
    596 	if ((el->el_flags & UNBUFFERED) == 0) {
    597 		read_finish(el);
    598 		if (nread)
    599 			*nread = num;
    600 	} else {
    601 		if (nread)
    602 			*nread = el->el_line.lastchar - el->el_line.buffer;
    603 	}
    604 	return (num ? el->el_line.buffer : NULL);
    605 }
    606