xref: /dragonfly/contrib/less/screen.c (revision a85cb24f)
1 /*
2  * Copyright (C) 1984-2019  Mark Nudelman
3  *
4  * You may distribute under the terms of either the GNU General Public
5  * License or the Less License, as specified in the README file.
6  *
7  * For more information, see the README file.
8  */
9 
10 
11 /*
12  * Routines which deal with the characteristics of the terminal.
13  * Uses termcap to be as terminal-independent as possible.
14  */
15 
16 #include "less.h"
17 #include "cmd.h"
18 
19 #if MSDOS_COMPILER
20 #include "pckeys.h"
21 #if MSDOS_COMPILER==MSOFTC
22 #include <graph.h>
23 #else
24 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
25 #include <conio.h>
26 #if MSDOS_COMPILER==DJGPPC
27 #include <pc.h>
28 extern int fd0;
29 #endif
30 #else
31 #if MSDOS_COMPILER==WIN32C
32 #include <windows.h>
33 #endif
34 #endif
35 #endif
36 #include <time.h>
37 
38 #else
39 
40 #if HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43 
44 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
45 #include <termios.h>
46 #else
47 #if HAVE_TERMIO_H
48 #include <termio.h>
49 #else
50 #if HAVE_SGSTAT_H
51 #include <sgstat.h>
52 #else
53 #include <sgtty.h>
54 #endif
55 #endif
56 #endif
57 
58 #if HAVE_TERMCAP_H
59 #include <termcap.h>
60 #endif
61 #ifdef _OSK
62 #include <signal.h>
63 #endif
64 #if OS2
65 #include <sys/signal.h>
66 #include "pckeys.h"
67 #endif
68 #if HAVE_SYS_STREAM_H
69 #include <sys/stream.h>
70 #endif
71 #if HAVE_SYS_PTEM_H
72 #include <sys/ptem.h>
73 #endif
74 
75 #endif /* MSDOS_COMPILER */
76 
77 /*
78  * Check for broken termios package that forces you to manually
79  * set the line discipline.
80  */
81 #ifdef __ultrix__
82 #define MUST_SET_LINE_DISCIPLINE 1
83 #else
84 #define MUST_SET_LINE_DISCIPLINE 0
85 #endif
86 
87 #if OS2
88 #define	DEFAULT_TERM		"ansi"
89 static char *windowid;
90 #else
91 #define	DEFAULT_TERM		"unknown"
92 #endif
93 
94 #if MSDOS_COMPILER==MSOFTC
95 static int videopages;
96 static long msec_loops;
97 static int flash_created = 0;
98 #define	SETCOLORS(fg,bg)	{ _settextcolor(fg); _setbkcolor(bg); }
99 #endif
100 
101 #if MSDOS_COMPILER==BORLANDC
102 static unsigned short *whitescreen;
103 static int flash_created = 0;
104 #endif
105 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
106 #define _settextposition(y,x)   gotoxy(x,y)
107 #define _clearscreen(m)         clrscr()
108 #define _outtext(s)             cputs(s)
109 #define	SETCOLORS(fg,bg)	{ textcolor(fg); textbackground(bg); }
110 extern int sc_height;
111 #endif
112 
113 #if MSDOS_COMPILER==WIN32C
114 struct keyRecord
115 {
116 	int ascii;
117 	int scan;
118 } currentKey;
119 
120 static int keyCount = 0;
121 static WORD curr_attr;
122 static int pending_scancode = 0;
123 static char x11mousebuf[] = "[M???";    /* Mouse report, after ESC */
124 static int x11mousePos, x11mouseCount;
125 
126 static HANDLE con_out_save = INVALID_HANDLE_VALUE; /* previous console */
127 static HANDLE con_out_ours = INVALID_HANDLE_VALUE; /* our own */
128 HANDLE con_out = INVALID_HANDLE_VALUE;             /* current console */
129 
130 extern int utf_mode;
131 extern int quitting;
132 static void win32_init_term();
133 static void win32_deinit_term();
134 
135 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
136 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 4
137 #endif
138 
139 #define FG_COLORS       (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
140 #define BG_COLORS       (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY)
141 #define	MAKEATTR(fg,bg)		((WORD)((fg)|((bg)<<4)))
142 #define	SETCOLORS(fg,bg)	{ curr_attr = MAKEATTR(fg,bg); \
143 				if (SetConsoleTextAttribute(con_out, curr_attr) == 0) \
144 				error("SETCOLORS failed", NULL_PARG); }
145 #endif
146 
147 #if MSDOS_COMPILER
148 public int nm_fg_color;		/* Color of normal text */
149 public int nm_bg_color;
150 public int bo_fg_color;		/* Color of bold text */
151 public int bo_bg_color;
152 public int ul_fg_color;		/* Color of underlined text */
153 public int ul_bg_color;
154 public int so_fg_color;		/* Color of standout text */
155 public int so_bg_color;
156 public int bl_fg_color;		/* Color of blinking text */
157 public int bl_bg_color;
158 static int sy_fg_color;		/* Color of system text (before less) */
159 static int sy_bg_color;
160 public int sgr_mode;		/* Honor ANSI sequences rather than using above */
161 #if MSDOS_COMPILER==WIN32C
162 public int have_ul;		/* Is underline available? */
163 #endif
164 #else
165 
166 /*
167  * Strings passed to tputs() to do various terminal functions.
168  */
169 static char
170 	*sc_pad,		/* Pad string */
171 	*sc_home,		/* Cursor home */
172 	*sc_addline,		/* Add line, scroll down following lines */
173 	*sc_lower_left,		/* Cursor to last line, first column */
174 	*sc_return,		/* Cursor to beginning of current line */
175 	*sc_move,		/* General cursor positioning */
176 	*sc_clear,		/* Clear screen */
177 	*sc_eol_clear,		/* Clear to end of line */
178 	*sc_eos_clear,		/* Clear to end of screen */
179 	*sc_s_in,		/* Enter standout (highlighted) mode */
180 	*sc_s_out,		/* Exit standout mode */
181 	*sc_u_in,		/* Enter underline mode */
182 	*sc_u_out,		/* Exit underline mode */
183 	*sc_b_in,		/* Enter bold mode */
184 	*sc_b_out,		/* Exit bold mode */
185 	*sc_bl_in,		/* Enter blink mode */
186 	*sc_bl_out,		/* Exit blink mode */
187 	*sc_visual_bell,	/* Visual bell (flash screen) sequence */
188 	*sc_backspace,		/* Backspace cursor */
189 	*sc_s_keypad,		/* Start keypad mode */
190 	*sc_e_keypad,		/* End keypad mode */
191 	*sc_s_mousecap,		/* Start mouse capture mode */
192 	*sc_e_mousecap,		/* End mouse capture mode */
193 	*sc_init,		/* Startup terminal initialization */
194 	*sc_deinit;		/* Exit terminal de-initialization */
195 #endif
196 
197 static int init_done = 0;
198 
199 public int auto_wrap;		/* Terminal does \r\n when write past margin */
200 public int ignaw;		/* Terminal ignores \n immediately after wrap */
201 public int erase_char;		/* The user's erase char */
202 public int erase2_char;		/* The user's other erase char */
203 public int kill_char;		/* The user's line-kill char */
204 public int werase_char;		/* The user's word-erase char */
205 public int sc_width, sc_height;	/* Height & width of screen */
206 public int bo_s_width, bo_e_width;	/* Printing width of boldface seq */
207 public int ul_s_width, ul_e_width;	/* Printing width of underline seq */
208 public int so_s_width, so_e_width;	/* Printing width of standout seq */
209 public int bl_s_width, bl_e_width;	/* Printing width of blink seq */
210 public int above_mem, below_mem;	/* Memory retained above/below screen */
211 public int can_goto_line;		/* Can move cursor to any line */
212 public int clear_bg;		/* Clear fills with background color */
213 public int missing_cap = 0;	/* Some capability is missing */
214 public char *kent = NULL;	/* Keypad ENTER sequence */
215 
216 static int attrmode = AT_NORMAL;
217 static int termcap_debug = -1;
218 extern int binattr;
219 extern int one_screen;
220 
221 #if !MSDOS_COMPILER
222 static char *cheaper();
223 static void tmodes();
224 #endif
225 
226 /*
227  * These two variables are sometimes defined in,
228  * and needed by, the termcap library.
229  */
230 #if MUST_DEFINE_OSPEED
231 extern short ospeed;	/* Terminal output baud rate */
232 extern char PC;		/* Pad character */
233 #endif
234 #ifdef _OSK
235 short ospeed;
236 char PC_, *UP, *BC;
237 #endif
238 
239 extern int quiet;		/* If VERY_QUIET, use visual bell for bell */
240 extern int no_back_scroll;
241 extern int swindow;
242 extern int no_init;
243 extern int no_keypad;
244 extern int sigs;
245 extern int wscroll;
246 extern int screen_trashed;
247 extern int top_scroll;
248 extern int quit_if_one_screen;
249 extern int oldbot;
250 extern int mousecap;
251 #if HILITE_SEARCH
252 extern int hilite_search;
253 #endif
254 #if MSDOS_COMPILER==WIN32C
255 extern HANDLE tty;
256 #else
257 extern int tty;
258 #endif
259 
260 extern char *tgetstr();
261 extern char *tgoto();
262 
263 
264 /*
265  * Change terminal to "raw mode", or restore to "normal" mode.
266  * "Raw mode" means
267  *	1. An outstanding read will complete on receipt of a single keystroke.
268  *	2. Input is not echoed.
269  *	3. On output, \n is mapped to \r\n.
270  *	4. \t is NOT expanded into spaces.
271  *	5. Signal-causing characters such as ctrl-C (interrupt),
272  *	   etc. are NOT disabled.
273  * It doesn't matter whether an input \n is mapped to \r, or vice versa.
274  */
275 	public void
276 raw_mode(on)
277 	int on;
278 {
279 	static int curr_on = 0;
280 
281 	if (on == curr_on)
282 		return;
283 	erase2_char = '\b'; /* in case OS doesn't know about erase2 */
284 #if HAVE_TERMIOS_H && HAVE_TERMIOS_FUNCS
285     {
286 	struct termios s;
287 	static struct termios save_term;
288 	static int saved_term = 0;
289 
290 	if (on)
291 	{
292 		/*
293 		 * Get terminal modes.
294 		 */
295 		tcgetattr(tty, &s);
296 
297 		/*
298 		 * Save modes and set certain variables dependent on modes.
299 		 */
300 		if (!saved_term)
301 		{
302 			save_term = s;
303 			saved_term = 1;
304 		}
305 #if HAVE_OSPEED
306 		switch (cfgetospeed(&s))
307 		{
308 #ifdef B0
309 		case B0: ospeed = 0; break;
310 #endif
311 #ifdef B50
312 		case B50: ospeed = 1; break;
313 #endif
314 #ifdef B75
315 		case B75: ospeed = 2; break;
316 #endif
317 #ifdef B110
318 		case B110: ospeed = 3; break;
319 #endif
320 #ifdef B134
321 		case B134: ospeed = 4; break;
322 #endif
323 #ifdef B150
324 		case B150: ospeed = 5; break;
325 #endif
326 #ifdef B200
327 		case B200: ospeed = 6; break;
328 #endif
329 #ifdef B300
330 		case B300: ospeed = 7; break;
331 #endif
332 #ifdef B600
333 		case B600: ospeed = 8; break;
334 #endif
335 #ifdef B1200
336 		case B1200: ospeed = 9; break;
337 #endif
338 #ifdef B1800
339 		case B1800: ospeed = 10; break;
340 #endif
341 #ifdef B2400
342 		case B2400: ospeed = 11; break;
343 #endif
344 #ifdef B4800
345 		case B4800: ospeed = 12; break;
346 #endif
347 #ifdef B9600
348 		case B9600: ospeed = 13; break;
349 #endif
350 #ifdef EXTA
351 		case EXTA: ospeed = 14; break;
352 #endif
353 #ifdef EXTB
354 		case EXTB: ospeed = 15; break;
355 #endif
356 #ifdef B57600
357 		case B57600: ospeed = 16; break;
358 #endif
359 #ifdef B115200
360 		case B115200: ospeed = 17; break;
361 #endif
362 		default: ;
363 		}
364 #endif
365 		erase_char = s.c_cc[VERASE];
366 #ifdef VERASE2
367 		erase2_char = s.c_cc[VERASE2];
368 #endif
369 		kill_char = s.c_cc[VKILL];
370 #ifdef VWERASE
371 		werase_char = s.c_cc[VWERASE];
372 #else
373 		werase_char = CONTROL('W');
374 #endif
375 
376 		/*
377 		 * Set the modes to the way we want them.
378 		 */
379 		s.c_lflag &= ~(0
380 #ifdef ICANON
381 			| ICANON
382 #endif
383 #ifdef ECHO
384 			| ECHO
385 #endif
386 #ifdef ECHOE
387 			| ECHOE
388 #endif
389 #ifdef ECHOK
390 			| ECHOK
391 #endif
392 #if ECHONL
393 			| ECHONL
394 #endif
395 		);
396 
397 		s.c_oflag |= (0
398 #ifdef OXTABS
399 			| OXTABS
400 #else
401 #ifdef TAB3
402 			| TAB3
403 #else
404 #ifdef XTABS
405 			| XTABS
406 #endif
407 #endif
408 #endif
409 #ifdef OPOST
410 			| OPOST
411 #endif
412 #ifdef ONLCR
413 			| ONLCR
414 #endif
415 		);
416 
417 		s.c_oflag &= ~(0
418 #ifdef ONOEOT
419 			| ONOEOT
420 #endif
421 #ifdef OCRNL
422 			| OCRNL
423 #endif
424 #ifdef ONOCR
425 			| ONOCR
426 #endif
427 #ifdef ONLRET
428 			| ONLRET
429 #endif
430 		);
431 		s.c_cc[VMIN] = 1;
432 		s.c_cc[VTIME] = 0;
433 #ifdef VLNEXT
434 		s.c_cc[VLNEXT] = 0;
435 #endif
436 #ifdef VDSUSP
437 		s.c_cc[VDSUSP] = 0;
438 #endif
439 #if MUST_SET_LINE_DISCIPLINE
440 		/*
441 		 * System's termios is broken; need to explicitly
442 		 * request TERMIODISC line discipline.
443 		 */
444 		s.c_line = TERMIODISC;
445 #endif
446 	} else
447 	{
448 		/*
449 		 * Restore saved modes.
450 		 */
451 		s = save_term;
452 	}
453 #if HAVE_FSYNC
454 	fsync(tty);
455 #endif
456 	tcsetattr(tty, TCSADRAIN, &s);
457 #if MUST_SET_LINE_DISCIPLINE
458 	if (!on)
459 	{
460 		/*
461 		 * Broken termios *ignores* any line discipline
462 		 * except TERMIODISC.  A different old line discipline
463 		 * is therefore not restored, yet.  Restore the old
464 		 * line discipline by hand.
465 		 */
466 		ioctl(tty, TIOCSETD, &save_term.c_line);
467 	}
468 #endif
469     }
470 #else
471 #ifdef TCGETA
472     {
473 	struct termio s;
474 	static struct termio save_term;
475 	static int saved_term = 0;
476 
477 	if (on)
478 	{
479 		/*
480 		 * Get terminal modes.
481 		 */
482 		ioctl(tty, TCGETA, &s);
483 
484 		/*
485 		 * Save modes and set certain variables dependent on modes.
486 		 */
487 		if (!saved_term)
488 		{
489 			save_term = s;
490 			saved_term = 1;
491 		}
492 #if HAVE_OSPEED
493 		ospeed = s.c_cflag & CBAUD;
494 #endif
495 		erase_char = s.c_cc[VERASE];
496 		kill_char = s.c_cc[VKILL];
497 #ifdef VWERASE
498 		werase_char = s.c_cc[VWERASE];
499 #else
500 		werase_char = CONTROL('W');
501 #endif
502 
503 		/*
504 		 * Set the modes to the way we want them.
505 		 */
506 		s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
507 		s.c_oflag |=  (OPOST|ONLCR|TAB3);
508 		s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
509 		s.c_cc[VMIN] = 1;
510 		s.c_cc[VTIME] = 0;
511 	} else
512 	{
513 		/*
514 		 * Restore saved modes.
515 		 */
516 		s = save_term;
517 	}
518 	ioctl(tty, TCSETAW, &s);
519     }
520 #else
521 #ifdef TIOCGETP
522     {
523 	struct sgttyb s;
524 	static struct sgttyb save_term;
525 	static int saved_term = 0;
526 
527 	if (on)
528 	{
529 		/*
530 		 * Get terminal modes.
531 		 */
532 		ioctl(tty, TIOCGETP, &s);
533 
534 		/*
535 		 * Save modes and set certain variables dependent on modes.
536 		 */
537 		if (!saved_term)
538 		{
539 			save_term = s;
540 			saved_term = 1;
541 		}
542 #if HAVE_OSPEED
543 		ospeed = s.sg_ospeed;
544 #endif
545 		erase_char = s.sg_erase;
546 		kill_char = s.sg_kill;
547 		werase_char = CONTROL('W');
548 
549 		/*
550 		 * Set the modes to the way we want them.
551 		 */
552 		s.sg_flags |= CBREAK;
553 		s.sg_flags &= ~(ECHO|XTABS);
554 	} else
555 	{
556 		/*
557 		 * Restore saved modes.
558 		 */
559 		s = save_term;
560 	}
561 	ioctl(tty, TIOCSETN, &s);
562     }
563 #else
564 #ifdef _OSK
565     {
566 	struct sgbuf s;
567 	static struct sgbuf save_term;
568 	static int saved_term = 0;
569 
570 	if (on)
571 	{
572 		/*
573 		 * Get terminal modes.
574 		 */
575 		_gs_opt(tty, &s);
576 
577 		/*
578 		 * Save modes and set certain variables dependent on modes.
579 		 */
580 		if (!saved_term)
581 		{
582 			save_term = s;
583 			saved_term = 1;
584 		}
585 		erase_char = s.sg_bspch;
586 		kill_char = s.sg_dlnch;
587 		werase_char = CONTROL('W');
588 
589 		/*
590 		 * Set the modes to the way we want them.
591 		 */
592 		s.sg_echo = 0;
593 		s.sg_eofch = 0;
594 		s.sg_pause = 0;
595 		s.sg_psch = 0;
596 	} else
597 	{
598 		/*
599 		 * Restore saved modes.
600 		 */
601 		s = save_term;
602 	}
603 	_ss_opt(tty, &s);
604     }
605 #else
606 	/* MS-DOS, Windows, or OS2 */
607 #if OS2
608 	/* OS2 */
609 	LSIGNAL(SIGINT, SIG_IGN);
610 #endif
611 	erase_char = '\b';
612 #if MSDOS_COMPILER==DJGPPC
613 	kill_char = CONTROL('U');
614 	/*
615 	 * So that when we shell out or run another program, its
616 	 * stdin is in cooked mode.  We do not switch stdin to binary
617 	 * mode if fd0 is zero, since that means we were called before
618 	 * tty was reopened in open_getchr, in which case we would be
619 	 * changing the original stdin device outside less.
620 	 */
621 	if (fd0 != 0)
622 		setmode(0, on ? O_BINARY : O_TEXT);
623 #else
624 	kill_char = ESC;
625 #endif
626 	werase_char = CONTROL('W');
627 #endif
628 #endif
629 #endif
630 #endif
631 	curr_on = on;
632 }
633 
634 #if !MSDOS_COMPILER
635 /*
636  * Some glue to prevent calling termcap functions if tgetent() failed.
637  */
638 static int hardcopy;
639 
640 	static char *
641 ltget_env(capname)
642 	char *capname;
643 {
644 	char name[64];
645 
646 	if (termcap_debug)
647 	{
648 		struct env { struct env *next; char *name; char *value; };
649 		static struct env *envs = NULL;
650 		struct env *p;
651 		for (p = envs;  p != NULL;  p = p->next)
652 			if (strcmp(p->name, capname) == 0)
653 				return p->value;
654 		p = (struct env *) ecalloc(1, sizeof(struct env));
655 		p->name = save(capname);
656 		p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
657 		sprintf(p->value, "<%s>", capname);
658 		p->next = envs;
659 		envs = p;
660 		return p->value;
661 	}
662 	SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
663 	return (lgetenv(name));
664 }
665 
666 	static int
667 ltgetflag(capname)
668 	char *capname;
669 {
670 	char *s;
671 
672 	if ((s = ltget_env(capname)) != NULL)
673 		return (*s != '\0' && *s != '0');
674 	if (hardcopy)
675 		return (0);
676 	return (tgetflag(capname));
677 }
678 
679 	static int
680 ltgetnum(capname)
681 	char *capname;
682 {
683 	char *s;
684 
685 	if ((s = ltget_env(capname)) != NULL)
686 		return (atoi(s));
687 	if (hardcopy)
688 		return (-1);
689 	return (tgetnum(capname));
690 }
691 
692 	static char *
693 ltgetstr(capname, pp)
694 	char *capname;
695 	char **pp;
696 {
697 	char *s;
698 
699 	if ((s = ltget_env(capname)) != NULL)
700 		return (s);
701 	if (hardcopy)
702 		return (NULL);
703 	return (tgetstr(capname, pp));
704 }
705 #endif /* MSDOS_COMPILER */
706 
707 /*
708  * Get size of the output screen.
709  */
710 	public void
711 scrsize(VOID_PARAM)
712 {
713 	char *s;
714 	int sys_height;
715 	int sys_width;
716 #if !MSDOS_COMPILER
717 	int n;
718 #endif
719 
720 #define	DEF_SC_WIDTH	80
721 #if MSDOS_COMPILER
722 #define	DEF_SC_HEIGHT	25
723 #else
724 #define	DEF_SC_HEIGHT	24
725 #endif
726 
727 
728 	sys_width = sys_height = 0;
729 
730 #if MSDOS_COMPILER==MSOFTC
731 	{
732 		struct videoconfig w;
733 		_getvideoconfig(&w);
734 		sys_height = w.numtextrows;
735 		sys_width = w.numtextcols;
736 	}
737 #else
738 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
739 	{
740 		struct text_info w;
741 		gettextinfo(&w);
742 		sys_height = w.screenheight;
743 		sys_width = w.screenwidth;
744 	}
745 #else
746 #if MSDOS_COMPILER==WIN32C
747 	{
748 		CONSOLE_SCREEN_BUFFER_INFO scr;
749 		GetConsoleScreenBufferInfo(con_out, &scr);
750 		sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
751 		sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
752 	}
753 #else
754 #if OS2
755 	{
756 		int s[2];
757 		_scrsize(s);
758 		sys_width = s[0];
759 		sys_height = s[1];
760 		/*
761 		 * When using terminal emulators for XFree86/OS2, the
762 		 * _scrsize function does not work well.
763 		 * Call the scrsize.exe program to get the window size.
764 		 */
765 		windowid = getenv("WINDOWID");
766 		if (windowid != NULL)
767 		{
768 			FILE *fd = popen("scrsize", "rt");
769 			if (fd != NULL)
770 			{
771 				int w, h;
772 				fscanf(fd, "%i %i", &w, &h);
773 				if (w > 0 && h > 0)
774 				{
775 					sys_width = w;
776 					sys_height = h;
777 				}
778 				pclose(fd);
779 			}
780 		}
781 	}
782 #else
783 #ifdef TIOCGWINSZ
784 	{
785 		struct winsize w;
786 		if (ioctl(2, TIOCGWINSZ, &w) == 0)
787 		{
788 			if (w.ws_row > 0)
789 				sys_height = w.ws_row;
790 			if (w.ws_col > 0)
791 				sys_width = w.ws_col;
792 		}
793 	}
794 #else
795 #ifdef WIOCGETD
796 	{
797 		struct uwdata w;
798 		if (ioctl(2, WIOCGETD, &w) == 0)
799 		{
800 			if (w.uw_height > 0)
801 				sys_height = w.uw_height / w.uw_vs;
802 			if (w.uw_width > 0)
803 				sys_width = w.uw_width / w.uw_hs;
804 		}
805 	}
806 #endif
807 #endif
808 #endif
809 #endif
810 #endif
811 #endif
812 
813 	if (sys_height > 0)
814 		sc_height = sys_height;
815 	else if ((s = lgetenv("LINES")) != NULL)
816 		sc_height = atoi(s);
817 #if !MSDOS_COMPILER
818 	else if ((n = ltgetnum("li")) > 0)
819  		sc_height = n;
820 #endif
821 	if (sc_height <= 0)
822 		sc_height = DEF_SC_HEIGHT;
823 
824 	if (sys_width > 0)
825 		sc_width = sys_width;
826 	else if ((s = lgetenv("COLUMNS")) != NULL)
827 		sc_width = atoi(s);
828 #if !MSDOS_COMPILER
829 	else if ((n = ltgetnum("co")) > 0)
830  		sc_width = n;
831 #endif
832 	if (sc_width <= 0)
833 		sc_width = DEF_SC_WIDTH;
834 }
835 
836 #if MSDOS_COMPILER==MSOFTC
837 /*
838  * Figure out how many empty loops it takes to delay a millisecond.
839  */
840 	static void
841 get_clock(VOID_PARAM)
842 {
843 	clock_t start;
844 
845 	/*
846 	 * Get synchronized at the start of a tick.
847 	 */
848 	start = clock();
849 	while (clock() == start)
850 		;
851 	/*
852 	 * Now count loops till the next tick.
853 	 */
854 	start = clock();
855 	msec_loops = 0;
856 	while (clock() == start)
857 		msec_loops++;
858 	/*
859 	 * Convert from (loops per clock) to (loops per millisecond).
860 	 */
861 	msec_loops *= CLOCKS_PER_SEC;
862 	msec_loops /= 1000;
863 }
864 
865 /*
866  * Delay for a specified number of milliseconds.
867  */
868 	static void
869 delay(msec)
870 	int msec;
871 {
872 	long i;
873 
874 	while (msec-- > 0)
875 	{
876 		for (i = 0;  i < msec_loops;  i++)
877 			(void) clock();
878 	}
879 }
880 #endif
881 
882 /*
883  * Return the characters actually input by a "special" key.
884  */
885 	public char *
886 special_key_str(key)
887 	int key;
888 {
889 	static char tbuf[40];
890 	char *s;
891 #if MSDOS_COMPILER || OS2
892 	static char k_right[]		= { '\340', PCK_RIGHT, 0 };
893 	static char k_left[]		= { '\340', PCK_LEFT, 0  };
894 	static char k_ctl_right[]	= { '\340', PCK_CTL_RIGHT, 0  };
895 	static char k_ctl_left[]	= { '\340', PCK_CTL_LEFT, 0  };
896 	static char k_insert[]		= { '\340', PCK_INSERT, 0  };
897 	static char k_delete[]		= { '\340', PCK_DELETE, 0  };
898 	static char k_ctl_delete[]	= { '\340', PCK_CTL_DELETE, 0  };
899 	static char k_ctl_backspace[]	= { '\177', 0 };
900 	static char k_home[]		= { '\340', PCK_HOME, 0 };
901 	static char k_end[]		= { '\340', PCK_END, 0 };
902 	static char k_up[]		= { '\340', PCK_UP, 0 };
903 	static char k_down[]		= { '\340', PCK_DOWN, 0 };
904 	static char k_backtab[]		= { '\340', PCK_SHIFT_TAB, 0 };
905 	static char k_pagedown[]	= { '\340', PCK_PAGEDOWN, 0 };
906 	static char k_pageup[]		= { '\340', PCK_PAGEUP, 0 };
907 	static char k_f1[]		= { '\340', PCK_F1, 0 };
908 #endif
909 #if !MSDOS_COMPILER
910 	char *sp = tbuf;
911 #endif
912 
913 	switch (key)
914 	{
915 #if OS2
916 	/*
917 	 * If windowid is not NULL, assume less is executed in
918 	 * the XFree86 environment.
919 	 */
920 	case SK_RIGHT_ARROW:
921 		s = windowid ? ltgetstr("kr", &sp) : k_right;
922 		break;
923 	case SK_LEFT_ARROW:
924 		s = windowid ? ltgetstr("kl", &sp) : k_left;
925 		break;
926 	case SK_UP_ARROW:
927 		s = windowid ? ltgetstr("ku", &sp) : k_up;
928 		break;
929 	case SK_DOWN_ARROW:
930 		s = windowid ? ltgetstr("kd", &sp) : k_down;
931 		break;
932 	case SK_PAGE_UP:
933 		s = windowid ? ltgetstr("kP", &sp) : k_pageup;
934 		break;
935 	case SK_PAGE_DOWN:
936 		s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
937 		break;
938 	case SK_HOME:
939 		s = windowid ? ltgetstr("kh", &sp) : k_home;
940 		break;
941 	case SK_END:
942 		s = windowid ? ltgetstr("@7", &sp) : k_end;
943 		break;
944 	case SK_DELETE:
945 		s = windowid ? ltgetstr("kD", &sp) : k_delete;
946 		if (s == NULL)
947 		{
948 			tbuf[0] = '\177';
949 			tbuf[1] = '\0';
950 			s = tbuf;
951 		}
952 		break;
953 #endif
954 #if MSDOS_COMPILER
955 	case SK_RIGHT_ARROW:
956 		s = k_right;
957 		break;
958 	case SK_LEFT_ARROW:
959 		s = k_left;
960 		break;
961 	case SK_UP_ARROW:
962 		s = k_up;
963 		break;
964 	case SK_DOWN_ARROW:
965 		s = k_down;
966 		break;
967 	case SK_PAGE_UP:
968 		s = k_pageup;
969 		break;
970 	case SK_PAGE_DOWN:
971 		s = k_pagedown;
972 		break;
973 	case SK_HOME:
974 		s = k_home;
975 		break;
976 	case SK_END:
977 		s = k_end;
978 		break;
979 	case SK_DELETE:
980 		s = k_delete;
981 		break;
982 #endif
983 #if MSDOS_COMPILER || OS2
984 	case SK_INSERT:
985 		s = k_insert;
986 		break;
987 	case SK_CTL_LEFT_ARROW:
988 		s = k_ctl_left;
989 		break;
990 	case SK_CTL_RIGHT_ARROW:
991 		s = k_ctl_right;
992 		break;
993 	case SK_CTL_BACKSPACE:
994 		s = k_ctl_backspace;
995 		break;
996 	case SK_CTL_DELETE:
997 		s = k_ctl_delete;
998 		break;
999 	case SK_F1:
1000 		s = k_f1;
1001 		break;
1002 	case SK_BACKTAB:
1003 		s = k_backtab;
1004 		break;
1005 #else
1006 	case SK_RIGHT_ARROW:
1007 		s = ltgetstr("kr", &sp);
1008 		break;
1009 	case SK_LEFT_ARROW:
1010 		s = ltgetstr("kl", &sp);
1011 		break;
1012 	case SK_UP_ARROW:
1013 		s = ltgetstr("ku", &sp);
1014 		break;
1015 	case SK_DOWN_ARROW:
1016 		s = ltgetstr("kd", &sp);
1017 		break;
1018 	case SK_PAGE_UP:
1019 		s = ltgetstr("kP", &sp);
1020 		break;
1021 	case SK_PAGE_DOWN:
1022 		s = ltgetstr("kN", &sp);
1023 		break;
1024 	case SK_HOME:
1025 		s = ltgetstr("kh", &sp);
1026 		break;
1027 	case SK_END:
1028 		s = ltgetstr("@7", &sp);
1029 		break;
1030 	case SK_DELETE:
1031 		s = ltgetstr("kD", &sp);
1032 		if (s == NULL)
1033 		{
1034 			tbuf[0] = '\177';
1035 			tbuf[1] = '\0';
1036 			s = tbuf;
1037 		}
1038 		break;
1039 #endif
1040 	case SK_CONTROL_K:
1041 		tbuf[0] = CONTROL('K');
1042 		tbuf[1] = '\0';
1043 		s = tbuf;
1044 		break;
1045 	default:
1046 		return (NULL);
1047 	}
1048 	return (s);
1049 }
1050 
1051 /*
1052  * Get terminal capabilities via termcap.
1053  */
1054 	public void
1055 get_term(VOID_PARAM)
1056 {
1057 	termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1058 #if MSDOS_COMPILER
1059 	auto_wrap = 1;
1060 	ignaw = 0;
1061 	can_goto_line = 1;
1062 	clear_bg = 1;
1063 	/*
1064 	 * Set up default colors.
1065 	 * The xx_s_width and xx_e_width vars are already initialized to 0.
1066 	 */
1067 #if MSDOS_COMPILER==MSOFTC
1068 	sy_bg_color = _getbkcolor();
1069 	sy_fg_color = _gettextcolor();
1070 	get_clock();
1071 #else
1072 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1073     {
1074 	struct text_info w;
1075 	gettextinfo(&w);
1076 	sy_bg_color = (w.attribute >> 4) & 0x0F;
1077 	sy_fg_color = (w.attribute >> 0) & 0x0F;
1078     }
1079 #else
1080 #if MSDOS_COMPILER==WIN32C
1081     {
1082 	DWORD nread;
1083 	CONSOLE_SCREEN_BUFFER_INFO scr;
1084 
1085 	con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1086 	/*
1087 	 * Always open stdin in binary. Note this *must* be done
1088 	 * before any file operations have been done on fd0.
1089 	 */
1090 	SET_BINARY(0);
1091 	GetConsoleScreenBufferInfo(con_out, &scr);
1092 	ReadConsoleOutputAttribute(con_out, &curr_attr,
1093 					1, scr.dwCursorPosition, &nread);
1094 	sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1095 	sy_fg_color = curr_attr & FG_COLORS;
1096     }
1097 #endif
1098 #endif
1099 #endif
1100 	nm_fg_color = sy_fg_color;
1101 	nm_bg_color = sy_bg_color;
1102 	bo_fg_color = 11;
1103 	bo_bg_color = 0;
1104 	ul_fg_color = 9;
1105 	ul_bg_color = 0;
1106 	so_fg_color = 15;
1107 	so_bg_color = 9;
1108 	bl_fg_color = 15;
1109 	bl_bg_color = 0;
1110 	sgr_mode = 0;
1111 
1112 	/*
1113 	 * Get size of the screen.
1114 	 */
1115 	scrsize();
1116 	pos_init();
1117 
1118 
1119 #else /* !MSDOS_COMPILER */
1120 {
1121 	char *sp;
1122 	char *t1, *t2;
1123 	char *term;
1124 	char termbuf[TERMBUF_SIZE];
1125 
1126 	static char sbuf[TERMSBUF_SIZE];
1127 
1128 #if OS2
1129 	/*
1130 	 * Make sure the termcap database is available.
1131 	 */
1132 	sp = lgetenv("TERMCAP");
1133 	if (isnullenv(sp))
1134 	{
1135 		char *termcap;
1136 		if ((sp = homefile("termcap.dat")) != NULL)
1137 		{
1138 			termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1139 			sprintf(termcap, "TERMCAP=%s", sp);
1140 			free(sp);
1141 			putenv(termcap);
1142 		}
1143 	}
1144 #endif
1145 	/*
1146 	 * Find out what kind of terminal this is.
1147 	 */
1148  	if ((term = lgetenv("TERM")) == NULL)
1149  		term = DEFAULT_TERM;
1150 	hardcopy = 0;
1151  	if (tgetent(termbuf, term) != TGETENT_OK)
1152  		hardcopy = 1;
1153  	if (ltgetflag("hc"))
1154 		hardcopy = 1;
1155 
1156 	/*
1157 	 * Get size of the screen.
1158 	 */
1159 	scrsize();
1160 	pos_init();
1161 
1162 	auto_wrap = ltgetflag("am");
1163 	ignaw = ltgetflag("xn");
1164 	above_mem = ltgetflag("da");
1165 	below_mem = ltgetflag("db");
1166 	clear_bg = ltgetflag("ut");
1167 
1168 	/*
1169 	 * Assumes termcap variable "sg" is the printing width of:
1170 	 * the standout sequence, the end standout sequence,
1171 	 * the underline sequence, the end underline sequence,
1172 	 * the boldface sequence, and the end boldface sequence.
1173 	 */
1174 	if ((so_s_width = ltgetnum("sg")) < 0)
1175 		so_s_width = 0;
1176 	so_e_width = so_s_width;
1177 
1178 	bo_s_width = bo_e_width = so_s_width;
1179 	ul_s_width = ul_e_width = so_s_width;
1180 	bl_s_width = bl_e_width = so_s_width;
1181 
1182 #if HILITE_SEARCH
1183 	if (so_s_width > 0 || so_e_width > 0)
1184 		/*
1185 		 * Disable highlighting by default on magic cookie terminals.
1186 		 * Turning on highlighting might change the displayed width
1187 		 * of a line, causing the display to get messed up.
1188 		 * The user can turn it back on with -g,
1189 		 * but she won't like the results.
1190 		 */
1191 		hilite_search = 0;
1192 #endif
1193 
1194 	/*
1195 	 * Get various string-valued capabilities.
1196 	 */
1197 	sp = sbuf;
1198 
1199 #if HAVE_OSPEED
1200 	sc_pad = ltgetstr("pc", &sp);
1201 	if (sc_pad != NULL)
1202 		PC = *sc_pad;
1203 #endif
1204 
1205 	sc_s_keypad = ltgetstr("ks", &sp);
1206 	if (sc_s_keypad == NULL)
1207 		sc_s_keypad = "";
1208 	sc_e_keypad = ltgetstr("ke", &sp);
1209 	if (sc_e_keypad == NULL)
1210 		sc_e_keypad = "";
1211 	kent = ltgetstr("@8", &sp);
1212 
1213 	sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1214 	if (sc_s_mousecap == NULL)
1215 		sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1216 	sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1217 	if (sc_e_mousecap == NULL)
1218 		sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1219 
1220 	sc_init = ltgetstr("ti", &sp);
1221 	if (sc_init == NULL)
1222 		sc_init = "";
1223 
1224 	sc_deinit= ltgetstr("te", &sp);
1225 	if (sc_deinit == NULL)
1226 		sc_deinit = "";
1227 
1228 	sc_eol_clear = ltgetstr("ce", &sp);
1229 	if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1230 	{
1231 		missing_cap = 1;
1232 		sc_eol_clear = "";
1233 	}
1234 
1235 	sc_eos_clear = ltgetstr("cd", &sp);
1236 	if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1237 	{
1238 		missing_cap = 1;
1239 		sc_eos_clear = "";
1240 	}
1241 
1242 	sc_clear = ltgetstr("cl", &sp);
1243 	if (sc_clear == NULL || *sc_clear == '\0')
1244 	{
1245 		missing_cap = 1;
1246 		sc_clear = "\n\n";
1247 	}
1248 
1249 	sc_move = ltgetstr("cm", &sp);
1250 	if (sc_move == NULL || *sc_move == '\0')
1251 	{
1252 		/*
1253 		 * This is not an error here, because we don't
1254 		 * always need sc_move.
1255 		 * We need it only if we don't have home or lower-left.
1256 		 */
1257 		sc_move = "";
1258 		can_goto_line = 0;
1259 	} else
1260 		can_goto_line = 1;
1261 
1262 	tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1263 	tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1264 	tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1265 	tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1266 
1267 	sc_visual_bell = ltgetstr("vb", &sp);
1268 	if (sc_visual_bell == NULL)
1269 		sc_visual_bell = "";
1270 
1271 	if (ltgetflag("bs"))
1272 		sc_backspace = "\b";
1273 	else
1274 	{
1275 		sc_backspace = ltgetstr("bc", &sp);
1276 		if (sc_backspace == NULL || *sc_backspace == '\0')
1277 			sc_backspace = "\b";
1278 	}
1279 
1280 	/*
1281 	 * Choose between using "ho" and "cm" ("home" and "cursor move")
1282 	 * to move the cursor to the upper left corner of the screen.
1283 	 */
1284 	t1 = ltgetstr("ho", &sp);
1285 	if (t1 == NULL)
1286 		t1 = "";
1287 	if (*sc_move == '\0')
1288 		t2 = "";
1289 	else
1290 	{
1291 		strcpy(sp, tgoto(sc_move, 0, 0));
1292 		t2 = sp;
1293 		sp += strlen(sp) + 1;
1294 	}
1295 	sc_home = cheaper(t1, t2, "|\b^");
1296 
1297 	/*
1298 	 * Choose between using "ll" and "cm"  ("lower left" and "cursor move")
1299 	 * to move the cursor to the lower left corner of the screen.
1300 	 */
1301 	t1 = ltgetstr("ll", &sp);
1302 	if (t1 == NULL)
1303 		t1 = "";
1304 	if (*sc_move == '\0')
1305 		t2 = "";
1306 	else
1307 	{
1308 		strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1309 		t2 = sp;
1310 		sp += strlen(sp) + 1;
1311 	}
1312 	sc_lower_left = cheaper(t1, t2, "\r");
1313 
1314 	/*
1315 	 * Get carriage return string.
1316 	 */
1317 	sc_return = ltgetstr("cr", &sp);
1318 	if (sc_return == NULL)
1319 		sc_return = "\r";
1320 
1321 	/*
1322 	 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1323 	 * to add a line at the top of the screen.
1324 	 */
1325 	t1 = ltgetstr("al", &sp);
1326 	if (t1 == NULL)
1327 		t1 = "";
1328 	t2 = ltgetstr("sr", &sp);
1329 	if (t2 == NULL)
1330 		t2 = "";
1331 #if OS2
1332 	if (*t1 == '\0' && *t2 == '\0')
1333 		sc_addline = "";
1334 	else
1335 #endif
1336 	if (above_mem)
1337 		sc_addline = t1;
1338 	else
1339 		sc_addline = cheaper(t1, t2, "");
1340 	if (*sc_addline == '\0')
1341 	{
1342 		/*
1343 		 * Force repaint on any backward movement.
1344 		 */
1345 		no_back_scroll = 1;
1346 	}
1347 }
1348 #endif /* MSDOS_COMPILER */
1349 }
1350 
1351 #if !MSDOS_COMPILER
1352 /*
1353  * Return the cost of displaying a termcap string.
1354  * We use the trick of calling tputs, but as a char printing function
1355  * we give it inc_costcount, which just increments "costcount".
1356  * This tells us how many chars would be printed by using this string.
1357  * {{ Couldn't we just use strlen? }}
1358  */
1359 static int costcount;
1360 
1361 /*ARGSUSED*/
1362 	static int
1363 inc_costcount(c)
1364 	int c;
1365 {
1366 	costcount++;
1367 	return (c);
1368 }
1369 
1370 	static int
1371 cost(t)
1372 	char *t;
1373 {
1374 	costcount = 0;
1375 	tputs(t, sc_height, inc_costcount);
1376 	return (costcount);
1377 }
1378 
1379 /*
1380  * Return the "best" of the two given termcap strings.
1381  * The best, if both exist, is the one with the lower
1382  * cost (see cost() function).
1383  */
1384 	static char *
1385 cheaper(t1, t2, def)
1386 	char *t1, *t2;
1387 	char *def;
1388 {
1389 	if (*t1 == '\0' && *t2 == '\0')
1390 	{
1391 		missing_cap = 1;
1392 		return (def);
1393 	}
1394 	if (*t1 == '\0')
1395 		return (t2);
1396 	if (*t2 == '\0')
1397 		return (t1);
1398 	if (cost(t1) < cost(t2))
1399 		return (t1);
1400 	return (t2);
1401 }
1402 
1403 	static void
1404 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1405 	char *incap;
1406 	char *outcap;
1407 	char **instr;
1408 	char **outstr;
1409 	char *def_instr;
1410 	char *def_outstr;
1411 	char **spp;
1412 {
1413 	*instr = ltgetstr(incap, spp);
1414 	if (*instr == NULL)
1415 	{
1416 		/* Use defaults. */
1417 		*instr = def_instr;
1418 		*outstr = def_outstr;
1419 		return;
1420 	}
1421 
1422 	*outstr = ltgetstr(outcap, spp);
1423 	if (*outstr == NULL)
1424 		/* No specific out capability; use "me". */
1425 		*outstr = ltgetstr("me", spp);
1426 	if (*outstr == NULL)
1427 		/* Don't even have "me"; use a null string. */
1428 		*outstr = "";
1429 }
1430 
1431 #endif /* MSDOS_COMPILER */
1432 
1433 
1434 /*
1435  * Below are the functions which perform all the
1436  * terminal-specific screen manipulation.
1437  */
1438 
1439 
1440 #if MSDOS_COMPILER
1441 
1442 #if MSDOS_COMPILER==WIN32C
1443 	static void
1444 _settextposition(int row, int col)
1445 {
1446 	COORD cpos;
1447 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1448 
1449 	GetConsoleScreenBufferInfo(con_out, &csbi);
1450 	cpos.X = csbi.srWindow.Left + (col - 1);
1451 	cpos.Y = csbi.srWindow.Top + (row - 1);
1452 	SetConsoleCursorPosition(con_out, cpos);
1453 }
1454 #endif
1455 
1456 /*
1457  * Initialize the screen to the correct color at startup.
1458  */
1459 	static void
1460 initcolor(VOID_PARAM)
1461 {
1462 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1463 	intensevideo();
1464 #endif
1465 	SETCOLORS(nm_fg_color, nm_bg_color);
1466 #if 0
1467 	/*
1468 	 * This clears the screen at startup.  This is different from
1469 	 * the behavior of other versions of less.  Disable it for now.
1470 	 */
1471 	char *blanks;
1472 	int row;
1473 	int col;
1474 
1475 	/*
1476 	 * Create a complete, blank screen using "normal" colors.
1477 	 */
1478 	SETCOLORS(nm_fg_color, nm_bg_color);
1479 	blanks = (char *) ecalloc(width+1, sizeof(char));
1480 	for (col = 0;  col < sc_width;  col++)
1481 		blanks[col] = ' ';
1482 	blanks[sc_width] = '\0';
1483 	for (row = 0;  row < sc_height;  row++)
1484 		_outtext(blanks);
1485 	free(blanks);
1486 #endif
1487 }
1488 #endif
1489 
1490 #if MSDOS_COMPILER==WIN32C
1491 
1492 /*
1493  * Termcap-like init with a private win32 console.
1494  */
1495 	static void
1496 win32_init_term(VOID_PARAM)
1497 {
1498 	CONSOLE_SCREEN_BUFFER_INFO scr;
1499 	COORD size;
1500 
1501 	if (con_out_save == INVALID_HANDLE_VALUE)
1502 		return;
1503 
1504 	GetConsoleScreenBufferInfo(con_out_save, &scr);
1505 
1506 	if (con_out_ours == INVALID_HANDLE_VALUE)
1507 	{
1508 		DWORD output_mode;
1509 
1510 		/*
1511 		 * Create our own screen buffer, so that we
1512 		 * may restore the original when done.
1513 		 */
1514 		con_out_ours = CreateConsoleScreenBuffer(
1515 			GENERIC_WRITE | GENERIC_READ,
1516 			FILE_SHARE_WRITE | FILE_SHARE_READ,
1517 			(LPSECURITY_ATTRIBUTES) NULL,
1518 			CONSOLE_TEXTMODE_BUFFER,
1519 			(LPVOID) NULL);
1520 		/*
1521 		 * Enable underline, if available.
1522 		 */
1523 		GetConsoleMode(con_out_ours, &output_mode);
1524 		have_ul = SetConsoleMode(con_out_ours,
1525 			    output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1526 	}
1527 
1528 	size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1529 	size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1530 	SetConsoleScreenBufferSize(con_out_ours, size);
1531 	SetConsoleActiveScreenBuffer(con_out_ours);
1532 	con_out = con_out_ours;
1533 }
1534 
1535 /*
1536  * Restore the startup console.
1537  */
1538 	static void
1539 win32_deinit_term(VOID_PARAM)
1540 {
1541 	if (con_out_save == INVALID_HANDLE_VALUE)
1542 		return;
1543 	if (quitting)
1544 		(void) CloseHandle(con_out_ours);
1545 	SetConsoleActiveScreenBuffer(con_out_save);
1546 	con_out = con_out_save;
1547 }
1548 
1549 #endif
1550 
1551 /*
1552  * Configure the termimal so mouse clicks and wheel moves
1553  * produce input to less.
1554  */
1555 	public void
1556 init_mouse(VOID_PARAM)
1557 {
1558 	if (!mousecap)
1559 		return;
1560 #if !MSDOS_COMPILER
1561 	tputs(sc_s_mousecap, sc_height, putchr);
1562 #else
1563 #if MSDOS_COMPILER==WIN32C
1564 	SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT);
1565 #endif
1566 #endif
1567 }
1568 
1569 /*
1570  * Configure the terminal so mouse clicks and wheel moves
1571  * are handled by the system (so text can be selected, etc).
1572  */
1573 	public void
1574 deinit_mouse(VOID_PARAM)
1575 {
1576 	if (!mousecap)
1577 		return;
1578 #if !MSDOS_COMPILER
1579 	tputs(sc_e_mousecap, sc_height, putchr);
1580 #else
1581 #if MSDOS_COMPILER==WIN32C
1582 	SetConsoleMode(tty, ENABLE_PROCESSED_INPUT);
1583 #endif
1584 #endif
1585 }
1586 
1587 /*
1588  * Initialize terminal
1589  */
1590 	public void
1591 init(VOID_PARAM)
1592 {
1593 #if !MSDOS_COMPILER
1594 	if (!(quit_if_one_screen && one_screen))
1595 	{
1596 		if (!no_init)
1597 			tputs(sc_init, sc_height, putchr);
1598 		if (!no_keypad)
1599 			tputs(sc_s_keypad, sc_height, putchr);
1600 		init_mouse();
1601 	}
1602 	if (top_scroll)
1603 	{
1604 		int i;
1605 
1606 		/*
1607 		 * This is nice to terminals with no alternate screen,
1608 		 * but with saved scrolled-off-the-top lines.  This way,
1609 		 * no previous line is lost, but we start with a whole
1610 		 * screen to ourself.
1611 		 */
1612 		for (i = 1; i < sc_height; i++)
1613 			putchr('\n');
1614 	} else
1615 		line_left();
1616 #else
1617 #if MSDOS_COMPILER==WIN32C
1618 	if (!no_init)
1619 		win32_init_term();
1620 #endif
1621 	initcolor();
1622 	flush();
1623 #endif
1624 	init_done = 1;
1625 }
1626 
1627 /*
1628  * Deinitialize terminal
1629  */
1630 	public void
1631 deinit(VOID_PARAM)
1632 {
1633 	if (!init_done)
1634 		return;
1635 #if !MSDOS_COMPILER
1636 	if (!(quit_if_one_screen && one_screen))
1637 	{
1638 		deinit_mouse();
1639 		if (!no_keypad)
1640 			tputs(sc_e_keypad, sc_height, putchr);
1641 		if (!no_init)
1642 			tputs(sc_deinit, sc_height, putchr);
1643 	}
1644 #else
1645 	/* Restore system colors. */
1646 	SETCOLORS(sy_fg_color, sy_bg_color);
1647 #if MSDOS_COMPILER==WIN32C
1648 	if (!no_init)
1649 		win32_deinit_term();
1650 #else
1651 	/* Need clreol to make SETCOLORS take effect. */
1652 	clreol();
1653 #endif
1654 #endif
1655 	init_done = 0;
1656 }
1657 
1658 /*
1659  * Home cursor (move to upper left corner of screen).
1660  */
1661 	public void
1662 home(VOID_PARAM)
1663 {
1664 #if !MSDOS_COMPILER
1665 	tputs(sc_home, 1, putchr);
1666 #else
1667 	flush();
1668 	_settextposition(1,1);
1669 #endif
1670 }
1671 
1672 /*
1673  * Add a blank line (called with cursor at home).
1674  * Should scroll the display down.
1675  */
1676 	public void
1677 add_line(VOID_PARAM)
1678 {
1679 #if !MSDOS_COMPILER
1680 	tputs(sc_addline, sc_height, putchr);
1681 #else
1682 	flush();
1683 #if MSDOS_COMPILER==MSOFTC
1684 	_scrolltextwindow(_GSCROLLDOWN);
1685 	_settextposition(1,1);
1686 #else
1687 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1688 	movetext(1,1, sc_width,sc_height-1, 1,2);
1689 	gotoxy(1,1);
1690 	clreol();
1691 #else
1692 #if MSDOS_COMPILER==WIN32C
1693     {
1694 	CHAR_INFO fillchar;
1695 	SMALL_RECT rcSrc, rcClip;
1696 	COORD new_org;
1697 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1698 
1699 	GetConsoleScreenBufferInfo(con_out,&csbi);
1700 
1701 	/* The clip rectangle is the entire visible screen. */
1702 	rcClip.Left = csbi.srWindow.Left;
1703 	rcClip.Top = csbi.srWindow.Top;
1704 	rcClip.Right = csbi.srWindow.Right;
1705 	rcClip.Bottom = csbi.srWindow.Bottom;
1706 
1707 	/* The source rectangle is the visible screen minus the last line. */
1708 	rcSrc = rcClip;
1709 	rcSrc.Bottom--;
1710 
1711 	/* Move the top left corner of the source window down one row. */
1712 	new_org.X = rcSrc.Left;
1713 	new_org.Y = rcSrc.Top + 1;
1714 
1715 	/* Fill the right character and attributes. */
1716 	fillchar.Char.AsciiChar = ' ';
1717 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1718 	fillchar.Attributes = curr_attr;
1719 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1720 	_settextposition(1,1);
1721     }
1722 #endif
1723 #endif
1724 #endif
1725 #endif
1726 }
1727 
1728 #if 0
1729 /*
1730  * Remove the n topmost lines and scroll everything below it in the
1731  * window upward.  This is needed to stop leaking the topmost line
1732  * into the scrollback buffer when we go down-one-line (in WIN32).
1733  */
1734 	public void
1735 remove_top(n)
1736 	int n;
1737 {
1738 #if MSDOS_COMPILER==WIN32C
1739 	SMALL_RECT rcSrc, rcClip;
1740 	CHAR_INFO fillchar;
1741 	COORD new_org;
1742 	CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1743 
1744 	if (n >= sc_height - 1)
1745 	{
1746 		clear();
1747 		home();
1748 		return;
1749 	}
1750 
1751 	flush();
1752 
1753 	GetConsoleScreenBufferInfo(con_out, &csbi);
1754 
1755 	/* Get the extent of all-visible-rows-but-the-last. */
1756 	rcSrc.Left    = csbi.srWindow.Left;
1757 	rcSrc.Top     = csbi.srWindow.Top + n;
1758 	rcSrc.Right   = csbi.srWindow.Right;
1759 	rcSrc.Bottom  = csbi.srWindow.Bottom;
1760 
1761 	/* Get the clip rectangle. */
1762 	rcClip.Left   = rcSrc.Left;
1763 	rcClip.Top    = csbi.srWindow.Top;
1764 	rcClip.Right  = rcSrc.Right;
1765 	rcClip.Bottom = rcSrc.Bottom ;
1766 
1767 	/* Move the source window up n rows. */
1768 	new_org.X = rcSrc.Left;
1769 	new_org.Y = rcSrc.Top - n;
1770 
1771 	/* Fill the right character and attributes. */
1772 	fillchar.Char.AsciiChar = ' ';
1773 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1774 	fillchar.Attributes = curr_attr;
1775 
1776 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1777 
1778 	/* Position cursor on first blank line. */
1779 	goto_line(sc_height - n - 1);
1780 #endif
1781 }
1782 #endif
1783 
1784 #if MSDOS_COMPILER==WIN32C
1785 /*
1786  * Clear the screen.
1787  */
1788 	static void
1789 win32_clear(VOID_PARAM)
1790 {
1791 	/*
1792 	 * This will clear only the currently visible rows of the NT
1793 	 * console buffer, which means none of the precious scrollback
1794 	 * rows are touched making for faster scrolling.  Note that, if
1795 	 * the window has fewer columns than the console buffer (i.e.
1796 	 * there is a horizontal scrollbar as well), the entire width
1797 	 * of the visible rows will be cleared.
1798 	 */
1799 	COORD topleft;
1800 	DWORD nchars;
1801 	DWORD winsz;
1802 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1803 
1804 	/* get the number of cells in the current buffer */
1805 	GetConsoleScreenBufferInfo(con_out, &csbi);
1806 	winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1807 	topleft.X = 0;
1808 	topleft.Y = csbi.srWindow.Top;
1809 
1810 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1811 	FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1812 	FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1813 }
1814 
1815 /*
1816  * Remove the n topmost lines and scroll everything below it in the
1817  * window upward.
1818  */
1819 	public void
1820 win32_scroll_up(n)
1821 	int n;
1822 {
1823 	SMALL_RECT rcSrc, rcClip;
1824 	CHAR_INFO fillchar;
1825 	COORD topleft;
1826 	COORD new_org;
1827 	DWORD nchars;
1828 	DWORD size;
1829 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1830 
1831 	if (n <= 0)
1832 		return;
1833 
1834 	if (n >= sc_height - 1)
1835 	{
1836 		win32_clear();
1837 		_settextposition(1,1);
1838 		return;
1839 	}
1840 
1841 	/* Get the extent of what will remain visible after scrolling. */
1842 	GetConsoleScreenBufferInfo(con_out, &csbi);
1843 	rcSrc.Left    = csbi.srWindow.Left;
1844 	rcSrc.Top     = csbi.srWindow.Top + n;
1845 	rcSrc.Right   = csbi.srWindow.Right;
1846 	rcSrc.Bottom  = csbi.srWindow.Bottom;
1847 
1848 	/* Get the clip rectangle. */
1849 	rcClip.Left   = rcSrc.Left;
1850 	rcClip.Top    = csbi.srWindow.Top;
1851 	rcClip.Right  = rcSrc.Right;
1852 	rcClip.Bottom = rcSrc.Bottom ;
1853 
1854 	/* Move the source text to the top of the screen. */
1855 	new_org.X = rcSrc.Left;
1856 	new_org.Y = rcClip.Top;
1857 
1858 	/* Fill the right character and attributes. */
1859 	fillchar.Char.AsciiChar = ' ';
1860 	fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1861 
1862 	/* Scroll the window. */
1863 	SetConsoleTextAttribute(con_out, fillchar.Attributes);
1864 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1865 
1866 	/* Clear remaining lines at bottom. */
1867 	topleft.X = csbi.dwCursorPosition.X;
1868 	topleft.Y = rcSrc.Bottom - n;
1869 	size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1870 	FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1871 		&nchars);
1872 	FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1873 		&nchars);
1874 	SetConsoleTextAttribute(con_out, curr_attr);
1875 
1876 	/* Move cursor n lines up from where it was. */
1877 	csbi.dwCursorPosition.Y -= n;
1878 	SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1879 }
1880 #endif
1881 
1882 /*
1883  * Move cursor to lower left corner of screen.
1884  */
1885 	public void
1886 lower_left(VOID_PARAM)
1887 {
1888 	if (!init_done)
1889 		return;
1890 #if !MSDOS_COMPILER
1891 	tputs(sc_lower_left, 1, putchr);
1892 #else
1893 	flush();
1894 	_settextposition(sc_height, 1);
1895 #endif
1896 }
1897 
1898 /*
1899  * Move cursor to left position of current line.
1900  */
1901 	public void
1902 line_left(VOID_PARAM)
1903 {
1904 #if !MSDOS_COMPILER
1905 	tputs(sc_return, 1, putchr);
1906 #else
1907 	int row;
1908 	flush();
1909 #if MSDOS_COMPILER==WIN32C
1910 	{
1911 		CONSOLE_SCREEN_BUFFER_INFO scr;
1912 		GetConsoleScreenBufferInfo(con_out, &scr);
1913 		row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1914 	}
1915 #else
1916 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1917 		row = wherey();
1918 #else
1919 	{
1920 		struct rccoord tpos = _gettextposition();
1921 		row = tpos.row;
1922 	}
1923 #endif
1924 #endif
1925 	_settextposition(row, 1);
1926 #endif
1927 }
1928 
1929 /*
1930  * Check if the console size has changed and reset internals
1931  * (in lieu of SIGWINCH for WIN32).
1932  */
1933 	public void
1934 check_winch(VOID_PARAM)
1935 {
1936 #if MSDOS_COMPILER==WIN32C
1937 	CONSOLE_SCREEN_BUFFER_INFO scr;
1938 	COORD size;
1939 
1940 	if (con_out == INVALID_HANDLE_VALUE)
1941 		return;
1942 
1943 	flush();
1944 	GetConsoleScreenBufferInfo(con_out, &scr);
1945 	size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1946 	size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1947 	if (size.Y != sc_height || size.X != sc_width)
1948 	{
1949 		sc_height = size.Y;
1950 		sc_width = size.X;
1951 		if (!no_init && con_out_ours == con_out)
1952 			SetConsoleScreenBufferSize(con_out, size);
1953 		pos_init();
1954 		wscroll = (sc_height + 1) / 2;
1955 		screen_trashed = 1;
1956 	}
1957 #endif
1958 }
1959 
1960 /*
1961  * Goto a specific line on the screen.
1962  */
1963 	public void
1964 goto_line(sindex)
1965 	int sindex;
1966 {
1967 #if !MSDOS_COMPILER
1968 	tputs(tgoto(sc_move, 0, sindex), 1, putchr);
1969 #else
1970 	flush();
1971 	_settextposition(sindex+1, 1);
1972 #endif
1973 }
1974 
1975 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1976 /*
1977  * Create an alternate screen which is all white.
1978  * This screen is used to create a "flash" effect, by displaying it
1979  * briefly and then switching back to the normal screen.
1980  * {{ Yuck!  There must be a better way to get a visual bell. }}
1981  */
1982 	static void
1983 create_flash(VOID_PARAM)
1984 {
1985 #if MSDOS_COMPILER==MSOFTC
1986 	struct videoconfig w;
1987 	char *blanks;
1988 	int row, col;
1989 
1990 	_getvideoconfig(&w);
1991 	videopages = w.numvideopages;
1992 	if (videopages < 2)
1993 	{
1994 		at_enter(AT_STANDOUT);
1995 		at_exit();
1996 	} else
1997 	{
1998 		_setactivepage(1);
1999 		at_enter(AT_STANDOUT);
2000 		blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2001 		for (col = 0;  col < w.numtextcols;  col++)
2002 			blanks[col] = ' ';
2003 		for (row = w.numtextrows;  row > 0;  row--)
2004 			_outmem(blanks, w.numtextcols);
2005 		_setactivepage(0);
2006 		_setvisualpage(0);
2007 		free(blanks);
2008 		at_exit();
2009 	}
2010 #else
2011 #if MSDOS_COMPILER==BORLANDC
2012 	int n;
2013 
2014 	whitescreen = (unsigned short *)
2015 		malloc(sc_width * sc_height * sizeof(short));
2016 	if (whitescreen == NULL)
2017 		return;
2018 	for (n = 0;  n < sc_width * sc_height;  n++)
2019 		whitescreen[n] = 0x7020;
2020 #endif
2021 #endif
2022 	flash_created = 1;
2023 }
2024 #endif /* MSDOS_COMPILER */
2025 
2026 /*
2027  * Output the "visual bell", if there is one.
2028  */
2029 	public void
2030 vbell(VOID_PARAM)
2031 {
2032 #if !MSDOS_COMPILER
2033 	if (*sc_visual_bell == '\0')
2034 		return;
2035 	tputs(sc_visual_bell, sc_height, putchr);
2036 #else
2037 #if MSDOS_COMPILER==DJGPPC
2038 	ScreenVisualBell();
2039 #else
2040 #if MSDOS_COMPILER==MSOFTC
2041 	/*
2042 	 * Create a flash screen on the second video page.
2043 	 * Switch to that page, then switch back.
2044 	 */
2045 	if (!flash_created)
2046 		create_flash();
2047 	if (videopages < 2)
2048 		return;
2049 	_setvisualpage(1);
2050 	delay(100);
2051 	_setvisualpage(0);
2052 #else
2053 #if MSDOS_COMPILER==BORLANDC
2054 	unsigned short *currscreen;
2055 
2056 	/*
2057 	 * Get a copy of the current screen.
2058 	 * Display the flash screen.
2059 	 * Then restore the old screen.
2060 	 */
2061 	if (!flash_created)
2062 		create_flash();
2063 	if (whitescreen == NULL)
2064 		return;
2065 	currscreen = (unsigned short *)
2066 		malloc(sc_width * sc_height * sizeof(short));
2067 	if (currscreen == NULL) return;
2068 	gettext(1, 1, sc_width, sc_height, currscreen);
2069 	puttext(1, 1, sc_width, sc_height, whitescreen);
2070 	delay(100);
2071 	puttext(1, 1, sc_width, sc_height, currscreen);
2072 	free(currscreen);
2073 #else
2074 #if MSDOS_COMPILER==WIN32C
2075 	/* paint screen with an inverse color */
2076 	clear();
2077 
2078 	/* leave it displayed for 100 msec. */
2079 	Sleep(100);
2080 
2081 	/* restore with a redraw */
2082 	repaint();
2083 #endif
2084 #endif
2085 #endif
2086 #endif
2087 #endif
2088 }
2089 
2090 /*
2091  * Make a noise.
2092  */
2093 	static void
2094 beep(VOID_PARAM)
2095 {
2096 #if !MSDOS_COMPILER
2097 	putchr(CONTROL('G'));
2098 #else
2099 #if MSDOS_COMPILER==WIN32C
2100 	MessageBeep(0);
2101 #else
2102 	write(1, "\7", 1);
2103 #endif
2104 #endif
2105 }
2106 
2107 /*
2108  * Ring the terminal bell.
2109  */
2110 	public void
2111 bell(VOID_PARAM)
2112 {
2113 	if (quiet == VERY_QUIET)
2114 		vbell();
2115 	else
2116 		beep();
2117 }
2118 
2119 /*
2120  * Clear the screen.
2121  */
2122 	public void
2123 clear(VOID_PARAM)
2124 {
2125 #if !MSDOS_COMPILER
2126 	tputs(sc_clear, sc_height, putchr);
2127 #else
2128 	flush();
2129 #if MSDOS_COMPILER==WIN32C
2130 	win32_clear();
2131 #else
2132 	_clearscreen(_GCLEARSCREEN);
2133 #endif
2134 #endif
2135 }
2136 
2137 /*
2138  * Clear from the cursor to the end of the cursor's line.
2139  * {{ This must not move the cursor. }}
2140  */
2141 	public void
2142 clear_eol(VOID_PARAM)
2143 {
2144 #if !MSDOS_COMPILER
2145 	tputs(sc_eol_clear, 1, putchr);
2146 #else
2147 #if MSDOS_COMPILER==MSOFTC
2148 	short top, left;
2149 	short bot, right;
2150 	struct rccoord tpos;
2151 
2152 	flush();
2153 	/*
2154 	 * Save current state.
2155 	 */
2156 	tpos = _gettextposition();
2157 	_gettextwindow(&top, &left, &bot, &right);
2158 	/*
2159 	 * Set a temporary window to the current line,
2160 	 * from the cursor's position to the right edge of the screen.
2161 	 * Then clear that window.
2162 	 */
2163 	_settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2164 	_clearscreen(_GWINDOW);
2165 	/*
2166 	 * Restore state.
2167 	 */
2168 	_settextwindow(top, left, bot, right);
2169 	_settextposition(tpos.row, tpos.col);
2170 #else
2171 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2172 	flush();
2173 	clreol();
2174 #else
2175 #if MSDOS_COMPILER==WIN32C
2176 	DWORD           nchars;
2177 	COORD           cpos;
2178 	CONSOLE_SCREEN_BUFFER_INFO scr;
2179 
2180 	flush();
2181 	memset(&scr, 0, sizeof(scr));
2182 	GetConsoleScreenBufferInfo(con_out, &scr);
2183 	cpos.X = scr.dwCursorPosition.X;
2184 	cpos.Y = scr.dwCursorPosition.Y;
2185 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2186 	FillConsoleOutputAttribute(con_out, curr_attr,
2187 		scr.dwSize.X - cpos.X, cpos, &nchars);
2188 	FillConsoleOutputCharacter(con_out, ' ',
2189 		scr.dwSize.X - cpos.X, cpos, &nchars);
2190 #endif
2191 #endif
2192 #endif
2193 #endif
2194 }
2195 
2196 /*
2197  * Clear the current line.
2198  * Clear the screen if there's off-screen memory below the display.
2199  */
2200 	static void
2201 clear_eol_bot(VOID_PARAM)
2202 {
2203 #if MSDOS_COMPILER
2204 	clear_eol();
2205 #else
2206 	if (below_mem)
2207 		tputs(sc_eos_clear, 1, putchr);
2208 	else
2209 		tputs(sc_eol_clear, 1, putchr);
2210 #endif
2211 }
2212 
2213 /*
2214  * Clear the bottom line of the display.
2215  * Leave the cursor at the beginning of the bottom line.
2216  */
2217 	public void
2218 clear_bot(VOID_PARAM)
2219 {
2220 	/*
2221 	 * If we're in a non-normal attribute mode, temporarily exit
2222 	 * the mode while we do the clear.  Some terminals fill the
2223 	 * cleared area with the current attribute.
2224 	 */
2225 	if (oldbot)
2226 		lower_left();
2227 	else
2228 		line_left();
2229 
2230 	if (attrmode == AT_NORMAL)
2231 		clear_eol_bot();
2232 	else
2233 	{
2234 		int saved_attrmode = attrmode;
2235 
2236 		at_exit();
2237 		clear_eol_bot();
2238 		at_enter(saved_attrmode);
2239 	}
2240 }
2241 
2242 	public void
2243 at_enter(attr)
2244 	int attr;
2245 {
2246 	attr = apply_at_specials(attr);
2247 
2248 #if !MSDOS_COMPILER
2249 	/* The one with the most priority is last.  */
2250 	if (attr & AT_UNDERLINE)
2251 		tputs(sc_u_in, 1, putchr);
2252 	if (attr & AT_BOLD)
2253 		tputs(sc_b_in, 1, putchr);
2254 	if (attr & AT_BLINK)
2255 		tputs(sc_bl_in, 1, putchr);
2256 	if (attr & AT_STANDOUT)
2257 		tputs(sc_s_in, 1, putchr);
2258 #else
2259 	flush();
2260 	/* The one with the most priority is first.  */
2261 	if (attr & AT_STANDOUT)
2262 	{
2263 		SETCOLORS(so_fg_color, so_bg_color);
2264 	} else if (attr & AT_BLINK)
2265 	{
2266 		SETCOLORS(bl_fg_color, bl_bg_color);
2267 	}
2268 	else if (attr & AT_BOLD)
2269 	{
2270 		SETCOLORS(bo_fg_color, bo_bg_color);
2271 	}
2272 	else if (attr & AT_UNDERLINE)
2273 	{
2274 		SETCOLORS(ul_fg_color, ul_bg_color);
2275 	}
2276 #endif
2277 
2278 	attrmode = attr;
2279 }
2280 
2281 	public void
2282 at_exit(VOID_PARAM)
2283 {
2284 #if !MSDOS_COMPILER
2285 	/* Undo things in the reverse order we did them.  */
2286 	if (attrmode & AT_STANDOUT)
2287 		tputs(sc_s_out, 1, putchr);
2288 	if (attrmode & AT_BLINK)
2289 		tputs(sc_bl_out, 1, putchr);
2290 	if (attrmode & AT_BOLD)
2291 		tputs(sc_b_out, 1, putchr);
2292 	if (attrmode & AT_UNDERLINE)
2293 		tputs(sc_u_out, 1, putchr);
2294 #else
2295 	flush();
2296 	SETCOLORS(nm_fg_color, nm_bg_color);
2297 #endif
2298 
2299 	attrmode = AT_NORMAL;
2300 }
2301 
2302 	public void
2303 at_switch(attr)
2304 	int attr;
2305 {
2306 	int new_attrmode = apply_at_specials(attr);
2307 	int ignore_modes = AT_ANSI;
2308 
2309 	if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2310 	{
2311 		at_exit();
2312 		at_enter(attr);
2313 	}
2314 }
2315 
2316 	public int
2317 is_at_equiv(attr1, attr2)
2318 	int attr1;
2319 	int attr2;
2320 {
2321 	attr1 = apply_at_specials(attr1);
2322 	attr2 = apply_at_specials(attr2);
2323 
2324 	return (attr1 == attr2);
2325 }
2326 
2327 	public int
2328 apply_at_specials(attr)
2329 	int attr;
2330 {
2331 	if (attr & AT_BINARY)
2332 		attr |= binattr;
2333 	if (attr & AT_HILITE)
2334 		attr |= AT_STANDOUT;
2335 	attr &= ~(AT_BINARY|AT_HILITE);
2336 
2337 	return attr;
2338 }
2339 
2340 #if 0 /* No longer used */
2341 /*
2342  * Erase the character to the left of the cursor
2343  * and move the cursor left.
2344  */
2345 	public void
2346 backspace(VOID_PARAM)
2347 {
2348 #if !MSDOS_COMPILER
2349 	/*
2350 	 * Erase the previous character by overstriking with a space.
2351 	 */
2352 	tputs(sc_backspace, 1, putchr);
2353 	putchr(' ');
2354 	tputs(sc_backspace, 1, putchr);
2355 #else
2356 #if MSDOS_COMPILER==MSOFTC
2357 	struct rccoord tpos;
2358 
2359 	flush();
2360 	tpos = _gettextposition();
2361 	if (tpos.col <= 1)
2362 		return;
2363 	_settextposition(tpos.row, tpos.col-1);
2364 	_outtext(" ");
2365 	_settextposition(tpos.row, tpos.col-1);
2366 #else
2367 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2368 	cputs("\b");
2369 #else
2370 #if MSDOS_COMPILER==WIN32C
2371 	COORD cpos;
2372 	DWORD cChars;
2373 	CONSOLE_SCREEN_BUFFER_INFO scr;
2374 
2375 	flush();
2376 	GetConsoleScreenBufferInfo(con_out, &scr);
2377 	cpos = scr.dwCursorPosition;
2378 	if (cpos.X <= 0)
2379 		return;
2380 	cpos.X--;
2381 	SetConsoleCursorPosition(con_out, cpos);
2382 	FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2383 	SetConsoleCursorPosition(con_out, cpos);
2384 #endif
2385 #endif
2386 #endif
2387 #endif
2388 }
2389 #endif /* 0 */
2390 
2391 /*
2392  * Output a plain backspace, without erasing the previous char.
2393  */
2394 	public void
2395 putbs(VOID_PARAM)
2396 {
2397 	if (termcap_debug)
2398 		putstr("<bs>");
2399 	else
2400 	{
2401 #if !MSDOS_COMPILER
2402 	tputs(sc_backspace, 1, putchr);
2403 #else
2404 	int row, col;
2405 
2406 	flush();
2407 	{
2408 #if MSDOS_COMPILER==MSOFTC
2409 		struct rccoord tpos;
2410 		tpos = _gettextposition();
2411 		row = tpos.row;
2412 		col = tpos.col;
2413 #else
2414 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2415 		row = wherey();
2416 		col = wherex();
2417 #else
2418 #if MSDOS_COMPILER==WIN32C
2419 		CONSOLE_SCREEN_BUFFER_INFO scr;
2420 		GetConsoleScreenBufferInfo(con_out, &scr);
2421 		row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2422 		col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2423 #endif
2424 #endif
2425 #endif
2426 	}
2427 	if (col <= 1)
2428 		return;
2429 	_settextposition(row, col-1);
2430 #endif /* MSDOS_COMPILER */
2431 	}
2432 }
2433 
2434 #if MSDOS_COMPILER==WIN32C
2435 /*
2436  * Determine whether an input character is waiting to be read.
2437  */
2438 	public int
2439 win32_kbhit(VOID_PARAM)
2440 {
2441 	INPUT_RECORD ip;
2442 	DWORD read;
2443 
2444 	if (keyCount > 0)
2445 		return (TRUE);
2446 
2447 	currentKey.ascii = 0;
2448 	currentKey.scan = 0;
2449 
2450 	if (x11mouseCount > 0)
2451 	{
2452 		currentKey.ascii = x11mousebuf[x11mousePos++];
2453 		--x11mouseCount;
2454 		keyCount = 1;
2455 		return (TRUE);
2456 	}
2457 
2458 	/*
2459 	 * Wait for a real key-down event, but
2460 	 * ignore SHIFT and CONTROL key events.
2461 	 */
2462 	do
2463 	{
2464 		PeekConsoleInput(tty, &ip, 1, &read);
2465 		if (read == 0)
2466 			return (FALSE);
2467 		ReadConsoleInput(tty, &ip, 1, &read);
2468 		/* generate an X11 mouse sequence from the mouse event */
2469 		if (mousecap && ip.EventType == MOUSE_EVENT &&
2470 		    ip.Event.MouseEvent.dwEventFlags != MOUSE_MOVED)
2471 		{
2472 			x11mousebuf[3] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.X + 1;
2473 			x11mousebuf[4] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.Y + 1;
2474 			switch (ip.Event.MouseEvent.dwEventFlags)
2475 			{
2476 			case 0: /* press or release */
2477 				if (ip.Event.MouseEvent.dwButtonState == 0)
2478 					x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2479 				else if (ip.Event.MouseEvent.dwButtonState & (FROM_LEFT_3RD_BUTTON_PRESSED | FROM_LEFT_4TH_BUTTON_PRESSED))
2480 					continue;
2481 				else
2482 					x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON1 + ((int)ip.Event.MouseEvent.dwButtonState << 1);
2483 				break;
2484 			case MOUSE_WHEELED:
2485 				x11mousebuf[2] = X11MOUSE_OFFSET + (((int)ip.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2486 				break;
2487 			default:
2488 				continue;
2489 			}
2490 			x11mousePos = 0;
2491 			x11mouseCount = 5;
2492 			currentKey.ascii = ESC;
2493 			keyCount = 1;
2494 			return (TRUE);
2495 		}
2496 	} while (ip.EventType != KEY_EVENT ||
2497 		ip.Event.KeyEvent.bKeyDown != TRUE ||
2498 		ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2499 		ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2500 		ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2501 		ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2502 
2503 	currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2504 	currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2505 	keyCount = ip.Event.KeyEvent.wRepeatCount;
2506 
2507 	if (ip.Event.KeyEvent.dwControlKeyState &
2508 		(LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2509 	{
2510 		switch (currentKey.scan)
2511 		{
2512 		case PCK_ALT_E:     /* letter 'E' */
2513 			currentKey.ascii = 0;
2514 			break;
2515 		}
2516 	} else if (ip.Event.KeyEvent.dwControlKeyState &
2517 		(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2518 	{
2519 		switch (currentKey.scan)
2520 		{
2521 		case PCK_RIGHT: /* right arrow */
2522 			currentKey.scan = PCK_CTL_RIGHT;
2523 			break;
2524 		case PCK_LEFT: /* left arrow */
2525 			currentKey.scan = PCK_CTL_LEFT;
2526 			break;
2527 		case PCK_DELETE: /* delete */
2528 			currentKey.scan = PCK_CTL_DELETE;
2529 			break;
2530 		}
2531 	} else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2532 	{
2533 		switch (currentKey.scan)
2534 		{
2535 		case PCK_SHIFT_TAB: /* tab */
2536 			currentKey.ascii = 0;
2537 			break;
2538 		}
2539 	}
2540 
2541 	return (TRUE);
2542 }
2543 
2544 /*
2545  * Read a character from the keyboard.
2546  */
2547 	public char
2548 WIN32getch(VOID_PARAM)
2549 {
2550 	int ascii;
2551 
2552 	if (pending_scancode)
2553 	{
2554 		pending_scancode = 0;
2555 		return ((char)(currentKey.scan & 0x00FF));
2556 	}
2557 
2558 	do {
2559 		while (win32_kbhit() == FALSE)
2560 		{
2561 			Sleep(20);
2562 			if (ABORT_SIGS())
2563 				return ('\003');
2564 			continue;
2565 		}
2566 		keyCount --;
2567 		ascii = currentKey.ascii;
2568 		/*
2569 		 * On PC's, the extended keys return a 2 byte sequence beginning
2570 		 * with '00', so if the ascii code is 00, the next byte will be
2571 		 * the lsb of the scan code.
2572 		 */
2573 		pending_scancode = (ascii == 0x00);
2574 	} while (pending_scancode &&
2575 		(currentKey.scan == PCK_CAPS_LOCK || currentKey.scan == PCK_NUM_LOCK));
2576 
2577 	return ((char)ascii);
2578 }
2579 #endif
2580 
2581 #if MSDOS_COMPILER
2582 /*
2583  */
2584 	public void
2585 WIN32setcolors(fg, bg)
2586 	int fg;
2587 	int bg;
2588 {
2589 	SETCOLORS(fg, bg);
2590 }
2591 
2592 /*
2593  */
2594 	public void
2595 WIN32textout(text, len)
2596 	char *text;
2597 	int len;
2598 {
2599 #if MSDOS_COMPILER==WIN32C
2600 	DWORD written;
2601 	if (utf_mode == 2)
2602 	{
2603 		/*
2604 		 * We've got UTF-8 text in a non-UTF-8 console.  Convert it to
2605 		 * wide and use WriteConsoleW.
2606 		 */
2607 		WCHAR wtext[1024];
2608 		len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext,
2609 					  sizeof(wtext)/sizeof(*wtext));
2610 		WriteConsoleW(con_out, wtext, len, &written, NULL);
2611 	} else
2612 		WriteConsole(con_out, text, len, &written, NULL);
2613 #else
2614 	char c = text[len];
2615 	text[len] = '\0';
2616 	cputs(text);
2617 	text[len] = c;
2618 #endif
2619 }
2620 #endif
2621