xref: /csrg-svn/old/more/more.c (revision 29906)
1 /*
2  * Copyright (c) 1980 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #ifndef lint
8 char copyright[] =
9 "@(#) Copyright (c) 1980 Regents of the University of California.\n\
10  All rights reserved.\n";
11 #endif not lint
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)more.c	5.4.1.1 (Berkeley) 10/21/86";
15 #endif not lint
16 
17 /*
18 ** more.c - General purpose tty output filter and file perusal program
19 **
20 **	by Eric Shienbrood, UC Berkeley
21 **
22 **	modified by Geoff Peck, UCB to add underlining, single spacing
23 **	modified by John Foderaro, UCB to add -c and MORE environment variable
24 */
25 
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <sgtty.h>
32 #include <setjmp.h>
33 #include <sys/stat.h>
34 #include <sys/file.h>
35 #include <sys/exec.h>
36 
37 #define HELPFILE	"/usr/lib/more.help"
38 #define VI		"/usr/ucb/vi"
39 
40 #define Fopen(s,m)	(Currline = 0,file_pos=0,fopen(s,m))
41 #define Ftell(f)	file_pos
42 #define Fseek(f,off)	(file_pos=off,fseek(f,off,0))
43 #define Getc(f)		(++file_pos, getc(f))
44 #define Ungetc(c,f)	(--file_pos, ungetc(c,f))
45 
46 #define MBIT	CBREAK
47 #define stty(fd,argp)	ioctl(fd,TIOCSETN,argp)
48 
49 #define TBUFSIZ	1024
50 #define LINSIZ	256
51 #define ctrl(letter)	('letter' & 077)
52 #define RUBOUT	'\177'
53 #define ESC	'\033'
54 #define QUIT	'\034'
55 
56 struct sgttyb	otty, savetty;
57 long		file_pos, file_size;
58 int		fnum, no_intty, no_tty, slow_tty;
59 int		dum_opt, dlines, onquit(), end_it(), chgwinsz();
60 int		onsusp();
61 int		nscroll = 11;	/* Number of lines scrolled by 'd' */
62 int		fold_opt = 1;	/* Fold long lines */
63 int		stop_opt = 1;	/* Stop after form feeds */
64 int		ssp_opt = 0;	/* Suppress white space */
65 int		ul_opt = 1;	/* Underline as best we can */
66 int		promptlen;
67 int		Currline;	/* Line we are currently at */
68 int		startup = 1;
69 int		firstf = 1;
70 int		notell = 1;
71 int		docrterase = 0;
72 int		docrtkill = 0;
73 int		bad_so;	/* True if overwriting does not turn off standout */
74 int		inwait, Pause, errors;
75 int		within;	/* true if we are within a file,
76 			false if we are between files */
77 int		hard, dumb, noscroll, hardtabs, clreol;
78 int		catch_susp;	/* We should catch the SIGTSTP signal */
79 char		**fnames;	/* The list of file names */
80 int		nfiles;		/* Number of files left to process */
81 char		*shell;		/* The name of the shell to use */
82 int		shellp;		/* A previous shell command exists */
83 char		ch;
84 jmp_buf		restore;
85 char		Line[LINSIZ];	/* Line buffer */
86 int		Lpp = 24;	/* lines per page */
87 char		*Clear;		/* clear screen */
88 char		*eraseln;	/* erase line */
89 char		*Senter, *Sexit;/* enter and exit standout mode */
90 char		*ULenter, *ULexit;	/* enter and exit underline mode */
91 char		*chUL;		/* underline character */
92 char		*chBS;		/* backspace character */
93 char		*Home;		/* go to home */
94 char		*cursorm;	/* cursor movement */
95 char		cursorhome[40];	/* contains cursor movement to home */
96 char		*EodClr;	/* clear rest of screen */
97 char		*tgetstr();
98 int		Mcol = 80;	/* number of columns */
99 int		Wrap = 1;	/* set if automargins */
100 int		soglitch;	/* terminal has standout mode glitch */
101 int		ulglitch;	/* terminal has underline mode glitch */
102 int		pstate = 0;	/* current UL state */
103 long		fseek();
104 char		*getenv();
105 struct {
106     long chrctr, line;
107 } context, screen_start;
108 extern char	PC;		/* pad character */
109 extern short	ospeed;
110 
111 
112 main(argc, argv)
113 int argc;
114 char *argv[];
115 {
116     register FILE	*f;
117     register char	*s;
118     register char	*p;
119     register char	ch;
120     register int	left;
121     int			prnames = 0;
122     int			initopt = 0;
123     int			srchopt = 0;
124     int			clearit = 0;
125     int			initline;
126     char		initbuf[80];
127     FILE		*checkf();
128 
129     nfiles = argc;
130     fnames = argv;
131     initterm ();
132     nscroll = Lpp/2 - 1;
133     if (nscroll <= 0)
134 	nscroll = 1;
135     if(s = getenv("MORE")) argscan(s);
136     while (--nfiles > 0) {
137 	if ((ch = (*++fnames)[0]) == '-') {
138 	    argscan(*fnames+1);
139 	}
140 	else if (ch == '+') {
141 	    s = *fnames;
142 	    if (*++s == '/') {
143 		srchopt++;
144 		for (++s, p = initbuf; p < initbuf + 79 && *s != '\0';)
145 		    *p++ = *s++;
146 		*p = '\0';
147 	    }
148 	    else {
149 		initopt++;
150 		for (initline = 0; *s != '\0'; s++)
151 		    if (isdigit (*s))
152 			initline = initline*10 + *s -'0';
153 		--initline;
154 	    }
155 	}
156 	else break;
157     }
158     /* allow clreol only if Home and eraseln and EodClr strings are
159      *  defined, and in that case, make sure we are in noscroll mode
160      */
161     if(clreol)
162     {
163         if((Home == NULL) || (*Home == '\0') ||
164 	   (eraseln == NULL) || (*eraseln == '\0') ||
165            (EodClr == NULL) || (*EodClr == '\0') )
166 	      clreol = 0;
167 	else noscroll = 1;
168     }
169     if (dlines == 0)
170 	dlines = Lpp - (noscroll ? 1 : 2);
171     left = dlines;
172     if (nfiles > 1)
173 	prnames++;
174     if (!no_intty && nfiles == 0) {
175 	fputs("Usage: ",stderr);
176 	fputs(argv[0],stderr);
177 	fputs(" [-dfln] [+linenum | +/pattern] name1 name2 ...\n",stderr);
178 	exit(1);
179     }
180     else
181 	f = stdin;
182     if (!no_tty) {
183 	signal(SIGQUIT, onquit);
184 	signal(SIGINT, end_it);
185 	signal(SIGWINCH, chgwinsz);
186 	if (signal (SIGTSTP, SIG_IGN) == SIG_DFL) {
187 	    signal(SIGTSTP, onsusp);
188 	    catch_susp++;
189 	}
190 	stty (fileno(stderr), &otty);
191     }
192     if (no_intty) {
193 	if (no_tty)
194 	    copy_file (stdin);
195 	else {
196 	    if ((ch = Getc (f)) == '\f')
197 		doclear();
198 	    else {
199 		Ungetc (ch, f);
200 		if (noscroll && (ch != EOF)) {
201 		    if (clreol)
202 			home ();
203 		    else
204 			doclear ();
205 		}
206 	    }
207 	    if (srchopt)
208 	    {
209 		search (initbuf, stdin, 1);
210 		if (noscroll)
211 		    left--;
212 	    }
213 	    else if (initopt)
214 		skiplns (initline, stdin);
215 	    screen (stdin, left);
216 	}
217 	no_intty = 0;
218 	prnames++;
219 	firstf = 0;
220     }
221 
222     while (fnum < nfiles) {
223 	if ((f = checkf (fnames[fnum], &clearit)) != NULL) {
224 	    context.line = context.chrctr = 0;
225 	    Currline = 0;
226 	    if (firstf) setjmp (restore);
227 	    if (firstf) {
228 		firstf = 0;
229 		if (srchopt)
230 		{
231 		    search (initbuf, f, 1);
232 		    if (noscroll)
233 			left--;
234 		}
235 		else if (initopt)
236 		    skiplns (initline, f);
237 	    }
238 	    else if (fnum < nfiles && !no_tty) {
239 		setjmp (restore);
240 		left = command (fnames[fnum], f);
241 	    }
242 	    if (left != 0) {
243 		if ((noscroll || clearit) && (file_size != 0x7fffffffffffffffL))
244 		    if (clreol)
245 			home ();
246 		    else
247 			doclear ();
248 		if (prnames) {
249 		    if (bad_so)
250 			erase (0);
251 		    if (clreol)
252 			cleareol ();
253 		    pr("::::::::::::::");
254 		    if (promptlen > 14)
255 			erase (14);
256 		    printf ("\n");
257 		    if(clreol) cleareol();
258 		    printf("%s\n", fnames[fnum]);
259 		    if(clreol) cleareol();
260 		    printf("::::::::::::::\n", fnames[fnum]);
261 		    if (left > Lpp - 4)
262 			left = Lpp - 4;
263 		}
264 		if (no_tty)
265 		    copy_file (f);
266 		else {
267 		    within++;
268 		    screen(f, left);
269 		    within = 0;
270 		}
271 	    }
272 	    setjmp (restore);
273 	    fflush(stdout);
274 	    fclose(f);
275 	    screen_start.line = screen_start.chrctr = 0L;
276 	    context.line = context.chrctr = 0L;
277 	}
278 	fnum++;
279 	firstf = 0;
280     }
281     reset_tty ();
282     exit(0);
283 }
284 
285 argscan(s)
286 char *s;
287 {
288 	for (dlines = 0; *s != '\0'; s++)
289 	{
290 		switch (*s)
291 		{
292 		  case '0': case '1': case '2':
293 		  case '3': case '4': case '5':
294 		  case '6': case '7': case '8':
295 		  case '9':
296 			dlines = dlines*10 + *s - '0';
297 			break;
298 		  case 'd':
299 			dum_opt = 1;
300 			break;
301 		  case 'l':
302 			stop_opt = 0;
303 			break;
304 		  case 'f':
305 			fold_opt = 0;
306 			break;
307 		  case 'p':
308 			noscroll++;
309 			break;
310 		  case 'c':
311 			clreol++;
312 			break;
313 		  case 's':
314 			ssp_opt = 1;
315 			break;
316 		  case 'u':
317 			ul_opt = 0;
318 			break;
319 		}
320 	}
321 }
322 
323 
324 /*
325 ** Check whether the file named by fs is an ASCII file which the user may
326 ** access.  If it is, return the opened file. Otherwise return NULL.
327 */
328 
329 FILE *
330 checkf (fs, clearfirst)
331 register char *fs;
332 int *clearfirst;
333 {
334     struct stat stbuf;
335     register FILE *f;
336     char c;
337 
338     if (stat (fs, &stbuf) == -1) {
339 	fflush(stdout);
340 	if (clreol)
341 	    cleareol ();
342 	perror(fs);
343 	return (NULL);
344     }
345     if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
346 	printf("\n*** %s: directory ***\n\n", fs);
347 	return (NULL);
348     }
349     if ((f=Fopen(fs, "r")) == NULL) {
350 	fflush(stdout);
351 	perror(fs);
352 	return (NULL);
353     }
354     /* Try to see whether it is an ASCII file */
355     if (magic(f)) {
356 	printf("\n******** %s: Not a text file ********\n\n", fs);
357 	fclose (f);
358 	return (NULL);
359     }
360     c = Getc(f);
361     if (c == '\f')
362 	*clearfirst = 1;
363     else {
364 	*clearfirst = 0;
365 	Ungetc (c, f);
366     }
367     if ((file_size = stbuf.st_size) == 0)
368 	file_size = 0x7fffffffffffffffL;
369     return (f);
370 }
371 
372 /*
373  * Check for file magic numbers. This code would best
374  * be shared with the file(1) program or, perhaps, more
375  * should not try and be so smart?
376  */
377 magic(f)
378     FILE *f;
379 {
380     long magic;
381 
382     magic = getw(f);
383     fseek(f, -sizeof (magic), L_INCR);		/* reset file position */
384     return (magic == 0405 || magic == OMAGIC || magic == NMAGIC ||
385 	magic == 0411 || magic == ZMAGIC || magic == 0177545);
386 }
387 
388 /*
389 ** A real function, for the tputs routine in termlib
390 */
391 
392 putch (ch)
393 char ch;
394 {
395     putchar (ch);
396 }
397 
398 /*
399 ** Print out the contents of the file f, one screenful at a time.
400 */
401 
402 #define STOP -10
403 
404 screen (f, num_lines)
405 register FILE *f;
406 register int num_lines;
407 {
408     register int c;
409     register int nchars;
410     int length;			/* length of current line */
411     static int prev_len = 1;	/* length of previous line */
412 
413     for (;;) {
414 	while (num_lines > 0 && !Pause) {
415 	    if ((nchars = getline (f, &length)) == EOF)
416 	    {
417 		if (clreol)
418 		    clreos();
419 		return;
420 	    }
421 	    if (ssp_opt && length == 0 && prev_len == 0)
422 		continue;
423 	    prev_len = length;
424 	    if (bad_so || (Senter && *Senter == ' ') && promptlen > 0)
425 		erase (0);
426 	    /* must clear before drawing line since tabs on some terminals
427 	     * do not erase what they tab over.
428 	     */
429 	    if (clreol)
430 		cleareol ();
431 	    prbuf (Line, length);
432 	    if (nchars < promptlen)
433 		erase (nchars);	/* erase () sets promptlen to 0 */
434 	    else promptlen = 0;
435 	    /* is this needed?
436 	     * if (clreol)
437 	     *	cleareol();	/* must clear again in case we wrapped *
438 	     */
439 	    if (nchars < Mcol || !fold_opt)
440 		prbuf("\n", 1);	/* will turn off UL if necessary */
441 	    if (nchars == STOP)
442 		break;
443 	    num_lines--;
444 	}
445 	if (pstate) {
446 		tputs(ULexit, 1, putch);
447 		pstate = 0;
448 	}
449 	fflush(stdout);
450 	if ((c = Getc(f)) == EOF)
451 	{
452 	    if (clreol)
453 		clreos ();
454 	    return;
455 	}
456 
457 	if (Pause && clreol)
458 	    clreos ();
459 	Ungetc (c, f);
460 	setjmp (restore);
461 	Pause = 0; startup = 0;
462 	if ((num_lines = command (NULL, f)) == 0)
463 	    return;
464 	if (hard && promptlen > 0)
465 		erase (0);
466 	if (noscroll && num_lines >= dlines)
467 	{
468 	    if (clreol)
469 		home();
470 	    else
471 		doclear ();
472 	}
473 	screen_start.line = Currline;
474 	screen_start.chrctr = Ftell (f);
475     }
476 }
477 
478 /*
479 ** Come here if a quit signal is received
480 */
481 
482 onquit()
483 {
484     signal(SIGQUIT, SIG_IGN);
485     if (!inwait) {
486 	putchar ('\n');
487 	if (!startup) {
488 	    signal(SIGQUIT, onquit);
489 	    longjmp (restore, 1);
490 	}
491 	else
492 	    Pause++;
493     }
494     else if (!dum_opt && notell) {
495 	write (2, "[Use q or Q to quit]", 20);
496 	promptlen += 20;
497 	notell = 0;
498     }
499     signal(SIGQUIT, onquit);
500 }
501 
502 /*
503 ** Come here if a signal for a window size change is received
504 */
505 
506 chgwinsz()
507 {
508     struct winsize win;
509 
510     (void) signal(SIGWINCH, SIG_IGN);
511     if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1) {
512 	if (win.ws_row != 0) {
513 	    Lpp = win.ws_row;
514 	    nscroll = Lpp/2 - 1;
515 	    if (nscroll <= 0)
516 		nscroll = 1;
517 	    dlines = Lpp - (noscroll ? 1 : 2);
518 	}
519 	if (win.ws_col != 0)
520 	    Mcol = win.ws_col;
521     }
522     (void) signal(SIGWINCH, chgwinsz);
523 }
524 
525 /*
526 ** Clean up terminal state and exit. Also come here if interrupt signal received
527 */
528 
529 end_it ()
530 {
531 
532     reset_tty ();
533     if (clreol) {
534 	putchar ('\r');
535 	clreos ();
536 	fflush (stdout);
537     }
538     else if (!clreol && (promptlen > 0)) {
539 	kill_line ();
540 	fflush (stdout);
541     }
542     else
543 	write (2, "\n", 1);
544     _exit(0);
545 }
546 
547 copy_file(f)
548 register FILE *f;
549 {
550     register int c;
551 
552     while ((c = getc(f)) != EOF)
553 	putchar(c);
554 }
555 
556 /* Simplified printf function */
557 
558 printf (fmt, args)
559 register char *fmt;
560 int args;
561 {
562 	register int *argp;
563 	register char ch;
564 	register int ccount;
565 
566 	ccount = 0;
567 	argp = &args;
568 	while (*fmt) {
569 		while ((ch = *fmt++) != '%') {
570 			if (ch == '\0')
571 				return (ccount);
572 			ccount++;
573 			putchar (ch);
574 		}
575 		switch (*fmt++) {
576 		case 'd':
577 			ccount += printd (*argp);
578 			break;
579 		case 's':
580 			ccount += pr ((char *)*argp);
581 			break;
582 		case '%':
583 			ccount++;
584 			argp--;
585 			putchar ('%');
586 			break;
587 		case '0':
588 			return (ccount);
589 		default:
590 			break;
591 		}
592 		++argp;
593 	}
594 	return (ccount);
595 
596 }
597 
598 /*
599 ** Print an integer as a string of decimal digits,
600 ** returning the length of the print representation.
601 */
602 
603 printd (n)
604 int n;
605 {
606     int a, nchars;
607 
608     if (a = n/10)
609 	nchars = 1 + printd(a);
610     else
611 	nchars = 1;
612     putchar (n % 10 + '0');
613     return (nchars);
614 }
615 
616 /* Put the print representation of an integer into a string */
617 static char *sptr;
618 
619 scanstr (n, str)
620 int n;
621 char *str;
622 {
623     sptr = str;
624     Sprintf (n);
625     *sptr = '\0';
626 }
627 
628 Sprintf (n)
629 {
630     int a;
631 
632     if (a = n/10)
633 	Sprintf (a);
634     *sptr++ = n % 10 + '0';
635 }
636 
637 static char bell = ctrl(G);
638 
639 strlen (s)
640 char *s;
641 {
642     register char *p;
643 
644     p = s;
645     while (*p++)
646 	;
647     return (p - s - 1);
648 }
649 
650 /* See whether the last component of the path name "path" is equal to the
651 ** string "string"
652 */
653 
654 tailequ (path, string)
655 char *path;
656 register char *string;
657 {
658 	register char *tail;
659 
660 	tail = path + strlen(path);
661 	while (tail >= path)
662 		if (*(--tail) == '/')
663 			break;
664 	++tail;
665 	while (*tail++ == *string++)
666 		if (*tail == '\0')
667 			return(1);
668 	return(0);
669 }
670 
671 prompt (filename)
672 char *filename;
673 {
674     if (clreol)
675 	cleareol ();
676     else if (promptlen > 0)
677 	kill_line ();
678     if (!hard) {
679 	promptlen = 8;
680 	if (Senter && Sexit) {
681 	    tputs (Senter, 1, putch);
682 	    promptlen += (2 * soglitch);
683 	}
684 	if (clreol)
685 	    cleareol ();
686 	pr("--More--");
687 	if (filename != NULL) {
688 	    promptlen += printf ("(Next file: %s)", filename);
689 	}
690 	else if (!no_intty) {
691 	    promptlen += printf ("(%d%%)", (int)((file_pos * 100) / file_size));
692 	}
693 	if (dum_opt) {
694 	    promptlen += pr("[Press space to continue, 'q' to quit.]");
695 	}
696 	if (Senter && Sexit)
697 	    tputs (Sexit, 1, putch);
698 	if (clreol)
699 	    clreos ();
700 	fflush(stdout);
701     }
702     else
703 	write (2, &bell, 1);
704     inwait++;
705 }
706 
707 /*
708 ** Get a logical line
709 */
710 
711 getline(f, length)
712 register FILE *f;
713 int *length;
714 {
715     register int	c;
716     register char	*p;
717     register int	column;
718     static int		colflg;
719 
720     p = Line;
721     column = 0;
722     c = Getc (f);
723     if (colflg && c == '\n') {
724 	Currline++;
725 	c = Getc (f);
726     }
727     while (p < &Line[LINSIZ - 1]) {
728 	if (c == EOF) {
729 	    if (p > Line) {
730 		*p = '\0';
731 		*length = p - Line;
732 		return (column);
733 	    }
734 	    *length = p - Line;
735 	    return (EOF);
736 	}
737 	if (c == '\n') {
738 	    Currline++;
739 	    break;
740 	}
741 	*p++ = c;
742 	if (c == '\t')
743 	    if (hardtabs && column < promptlen && !hard) {
744 		if (eraseln && !dumb) {
745 		    column = 1 + (column | 7);
746 		    tputs (eraseln, 1, putch);
747 		    promptlen = 0;
748 		}
749 		else {
750 		    for (--p; column & 7 && p < &Line[LINSIZ - 1]; column++) {
751 			*p++ = ' ';
752 		    }
753 		    if (column >= promptlen) promptlen = 0;
754 		}
755 	    }
756 	    else
757 		column = 1 + (column | 7);
758 	else if (c == '\b' && column > 0)
759 	    column--;
760 	else if (c == '\r')
761 	    column = 0;
762 	else if (c == '\f' && stop_opt) {
763 		p[-1] = '^';
764 		*p++ = 'L';
765 		column += 2;
766 		Pause++;
767 	}
768 	else if (c == EOF) {
769 	    *length = p - Line;
770 	    return (column);
771 	}
772 	else if (c >= ' ' && c != RUBOUT)
773 	    column++;
774 	if (column >= Mcol && fold_opt) break;
775 	c = Getc (f);
776     }
777     if (column >= Mcol && Mcol > 0) {
778 	if (!Wrap) {
779 	    *p++ = '\n';
780 	}
781     }
782     colflg = column == Mcol && fold_opt;
783     *length = p - Line;
784     *p = 0;
785     return (column);
786 }
787 
788 /*
789 ** Erase the rest of the prompt, assuming we are starting at column col.
790 */
791 
792 erase (col)
793 register int col;
794 {
795 
796     if (promptlen == 0)
797 	return;
798     if (hard) {
799 	putchar ('\n');
800     }
801     else {
802 	if (col == 0)
803 	    putchar ('\r');
804 	if (!dumb && eraseln)
805 	    tputs (eraseln, 1, putch);
806 	else
807 	    for (col = promptlen - col; col > 0; col--)
808 		putchar (' ');
809     }
810     promptlen = 0;
811 }
812 
813 /*
814 ** Erase the current line entirely
815 */
816 
817 kill_line ()
818 {
819     erase (0);
820     if (!eraseln || dumb) putchar ('\r');
821 }
822 
823 /*
824  * force clear to end of line
825  */
826 cleareol()
827 {
828     tputs(eraseln, 1, putch);
829 }
830 
831 clreos()
832 {
833     tputs(EodClr, 1, putch);
834 }
835 
836 /*
837 **  Print string and return number of characters
838 */
839 
840 pr(s1)
841 char	*s1;
842 {
843     register char	*s;
844     register char	c;
845 
846     for (s = s1; c = *s++; )
847 	putchar(c);
848     return (s - s1 - 1);
849 }
850 
851 
852 /* Print a buffer of n characters */
853 
854 prbuf (s, n)
855 register char *s;
856 register int n;
857 {
858     register char c;			/* next output character */
859     register int state;			/* next output char's UL state */
860 #define wouldul(s,n)	((n) >= 2 && (((s)[0] == '_' && (s)[1] == '\b') || ((s)[1] == '\b' && (s)[2] == '_')))
861 
862     while (--n >= 0)
863 	if (!ul_opt)
864 	    putchar (*s++);
865 	else {
866 	    if (*s == ' ' && pstate == 0 && ulglitch && wouldul(s+1, n-1)) {
867 		s++;
868 		continue;
869 	    }
870 	    if (state = wouldul(s, n)) {
871 		c = (*s == '_')? s[2] : *s ;
872 		n -= 2;
873 		s += 3;
874 	    } else
875 		c = *s++;
876 	    if (state != pstate) {
877 		if (c == ' ' && state == 0 && ulglitch && wouldul(s, n-1))
878 		    state = 1;
879 		else
880 		    tputs(state ? ULenter : ULexit, 1, putch);
881 	    }
882 	    if (c != ' ' || pstate == 0 || state != 0 || ulglitch == 0)
883 	        putchar(c);
884 	    if (state && *chUL) {
885 		pr(chBS);
886 		tputs(chUL, 1, putch);
887 	    }
888 	    pstate = state;
889 	}
890 }
891 
892 /*
893 **  Clear the screen
894 */
895 
896 doclear()
897 {
898     if (Clear && !hard) {
899 	tputs(Clear, 1, putch);
900 
901 	/* Put out carriage return so that system doesn't
902 	** get confused by escape sequences when expanding tabs
903 	*/
904 	putchar ('\r');
905 	promptlen = 0;
906     }
907 }
908 
909 /*
910  * Go to home position
911  */
912 home()
913 {
914     tputs(Home,1,putch);
915 }
916 
917 static int lastcmd, lastarg, lastp;
918 static int lastcolon;
919 char shell_line[132];
920 
921 /*
922 ** Read a command and do it. A command consists of an optional integer
923 ** argument followed by the command character.  Return the number of lines
924 ** to display in the next screenful.  If there is nothing more to display
925 ** in the current file, zero is returned.
926 */
927 
928 command (filename, f)
929 char *filename;
930 register FILE *f;
931 {
932     register int nlines;
933     register int retval;
934     register char c;
935     char colonch;
936     FILE *helpf;
937     int done;
938     char comchar, cmdbuf[80], *p;
939 
940 #define ret(val) retval=val;done++;break
941 
942     done = 0;
943     if (!errors)
944 	prompt (filename);
945     else
946 	errors = 0;
947     if (MBIT == RAW && slow_tty) {
948 	otty.sg_flags |= MBIT;
949 	stty(fileno(stderr), &otty);
950     }
951     for (;;) {
952 	nlines = number (&comchar);
953 	lastp = colonch = 0;
954 	if (comchar == '.') {	/* Repeat last command */
955 		lastp++;
956 		comchar = lastcmd;
957 		nlines = lastarg;
958 		if (lastcmd == ':')
959 			colonch = lastcolon;
960 	}
961 	lastcmd = comchar;
962 	lastarg = nlines;
963 	if (comchar == otty.sg_erase) {
964 	    kill_line ();
965 	    prompt (filename);
966 	    continue;
967 	}
968 	switch (comchar) {
969 	case ':':
970 	    retval = colon (filename, colonch, nlines);
971 	    if (retval >= 0)
972 		done++;
973 	    break;
974 	case 'b':
975 	case ctrl(B):
976 	    {
977 		register int initline;
978 
979 		if (no_intty) {
980 		    write(2, &bell, 1);
981 		    return (-1);
982 		}
983 
984 		if (nlines == 0) nlines++;
985 
986 		putchar ('\r');
987 		erase (0);
988 		printf ("\n");
989 		if (clreol)
990 			cleareol ();
991 		printf ("...back %d page", nlines);
992 		if (nlines > 1)
993 			pr ("s\n");
994 		else
995 			pr ("\n");
996 
997 		if (clreol)
998 			cleareol ();
999 		pr ("\n");
1000 
1001 		initline = Currline - dlines * (nlines + 1);
1002 		if (! noscroll)
1003 		    --initline;
1004 		if (initline < 0) initline = 0;
1005 		Fseek(f, 0L);
1006 		Currline = 0;	/* skiplns() will make Currline correct */
1007 		skiplns(initline, f);
1008 		if (! noscroll) {
1009 		    ret(dlines + 1);
1010 		}
1011 		else {
1012 		    ret(dlines);
1013 		}
1014 	    }
1015 	case ' ':
1016 	case 'z':
1017 	    if (nlines == 0) nlines = dlines;
1018 	    else if (comchar == 'z') dlines = nlines;
1019 	    ret (nlines);
1020 	case 'd':
1021 	case ctrl(D):
1022 	    if (nlines != 0) nscroll = nlines;
1023 	    ret (nscroll);
1024 	case 'q':
1025 	case 'Q':
1026 	    end_it ();
1027 	case 's':
1028 	case 'f':
1029 	    if (nlines == 0) nlines++;
1030 	    if (comchar == 'f')
1031 		nlines *= dlines;
1032 	    putchar ('\r');
1033 	    erase (0);
1034 	    printf ("\n");
1035 	    if (clreol)
1036 		cleareol ();
1037 	    printf ("...skipping %d line", nlines);
1038 	    if (nlines > 1)
1039 		pr ("s\n");
1040 	    else
1041 		pr ("\n");
1042 
1043 	    if (clreol)
1044 		cleareol ();
1045 	    pr ("\n");
1046 
1047 	    while (nlines > 0) {
1048 		while ((c = Getc (f)) != '\n')
1049 		    if (c == EOF) {
1050 			retval = 0;
1051 			done++;
1052 			goto endsw;
1053 		    }
1054 		    Currline++;
1055 		    nlines--;
1056 	    }
1057 	    ret (dlines);
1058 	case '\n':
1059 	    if (nlines != 0)
1060 		dlines = nlines;
1061 	    else
1062 		nlines = 1;
1063 	    ret (nlines);
1064 	case '\f':
1065 	    if (!no_intty) {
1066 		doclear ();
1067 		Fseek (f, screen_start.chrctr);
1068 		Currline = screen_start.line;
1069 		ret (dlines);
1070 	    }
1071 	    else {
1072 		write (2, &bell, 1);
1073 		break;
1074 	    }
1075 	case '\'':
1076 	    if (!no_intty) {
1077 		kill_line ();
1078 		pr ("\n***Back***\n\n");
1079 		Fseek (f, context.chrctr);
1080 		Currline = context.line;
1081 		ret (dlines);
1082 	    }
1083 	    else {
1084 		write (2, &bell, 1);
1085 		break;
1086 	    }
1087 	case '=':
1088 	    kill_line ();
1089 	    promptlen = printd (Currline);
1090 	    fflush (stdout);
1091 	    break;
1092 	case 'n':
1093 	    lastp++;
1094 	case '/':
1095 	    if (nlines == 0) nlines++;
1096 	    kill_line ();
1097 	    pr ("/");
1098 	    promptlen = 1;
1099 	    fflush (stdout);
1100 	    if (lastp) {
1101 		write (2,"\r", 1);
1102 		search (NULL, f, nlines);	/* Use previous r.e. */
1103 	    }
1104 	    else {
1105 		ttyin (cmdbuf, 78, '/');
1106 		write (2, "\r", 1);
1107 		search (cmdbuf, f, nlines);
1108 	    }
1109 	    ret (dlines-1);
1110 	case '!':
1111 	    do_shell (filename);
1112 	    break;
1113 	case '?':
1114 	case 'h':
1115 	    if ((helpf = fopen (HELPFILE, "r")) == NULL)
1116 		error ("Can't open help file");
1117 	    if (noscroll) doclear ();
1118 	    copy_file (helpf);
1119 	    fclose (helpf);
1120 	    prompt (filename);
1121 	    break;
1122 	case 'v':	/* This case should go right before default */
1123 	    if (!no_intty) {
1124 		kill_line ();
1125 		cmdbuf[0] = '+';
1126 		scanstr (Currline - dlines < 0 ? 0
1127 				: Currline - (dlines + 1) / 2, &cmdbuf[1]);
1128 		pr ("vi "); pr (cmdbuf); putchar (' '); pr (fnames[fnum]);
1129 		execute (filename, VI, "vi", cmdbuf, fnames[fnum], 0);
1130 		break;
1131 	    }
1132 	default:
1133 	    if (dum_opt) {
1134    		kill_line ();
1135 		if (Senter && Sexit) {
1136 		    tputs (Senter, 1, putch);
1137 		    promptlen = pr ("[Press 'h' for instructions.]") + (2 * soglitch);
1138 		    tputs (Sexit, 1, putch);
1139 		}
1140 		else
1141 		    promptlen = pr ("[Press 'h' for instructions.]");
1142 		fflush (stdout);
1143 	    }
1144 	    else
1145 		write (2, &bell, 1);
1146 	    break;
1147 	}
1148 	if (done) break;
1149     }
1150     putchar ('\r');
1151 endsw:
1152     inwait = 0;
1153     notell++;
1154     if (MBIT == RAW && slow_tty) {
1155 	otty.sg_flags &= ~MBIT;
1156 	stty(fileno(stderr), &otty);
1157     }
1158     return (retval);
1159 }
1160 
1161 char ch;
1162 
1163 /*
1164  * Execute a colon-prefixed command.
1165  * Returns <0 if not a command that should cause
1166  * more of the file to be printed.
1167  */
1168 
1169 colon (filename, cmd, nlines)
1170 char *filename;
1171 int cmd;
1172 int nlines;
1173 {
1174 	if (cmd == 0)
1175 		ch = readch ();
1176 	else
1177 		ch = cmd;
1178 	lastcolon = ch;
1179 	switch (ch) {
1180 	case 'f':
1181 		kill_line ();
1182 		if (!no_intty)
1183 			promptlen = printf ("\"%s\" line %d", fnames[fnum], Currline);
1184 		else
1185 			promptlen = printf ("[Not a file] line %d", Currline);
1186 		fflush (stdout);
1187 		return (-1);
1188 	case 'n':
1189 		if (nlines == 0) {
1190 			if (fnum >= nfiles - 1)
1191 				end_it ();
1192 			nlines++;
1193 		}
1194 		putchar ('\r');
1195 		erase (0);
1196 		skipf (nlines);
1197 		return (0);
1198 	case 'p':
1199 		if (no_intty) {
1200 			write (2, &bell, 1);
1201 			return (-1);
1202 		}
1203 		putchar ('\r');
1204 		erase (0);
1205 		if (nlines == 0)
1206 			nlines++;
1207 		skipf (-nlines);
1208 		return (0);
1209 	case '!':
1210 		do_shell (filename);
1211 		return (-1);
1212 	case 'q':
1213 	case 'Q':
1214 		end_it ();
1215 	default:
1216 		write (2, &bell, 1);
1217 		return (-1);
1218 	}
1219 }
1220 
1221 /*
1222 ** Read a decimal number from the terminal. Set cmd to the non-digit which
1223 ** terminates the number.
1224 */
1225 
1226 number(cmd)
1227 char *cmd;
1228 {
1229 	register int i;
1230 
1231 	i = 0; ch = otty.sg_kill;
1232 	for (;;) {
1233 		ch = readch ();
1234 		if (ch >= '0' && ch <= '9')
1235 			i = i*10 + ch - '0';
1236 		else if (ch == otty.sg_kill)
1237 			i = 0;
1238 		else {
1239 			*cmd = ch;
1240 			break;
1241 		}
1242 	}
1243 	return (i);
1244 }
1245 
1246 do_shell (filename)
1247 char *filename;
1248 {
1249 	char cmdbuf[80];
1250 
1251 	kill_line ();
1252 	pr ("!");
1253 	fflush (stdout);
1254 	promptlen = 1;
1255 	if (lastp)
1256 		pr (shell_line);
1257 	else {
1258 		ttyin (cmdbuf, 78, '!');
1259 		if (expand (shell_line, cmdbuf)) {
1260 			kill_line ();
1261 			promptlen = printf ("!%s", shell_line);
1262 		}
1263 	}
1264 	fflush (stdout);
1265 	write (2, "\n", 1);
1266 	promptlen = 0;
1267 	shellp = 1;
1268 	execute (filename, shell, shell, "-c", shell_line, 0);
1269 }
1270 
1271 /*
1272 ** Search for nth ocurrence of regular expression contained in buf in the file
1273 */
1274 
1275 search (buf, file, n)
1276 char buf[];
1277 FILE *file;
1278 register int n;
1279 {
1280     long startline = Ftell (file);
1281     register long line1 = startline;
1282     register long line2 = startline;
1283     register long line3 = startline;
1284     register int lncount;
1285     int saveln, rv, re_exec();
1286     char *s, *re_comp();
1287 
1288     context.line = saveln = Currline;
1289     context.chrctr = startline;
1290     lncount = 0;
1291     if ((s = re_comp (buf)) != 0)
1292 	error (s);
1293     while (!feof (file)) {
1294 	line3 = line2;
1295 	line2 = line1;
1296 	line1 = Ftell (file);
1297 	rdline (file);
1298 	lncount++;
1299 	if ((rv = re_exec (Line)) == 1)
1300 		if (--n == 0) {
1301 		    if (lncount > 3 || (lncount > 1 && no_intty))
1302 		    {
1303 			pr ("\n");
1304 			if (clreol)
1305 			    cleareol ();
1306 			pr("...skipping\n");
1307 		    }
1308 		    if (!no_intty) {
1309 			Currline -= (lncount >= 3 ? 3 : lncount);
1310 			Fseek (file, line3);
1311 			if (noscroll)
1312 			    if (clreol) {
1313 				home ();
1314 				cleareol ();
1315 			    }
1316 			    else
1317 				doclear ();
1318 		    }
1319 		    else {
1320 			kill_line ();
1321 			if (noscroll)
1322 			    if (clreol) {
1323 			        home ();
1324 			        cleareol ();
1325 			    }
1326 			    else
1327 				doclear ();
1328 			pr (Line);
1329 			putchar ('\n');
1330 		    }
1331 		    break;
1332 		}
1333 	else if (rv == -1)
1334 	    error ("Regular expression botch");
1335     }
1336     if (feof (file)) {
1337 	if (!no_intty) {
1338 	    file->_flag &= ~_IOEOF; /* why doesn't fseek do this ??!!??! */
1339 	    Currline = saveln;
1340 	    Fseek (file, startline);
1341 	}
1342 	else {
1343 	    pr ("\nPattern not found\n");
1344 	    end_it ();
1345 	}
1346 	error ("Pattern not found");
1347     }
1348 }
1349 
1350 execute (filename, cmd, args)
1351 char *filename;
1352 char *cmd, *args;
1353 {
1354 	int id;
1355 	int n;
1356 
1357 	fflush (stdout);
1358 	reset_tty ();
1359 	for (n = 10; (id = fork ()) < 0 && n > 0; n--)
1360 	    sleep (5);
1361 	if (id == 0) {
1362 	    if (!isatty(0)) {
1363 		close(0);
1364 		open("/dev/tty", 0);
1365 	    }
1366 	    execv (cmd, &args);
1367 	    write (2, "exec failed\n", 12);
1368 	    exit (1);
1369 	}
1370 	if (id > 0) {
1371 	    signal (SIGINT, SIG_IGN);
1372 	    signal (SIGQUIT, SIG_IGN);
1373 	    if (catch_susp)
1374 		signal(SIGTSTP, SIG_DFL);
1375 	    while (wait(0) > 0);
1376 	    signal (SIGINT, end_it);
1377 	    signal (SIGQUIT, onquit);
1378 	    if (catch_susp)
1379 		signal(SIGTSTP, onsusp);
1380 	} else
1381 	    write(2, "can't fork\n", 11);
1382 	set_tty ();
1383 	pr ("------------------------\n");
1384 	prompt (filename);
1385 }
1386 /*
1387 ** Skip n lines in the file f
1388 */
1389 
1390 skiplns (n, f)
1391 register int n;
1392 register FILE *f;
1393 {
1394     register char c;
1395 
1396     while (n > 0) {
1397 	while ((c = Getc (f)) != '\n')
1398 	    if (c == EOF)
1399 		return;
1400 	    n--;
1401 	    Currline++;
1402     }
1403 }
1404 
1405 /*
1406 ** Skip nskip files in the file list (from the command line). Nskip may be
1407 ** negative.
1408 */
1409 
1410 skipf (nskip)
1411 register int nskip;
1412 {
1413     if (nskip == 0) return;
1414     if (nskip > 0) {
1415 	if (fnum + nskip > nfiles - 1)
1416 	    nskip = nfiles - fnum - 1;
1417     }
1418     else if (within)
1419 	++fnum;
1420     fnum += nskip;
1421     if (fnum < 0)
1422 	fnum = 0;
1423     pr ("\n...Skipping ");
1424     pr ("\n");
1425     if (clreol)
1426 	cleareol ();
1427     pr ("...Skipping ");
1428     pr (nskip > 0 ? "to file " : "back to file ");
1429     pr (fnames[fnum]);
1430     pr ("\n");
1431     if (clreol)
1432 	cleareol ();
1433     pr ("\n");
1434     --fnum;
1435 }
1436 
1437 /*----------------------------- Terminal I/O -------------------------------*/
1438 
1439 initterm ()
1440 {
1441     char	buf[TBUFSIZ];
1442     static char	clearbuf[TBUFSIZ];
1443     char	*clearptr, *padstr;
1444     int		ldisc;
1445     int		lmode;
1446     char	*term;
1447     int		tgrp;
1448     struct winsize win;
1449 
1450 retry:
1451     if (!(no_tty = gtty(fileno(stdout), &otty))) {
1452 	if (ioctl(fileno(stdout), TIOCLGET, &lmode) < 0) {
1453 	    perror("TIOCLGET");
1454 	    exit(1);
1455 	}
1456 	docrterase = ((lmode & LCRTERA) != 0);
1457 	docrtkill = ((lmode & LCRTKIL) != 0);
1458 	/*
1459 	 * Wait until we're in the foreground before we save the
1460 	 * the terminal modes.
1461 	 */
1462 	if (ioctl(fileno(stdout), TIOCGPGRP, &tgrp) < 0) {
1463 	    perror("TIOCGPGRP");
1464 	    exit(1);
1465 	}
1466 	if (tgrp != getpgrp(0)) {
1467 	    kill(0, SIGTTOU);
1468 	    goto retry;
1469 	}
1470 	if ((term = getenv("TERM")) == 0 || tgetent(buf, term) <= 0) {
1471 	    dumb++; ul_opt = 0;
1472 	}
1473 	else {
1474 	    if (ioctl(fileno(stdout), TIOCGWINSZ, &win) < 0) {
1475 		Lpp = tgetnum("li");
1476 		Mcol = tgetnum("co");
1477 	    } else {
1478 		if ((Lpp = win.ws_row) == 0)
1479 		    Lpp = tgetnum("li");
1480 		if ((Mcol = win.ws_col) == 0)
1481 		    Mcol = tgetnum("co");
1482 	    }
1483 	    if ((Lpp <= 0) || tgetflag("hc")) {
1484 		hard++;	/* Hard copy terminal */
1485 		Lpp = 24;
1486 	    }
1487 	    if (Mcol <= 0)
1488 		Mcol = 80;
1489 
1490 	    if (tailequ (fnames[0], "page") || !hard && tgetflag("ns"))
1491 		noscroll++;
1492 	    Wrap = tgetflag("am");
1493 	    bad_so = tgetflag ("xs");
1494 	    clearptr = clearbuf;
1495 	    eraseln = tgetstr("ce",&clearptr);
1496 	    Clear = tgetstr("cl", &clearptr);
1497 	    Senter = tgetstr("so", &clearptr);
1498 	    Sexit = tgetstr("se", &clearptr);
1499 	    if ((soglitch = tgetnum("sg")) < 0)
1500 		soglitch = 0;
1501 
1502 	    /*
1503 	     *  Set up for underlining:  some terminals don't need it;
1504 	     *  others have start/stop sequences, still others have an
1505 	     *  underline char sequence which is assumed to move the
1506 	     *  cursor forward one character.  If underline sequence
1507 	     *  isn't available, settle for standout sequence.
1508 	     */
1509 
1510 	    if (tgetflag("ul") || tgetflag("os"))
1511 		ul_opt = 0;
1512 	    if ((chUL = tgetstr("uc", &clearptr)) == NULL )
1513 		chUL = "";
1514 	    if (((ULenter = tgetstr("us", &clearptr)) == NULL ||
1515 	         (ULexit = tgetstr("ue", &clearptr)) == NULL) && !*chUL) {
1516 	        if ((ULenter = Senter) == NULL || (ULexit = Sexit) == NULL) {
1517 			ULenter = "";
1518 			ULexit = "";
1519 		} else
1520 			ulglitch = soglitch;
1521 	    } else {
1522 		if ((ulglitch = tgetnum("ug")) < 0)
1523 		    ulglitch = 0;
1524 	    }
1525 
1526 	    if (padstr = tgetstr("pc", &clearptr))
1527 		PC = *padstr;
1528 	    Home = tgetstr("ho",&clearptr);
1529 	    if (Home == 0 || *Home == '\0')
1530 	    {
1531 		if ((cursorm = tgetstr("cm", &clearptr)) != NULL) {
1532 		    strcpy(cursorhome, tgoto(cursorm, 0, 0));
1533 		    Home = cursorhome;
1534 	       }
1535 	    }
1536 	    EodClr = tgetstr("cd", &clearptr);
1537 	    if ((chBS = tgetstr("bc", &clearptr)) == NULL)
1538 		chBS = "\b";
1539 
1540 	}
1541 	if ((shell = getenv("SHELL")) == NULL)
1542 	    shell = "/bin/sh";
1543     }
1544     no_intty = gtty(fileno(stdin), &otty);
1545     gtty(fileno(stderr), &otty);
1546     savetty = otty;
1547     ospeed = otty.sg_ospeed;
1548     slow_tty = ospeed < B1200;
1549     hardtabs = (otty.sg_flags & TBDELAY) != XTABS;
1550     if (!no_tty) {
1551 	otty.sg_flags &= ~ECHO;
1552 	if (MBIT == CBREAK || !slow_tty)
1553 	    otty.sg_flags |= MBIT;
1554     }
1555 }
1556 
1557 readch ()
1558 {
1559 	char ch;
1560 	extern int errno;
1561 
1562 	if (read (2, &ch, 1) <= 0)
1563 		if (errno != EINTR)
1564 			exit(0);
1565 		else
1566 			ch = otty.sg_kill;
1567 	return (ch);
1568 }
1569 
1570 static char BS = '\b';
1571 static char *BSB = "\b \b";
1572 static char CARAT = '^';
1573 #define ERASEONECHAR \
1574     if (docrterase) \
1575 	write (2, BSB, sizeof(BSB)); \
1576     else \
1577 	write (2, &BS, sizeof(BS));
1578 
1579 ttyin (buf, nmax, pchar)
1580 char buf[];
1581 register int nmax;
1582 char pchar;
1583 {
1584     register char *sptr;
1585     register char ch;
1586     register int slash = 0;
1587     int	maxlen;
1588     char cbuf;
1589 
1590     sptr = buf;
1591     maxlen = 0;
1592     while (sptr - buf < nmax) {
1593 	if (promptlen > maxlen) maxlen = promptlen;
1594 	ch = readch ();
1595 	if (ch == '\\') {
1596 	    slash++;
1597 	}
1598 	else if ((ch == otty.sg_erase) && !slash) {
1599 	    if (sptr > buf) {
1600 		--promptlen;
1601 		ERASEONECHAR
1602 		--sptr;
1603 		if ((*sptr < ' ' && *sptr != '\n') || *sptr == RUBOUT) {
1604 		    --promptlen;
1605 		    ERASEONECHAR
1606 		}
1607 		continue;
1608 	    }
1609 	    else {
1610 		if (!eraseln) promptlen = maxlen;
1611 		longjmp (restore, 1);
1612 	    }
1613 	}
1614 	else if ((ch == otty.sg_kill) && !slash) {
1615 	    if (hard) {
1616 		show (ch);
1617 		putchar ('\n');
1618 		putchar (pchar);
1619 	    }
1620 	    else {
1621 		putchar ('\r');
1622 		putchar (pchar);
1623 		if (eraseln)
1624 		    erase (1);
1625 		else if (docrtkill)
1626 		    while (promptlen-- > 1)
1627 			write (2, BSB, sizeof(BSB));
1628 		promptlen = 1;
1629 	    }
1630 	    sptr = buf;
1631 	    fflush (stdout);
1632 	    continue;
1633 	}
1634 	if (slash && (ch == otty.sg_kill || ch == otty.sg_erase)) {
1635 	    ERASEONECHAR
1636 	    --sptr;
1637 	}
1638 	if (ch != '\\')
1639 	    slash = 0;
1640 	*sptr++ = ch;
1641 	if ((ch < ' ' && ch != '\n' && ch != ESC) || ch == RUBOUT) {
1642 	    ch += ch == RUBOUT ? -0100 : 0100;
1643 	    write (2, &CARAT, 1);
1644 	    promptlen++;
1645 	}
1646 	cbuf = ch;
1647 	if (ch != '\n' && ch != ESC) {
1648 	    write (2, &cbuf, 1);
1649 	    promptlen++;
1650 	}
1651 	else
1652 	    break;
1653     }
1654     *--sptr = '\0';
1655     if (!eraseln) promptlen = maxlen;
1656     if (sptr - buf >= nmax - 1)
1657 	error ("Line too long");
1658 }
1659 
1660 expand (outbuf, inbuf)
1661 char *outbuf;
1662 char *inbuf;
1663 {
1664     register char *instr;
1665     register char *outstr;
1666     register char ch;
1667     char temp[200];
1668     int changed = 0;
1669 
1670     instr = inbuf;
1671     outstr = temp;
1672     while ((ch = *instr++) != '\0')
1673 	switch (ch) {
1674 	case '%':
1675 	    if (!no_intty) {
1676 		strcpy (outstr, fnames[fnum]);
1677 		outstr += strlen (fnames[fnum]);
1678 		changed++;
1679 	    }
1680 	    else
1681 		*outstr++ = ch;
1682 	    break;
1683 	case '!':
1684 	    if (!shellp)
1685 		error ("No previous command to substitute for");
1686 	    strcpy (outstr, shell_line);
1687 	    outstr += strlen (shell_line);
1688 	    changed++;
1689 	    break;
1690 	case '\\':
1691 	    if (*instr == '%' || *instr == '!') {
1692 		*outstr++ = *instr++;
1693 		break;
1694 	    }
1695 	default:
1696 	    *outstr++ = ch;
1697 	}
1698     *outstr++ = '\0';
1699     strcpy (outbuf, temp);
1700     return (changed);
1701 }
1702 
1703 show (ch)
1704 register char ch;
1705 {
1706     char cbuf;
1707 
1708     if ((ch < ' ' && ch != '\n' && ch != ESC) || ch == RUBOUT) {
1709 	ch += ch == RUBOUT ? -0100 : 0100;
1710 	write (2, &CARAT, 1);
1711 	promptlen++;
1712     }
1713     cbuf = ch;
1714     write (2, &cbuf, 1);
1715     promptlen++;
1716 }
1717 
1718 error (mess)
1719 char *mess;
1720 {
1721     if (clreol)
1722 	cleareol ();
1723     else
1724 	kill_line ();
1725     promptlen += strlen (mess);
1726     if (Senter && Sexit) {
1727 	tputs (Senter, 1, putch);
1728 	pr(mess);
1729 	tputs (Sexit, 1, putch);
1730     }
1731     else
1732 	pr (mess);
1733     fflush(stdout);
1734     errors++;
1735     longjmp (restore, 1);
1736 }
1737 
1738 
1739 set_tty ()
1740 {
1741 	otty.sg_flags |= MBIT;
1742 	otty.sg_flags &= ~ECHO;
1743 	stty(fileno(stderr), &otty);
1744 }
1745 
1746 reset_tty ()
1747 {
1748     if (pstate) {
1749 	tputs(ULexit, 1, putch);
1750 	fflush(stdout);
1751 	pstate = 0;
1752     }
1753     otty.sg_flags |= ECHO;
1754     otty.sg_flags &= ~MBIT;
1755     stty(fileno(stderr), &savetty);
1756 }
1757 
1758 rdline (f)
1759 register FILE *f;
1760 {
1761     register char c;
1762     register char *p;
1763 
1764     p = Line;
1765     while ((c = Getc (f)) != '\n' && c != EOF && p - Line < LINSIZ - 1)
1766 	*p++ = c;
1767     if (c == '\n')
1768 	Currline++;
1769     *p = '\0';
1770 }
1771 
1772 /* Come here when we get a suspend signal from the terminal */
1773 
1774 onsusp ()
1775 {
1776     /* ignore SIGTTOU so we don't get stopped if csh grabs the tty */
1777     signal(SIGTTOU, SIG_IGN);
1778     reset_tty ();
1779     fflush (stdout);
1780     signal(SIGTTOU, SIG_DFL);
1781     /* Send the TSTP signal to suspend our process group */
1782     signal(SIGTSTP, SIG_DFL);
1783     sigsetmask(0);
1784     kill (0, SIGTSTP);
1785     /* Pause for station break */
1786 
1787     /* We're back */
1788     signal (SIGTSTP, onsusp);
1789     set_tty ();
1790     if (inwait)
1791 	    longjmp (restore);
1792 }
1793