xref: /original-bsd/usr.bin/tset/term.c (revision e5b2786e)
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)term.c	5.1 (Berkeley) 12/22/91";
10 #endif /* not lint */
11 
12 #include <sys/types.h>
13 #include <errno.h>
14 #include <ttyent.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include "extern.h"
20 
21 char    tbuf[1024];      		/* Termcap entry. */
22 
23 char	*askuser __P((char *));
24 char	*ttys __P((char *));
25 
26 /*
27  * Figure out what kind of terminal we're dealing with, and then read in
28  * its termcap entry.
29  */
30 char *
31 get_termcap_entry(userarg, tcapbufp)
32 	char *userarg, **tcapbufp;
33 {
34 	struct ttyent *t;
35 	int rval;
36 	char *base, *ttype, *ttypath;
37 
38 	if (userarg) {
39 		ttype = userarg;
40 		goto found;
41 	}
42 
43 	/* Try the environment. */
44 	if (ttype = getenv("TERM"))
45 		goto map;
46 
47 	/* Try ttyname(3); check for dialup or other mapping. */
48 	if (ttypath = ttyname(STDERR_FILENO)) {
49 		if (base = rindex(ttypath, '/'))
50 			++base;
51 		else
52 			base = ttypath;
53 		if ((t = getttynam(base))) {
54 			ttype = t->ty_type;
55 			goto map;
56 		}
57 	}
58 
59 	/* If still undefined, use "unknown". */
60 	ttype = "unknown";
61 
62 map:	ttype = mapped(ttype);
63 
64 	/*
65 	 * Remove TERMCAP from the environment so we get a real entry from
66 	 * /etc/termcap.  This prevents us from being fooled by out of date
67 	 * stuff in the environment.
68 	 */
69 found:	unsetenv("TERMCAP");
70 
71 	/*
72 	 * ttype now contains a pointer to the type of the terminal.
73 	 * If the first character is '?', ask the user.
74 	 */
75 	if (ttype[0] == '?')
76 		ttype = askuser(ttype + 1);
77 
78 	/* Find the termcap entry.  If it doesn't exist, ask the user. */
79 	while ((rval = tgetent(tbuf, ttype)) == 0) {
80 		(void)fprintf(stderr,
81 		    "tset: terminal type %s is unknown\n", ttype);
82 		ttype = askuser(NULL);
83 	}
84 	if (rval == -1)
85 		err("termcap: %s", strerror(errno ? errno : ENOENT));
86 	*tcapbufp = tbuf;
87 	return (ttype);
88 }
89 
90 /* Prompt the user for a terminal type. */
91 char *
92 askuser(dflt)
93 	char *dflt;
94 {
95 	static char answer[256];
96 	char *p;
97 
98 	for (;;) {
99 		if (dflt)
100 			(void)fprintf(stderr, "Terminal type? [%s] ", dflt);
101 		else
102 			(void)fprintf(stderr, "Terminal type? ");
103 		(void)fflush(stderr);
104 
105 		if (fgets(answer, sizeof(answer), stdin) == NULL)
106 			continue;
107 
108 		if (p = index(answer, '\n'))
109 			*p = '\0';
110 		return (answer[0] ? answer : dflt);
111 	}
112 }
113