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