xref: /freebsd/contrib/less/screen.c (revision 7cc42f6d)
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 	char *s;
646 
647 	if (termcap_debug)
648 	{
649 		struct env { struct env *next; char *name; char *value; };
650 		static struct env *envs = NULL;
651 		struct env *p;
652 		for (p = envs;  p != NULL;  p = p->next)
653 			if (strcmp(p->name, capname) == 0)
654 				return p->value;
655 		p = (struct env *) ecalloc(1, sizeof(struct env));
656 		p->name = save(capname);
657 		p->value = (char *) ecalloc(strlen(capname)+3, sizeof(char));
658 		sprintf(p->value, "<%s>", capname);
659 		p->next = envs;
660 		envs = p;
661 		return p->value;
662 	}
663 	SNPRINTF1(name, sizeof(name), "LESS_TERMCAP_%s", capname);
664 	return (lgetenv(name));
665 }
666 
667 	static int
668 ltgetflag(capname)
669 	char *capname;
670 {
671 	char *s;
672 
673 	if ((s = ltget_env(capname)) != NULL)
674 		return (*s != '\0' && *s != '0');
675 	if (hardcopy)
676 		return (0);
677 	return (tgetflag(capname));
678 }
679 
680 	static int
681 ltgetnum(capname)
682 	char *capname;
683 {
684 	char *s;
685 
686 	if ((s = ltget_env(capname)) != NULL)
687 		return (atoi(s));
688 	if (hardcopy)
689 		return (-1);
690 	return (tgetnum(capname));
691 }
692 
693 	static char *
694 ltgetstr(capname, pp)
695 	char *capname;
696 	char **pp;
697 {
698 	char *s;
699 
700 	if ((s = ltget_env(capname)) != NULL)
701 		return (s);
702 	if (hardcopy)
703 		return (NULL);
704 	return (tgetstr(capname, pp));
705 }
706 #endif /* MSDOS_COMPILER */
707 
708 /*
709  * Get size of the output screen.
710  */
711 	public void
712 scrsize(VOID_PARAM)
713 {
714 	char *s;
715 	int sys_height;
716 	int sys_width;
717 #if !MSDOS_COMPILER
718 	int n;
719 #endif
720 
721 #define	DEF_SC_WIDTH	80
722 #if MSDOS_COMPILER
723 #define	DEF_SC_HEIGHT	25
724 #else
725 #define	DEF_SC_HEIGHT	24
726 #endif
727 
728 
729 	sys_width = sys_height = 0;
730 
731 #if MSDOS_COMPILER==MSOFTC
732 	{
733 		struct videoconfig w;
734 		_getvideoconfig(&w);
735 		sys_height = w.numtextrows;
736 		sys_width = w.numtextcols;
737 	}
738 #else
739 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
740 	{
741 		struct text_info w;
742 		gettextinfo(&w);
743 		sys_height = w.screenheight;
744 		sys_width = w.screenwidth;
745 	}
746 #else
747 #if MSDOS_COMPILER==WIN32C
748 	{
749 		CONSOLE_SCREEN_BUFFER_INFO scr;
750 		GetConsoleScreenBufferInfo(con_out, &scr);
751 		sys_height = scr.srWindow.Bottom - scr.srWindow.Top + 1;
752 		sys_width = scr.srWindow.Right - scr.srWindow.Left + 1;
753 	}
754 #else
755 #if OS2
756 	{
757 		int s[2];
758 		_scrsize(s);
759 		sys_width = s[0];
760 		sys_height = s[1];
761 		/*
762 		 * When using terminal emulators for XFree86/OS2, the
763 		 * _scrsize function does not work well.
764 		 * Call the scrsize.exe program to get the window size.
765 		 */
766 		windowid = getenv("WINDOWID");
767 		if (windowid != NULL)
768 		{
769 			FILE *fd = popen("scrsize", "rt");
770 			if (fd != NULL)
771 			{
772 				int w, h;
773 				fscanf(fd, "%i %i", &w, &h);
774 				if (w > 0 && h > 0)
775 				{
776 					sys_width = w;
777 					sys_height = h;
778 				}
779 				pclose(fd);
780 			}
781 		}
782 	}
783 #else
784 #ifdef TIOCGWINSZ
785 	{
786 		struct winsize w;
787 		if (ioctl(2, TIOCGWINSZ, &w) == 0)
788 		{
789 			if (w.ws_row > 0)
790 				sys_height = w.ws_row;
791 			if (w.ws_col > 0)
792 				sys_width = w.ws_col;
793 		}
794 	}
795 #else
796 #ifdef WIOCGETD
797 	{
798 		struct uwdata w;
799 		if (ioctl(2, WIOCGETD, &w) == 0)
800 		{
801 			if (w.uw_height > 0)
802 				sys_height = w.uw_height / w.uw_vs;
803 			if (w.uw_width > 0)
804 				sys_width = w.uw_width / w.uw_hs;
805 		}
806 	}
807 #endif
808 #endif
809 #endif
810 #endif
811 #endif
812 #endif
813 
814 	if (sys_height > 0)
815 		sc_height = sys_height;
816 	else if ((s = lgetenv("LINES")) != NULL)
817 		sc_height = atoi(s);
818 #if !MSDOS_COMPILER
819 	else if ((n = ltgetnum("li")) > 0)
820  		sc_height = n;
821 #endif
822 	if (sc_height <= 0)
823 		sc_height = DEF_SC_HEIGHT;
824 
825 	if (sys_width > 0)
826 		sc_width = sys_width;
827 	else if ((s = lgetenv("COLUMNS")) != NULL)
828 		sc_width = atoi(s);
829 #if !MSDOS_COMPILER
830 	else if ((n = ltgetnum("co")) > 0)
831  		sc_width = n;
832 #endif
833 	if (sc_width <= 0)
834 		sc_width = DEF_SC_WIDTH;
835 }
836 
837 #if MSDOS_COMPILER==MSOFTC
838 /*
839  * Figure out how many empty loops it takes to delay a millisecond.
840  */
841 	static void
842 get_clock(VOID_PARAM)
843 {
844 	clock_t start;
845 
846 	/*
847 	 * Get synchronized at the start of a tick.
848 	 */
849 	start = clock();
850 	while (clock() == start)
851 		;
852 	/*
853 	 * Now count loops till the next tick.
854 	 */
855 	start = clock();
856 	msec_loops = 0;
857 	while (clock() == start)
858 		msec_loops++;
859 	/*
860 	 * Convert from (loops per clock) to (loops per millisecond).
861 	 */
862 	msec_loops *= CLOCKS_PER_SEC;
863 	msec_loops /= 1000;
864 }
865 
866 /*
867  * Delay for a specified number of milliseconds.
868  */
869 	static void
870 delay(msec)
871 	int msec;
872 {
873 	long i;
874 
875 	while (msec-- > 0)
876 	{
877 		for (i = 0;  i < msec_loops;  i++)
878 			(void) clock();
879 	}
880 }
881 #endif
882 
883 /*
884  * Return the characters actually input by a "special" key.
885  */
886 	public char *
887 special_key_str(key)
888 	int key;
889 {
890 	static char tbuf[40];
891 	char *s;
892 #if MSDOS_COMPILER || OS2
893 	static char k_right[]		= { '\340', PCK_RIGHT, 0 };
894 	static char k_left[]		= { '\340', PCK_LEFT, 0  };
895 	static char k_ctl_right[]	= { '\340', PCK_CTL_RIGHT, 0  };
896 	static char k_ctl_left[]	= { '\340', PCK_CTL_LEFT, 0  };
897 	static char k_insert[]		= { '\340', PCK_INSERT, 0  };
898 	static char k_delete[]		= { '\340', PCK_DELETE, 0  };
899 	static char k_ctl_delete[]	= { '\340', PCK_CTL_DELETE, 0  };
900 	static char k_ctl_backspace[]	= { '\177', 0 };
901 	static char k_home[]		= { '\340', PCK_HOME, 0 };
902 	static char k_end[]		= { '\340', PCK_END, 0 };
903 	static char k_up[]		= { '\340', PCK_UP, 0 };
904 	static char k_down[]		= { '\340', PCK_DOWN, 0 };
905 	static char k_backtab[]		= { '\340', PCK_SHIFT_TAB, 0 };
906 	static char k_pagedown[]	= { '\340', PCK_PAGEDOWN, 0 };
907 	static char k_pageup[]		= { '\340', PCK_PAGEUP, 0 };
908 	static char k_f1[]		= { '\340', PCK_F1, 0 };
909 #endif
910 #if !MSDOS_COMPILER
911 	char *sp = tbuf;
912 #endif
913 
914 	switch (key)
915 	{
916 #if OS2
917 	/*
918 	 * If windowid is not NULL, assume less is executed in
919 	 * the XFree86 environment.
920 	 */
921 	case SK_RIGHT_ARROW:
922 		s = windowid ? ltgetstr("kr", &sp) : k_right;
923 		break;
924 	case SK_LEFT_ARROW:
925 		s = windowid ? ltgetstr("kl", &sp) : k_left;
926 		break;
927 	case SK_UP_ARROW:
928 		s = windowid ? ltgetstr("ku", &sp) : k_up;
929 		break;
930 	case SK_DOWN_ARROW:
931 		s = windowid ? ltgetstr("kd", &sp) : k_down;
932 		break;
933 	case SK_PAGE_UP:
934 		s = windowid ? ltgetstr("kP", &sp) : k_pageup;
935 		break;
936 	case SK_PAGE_DOWN:
937 		s = windowid ? ltgetstr("kN", &sp) : k_pagedown;
938 		break;
939 	case SK_HOME:
940 		s = windowid ? ltgetstr("kh", &sp) : k_home;
941 		break;
942 	case SK_END:
943 		s = windowid ? ltgetstr("@7", &sp) : k_end;
944 		break;
945 	case SK_DELETE:
946 		s = windowid ? ltgetstr("kD", &sp) : k_delete;
947 		if (s == NULL)
948 		{
949 			tbuf[0] = '\177';
950 			tbuf[1] = '\0';
951 			s = tbuf;
952 		}
953 		break;
954 #endif
955 #if MSDOS_COMPILER
956 	case SK_RIGHT_ARROW:
957 		s = k_right;
958 		break;
959 	case SK_LEFT_ARROW:
960 		s = k_left;
961 		break;
962 	case SK_UP_ARROW:
963 		s = k_up;
964 		break;
965 	case SK_DOWN_ARROW:
966 		s = k_down;
967 		break;
968 	case SK_PAGE_UP:
969 		s = k_pageup;
970 		break;
971 	case SK_PAGE_DOWN:
972 		s = k_pagedown;
973 		break;
974 	case SK_HOME:
975 		s = k_home;
976 		break;
977 	case SK_END:
978 		s = k_end;
979 		break;
980 	case SK_DELETE:
981 		s = k_delete;
982 		break;
983 #endif
984 #if MSDOS_COMPILER || OS2
985 	case SK_INSERT:
986 		s = k_insert;
987 		break;
988 	case SK_CTL_LEFT_ARROW:
989 		s = k_ctl_left;
990 		break;
991 	case SK_CTL_RIGHT_ARROW:
992 		s = k_ctl_right;
993 		break;
994 	case SK_CTL_BACKSPACE:
995 		s = k_ctl_backspace;
996 		break;
997 	case SK_CTL_DELETE:
998 		s = k_ctl_delete;
999 		break;
1000 	case SK_F1:
1001 		s = k_f1;
1002 		break;
1003 	case SK_BACKTAB:
1004 		s = k_backtab;
1005 		break;
1006 #else
1007 	case SK_RIGHT_ARROW:
1008 		s = ltgetstr("kr", &sp);
1009 		break;
1010 	case SK_LEFT_ARROW:
1011 		s = ltgetstr("kl", &sp);
1012 		break;
1013 	case SK_UP_ARROW:
1014 		s = ltgetstr("ku", &sp);
1015 		break;
1016 	case SK_DOWN_ARROW:
1017 		s = ltgetstr("kd", &sp);
1018 		break;
1019 	case SK_PAGE_UP:
1020 		s = ltgetstr("kP", &sp);
1021 		break;
1022 	case SK_PAGE_DOWN:
1023 		s = ltgetstr("kN", &sp);
1024 		break;
1025 	case SK_HOME:
1026 		s = ltgetstr("kh", &sp);
1027 		break;
1028 	case SK_END:
1029 		s = ltgetstr("@7", &sp);
1030 		break;
1031 	case SK_DELETE:
1032 		s = ltgetstr("kD", &sp);
1033 		if (s == NULL)
1034 		{
1035 			tbuf[0] = '\177';
1036 			tbuf[1] = '\0';
1037 			s = tbuf;
1038 		}
1039 		break;
1040 #endif
1041 	case SK_CONTROL_K:
1042 		tbuf[0] = CONTROL('K');
1043 		tbuf[1] = '\0';
1044 		s = tbuf;
1045 		break;
1046 	default:
1047 		return (NULL);
1048 	}
1049 	return (s);
1050 }
1051 
1052 /*
1053  * Get terminal capabilities via termcap.
1054  */
1055 	public void
1056 get_term(VOID_PARAM)
1057 {
1058 	termcap_debug = !isnullenv(lgetenv("LESS_TERMCAP_DEBUG"));
1059 #if MSDOS_COMPILER
1060 	auto_wrap = 1;
1061 	ignaw = 0;
1062 	can_goto_line = 1;
1063 	clear_bg = 1;
1064 	/*
1065 	 * Set up default colors.
1066 	 * The xx_s_width and xx_e_width vars are already initialized to 0.
1067 	 */
1068 #if MSDOS_COMPILER==MSOFTC
1069 	sy_bg_color = _getbkcolor();
1070 	sy_fg_color = _gettextcolor();
1071 	get_clock();
1072 #else
1073 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1074     {
1075 	struct text_info w;
1076 	gettextinfo(&w);
1077 	sy_bg_color = (w.attribute >> 4) & 0x0F;
1078 	sy_fg_color = (w.attribute >> 0) & 0x0F;
1079     }
1080 #else
1081 #if MSDOS_COMPILER==WIN32C
1082     {
1083 	DWORD nread;
1084 	CONSOLE_SCREEN_BUFFER_INFO scr;
1085 
1086 	con_out_save = con_out = GetStdHandle(STD_OUTPUT_HANDLE);
1087 	/*
1088 	 * Always open stdin in binary. Note this *must* be done
1089 	 * before any file operations have been done on fd0.
1090 	 */
1091 	SET_BINARY(0);
1092 	GetConsoleScreenBufferInfo(con_out, &scr);
1093 	ReadConsoleOutputAttribute(con_out, &curr_attr,
1094 					1, scr.dwCursorPosition, &nread);
1095 	sy_bg_color = (curr_attr & BG_COLORS) >> 4; /* normalize */
1096 	sy_fg_color = curr_attr & FG_COLORS;
1097     }
1098 #endif
1099 #endif
1100 #endif
1101 	nm_fg_color = sy_fg_color;
1102 	nm_bg_color = sy_bg_color;
1103 	bo_fg_color = 11;
1104 	bo_bg_color = 0;
1105 	ul_fg_color = 9;
1106 	ul_bg_color = 0;
1107 	so_fg_color = 15;
1108 	so_bg_color = 9;
1109 	bl_fg_color = 15;
1110 	bl_bg_color = 0;
1111 	sgr_mode = 0;
1112 
1113 	/*
1114 	 * Get size of the screen.
1115 	 */
1116 	scrsize();
1117 	pos_init();
1118 
1119 
1120 #else /* !MSDOS_COMPILER */
1121 {
1122 	char *sp;
1123 	char *t1, *t2;
1124 	char *term;
1125 	char termbuf[TERMBUF_SIZE];
1126 
1127 	static char sbuf[TERMSBUF_SIZE];
1128 
1129 #if OS2
1130 	/*
1131 	 * Make sure the termcap database is available.
1132 	 */
1133 	sp = lgetenv("TERMCAP");
1134 	if (isnullenv(sp))
1135 	{
1136 		char *termcap;
1137 		if ((sp = homefile("termcap.dat")) != NULL)
1138 		{
1139 			termcap = (char *) ecalloc(strlen(sp)+9, sizeof(char));
1140 			sprintf(termcap, "TERMCAP=%s", sp);
1141 			free(sp);
1142 			putenv(termcap);
1143 		}
1144 	}
1145 #endif
1146 	/*
1147 	 * Find out what kind of terminal this is.
1148 	 */
1149  	if ((term = lgetenv("TERM")) == NULL)
1150  		term = DEFAULT_TERM;
1151 	hardcopy = 0;
1152  	if (tgetent(termbuf, term) != TGETENT_OK)
1153  		hardcopy = 1;
1154  	if (ltgetflag("hc"))
1155 		hardcopy = 1;
1156 
1157 	/*
1158 	 * Get size of the screen.
1159 	 */
1160 	scrsize();
1161 	pos_init();
1162 
1163 	auto_wrap = ltgetflag("am");
1164 	ignaw = ltgetflag("xn");
1165 	above_mem = ltgetflag("da");
1166 	below_mem = ltgetflag("db");
1167 	clear_bg = ltgetflag("ut");
1168 
1169 	/*
1170 	 * Assumes termcap variable "sg" is the printing width of:
1171 	 * the standout sequence, the end standout sequence,
1172 	 * the underline sequence, the end underline sequence,
1173 	 * the boldface sequence, and the end boldface sequence.
1174 	 */
1175 	if ((so_s_width = ltgetnum("sg")) < 0)
1176 		so_s_width = 0;
1177 	so_e_width = so_s_width;
1178 
1179 	bo_s_width = bo_e_width = so_s_width;
1180 	ul_s_width = ul_e_width = so_s_width;
1181 	bl_s_width = bl_e_width = so_s_width;
1182 
1183 #if HILITE_SEARCH
1184 	if (so_s_width > 0 || so_e_width > 0)
1185 		/*
1186 		 * Disable highlighting by default on magic cookie terminals.
1187 		 * Turning on highlighting might change the displayed width
1188 		 * of a line, causing the display to get messed up.
1189 		 * The user can turn it back on with -g,
1190 		 * but she won't like the results.
1191 		 */
1192 		hilite_search = 0;
1193 #endif
1194 
1195 	/*
1196 	 * Get various string-valued capabilities.
1197 	 */
1198 	sp = sbuf;
1199 
1200 #if HAVE_OSPEED
1201 	sc_pad = ltgetstr("pc", &sp);
1202 	if (sc_pad != NULL)
1203 		PC = *sc_pad;
1204 #endif
1205 
1206 	sc_s_keypad = ltgetstr("ks", &sp);
1207 	if (sc_s_keypad == NULL)
1208 		sc_s_keypad = "";
1209 	sc_e_keypad = ltgetstr("ke", &sp);
1210 	if (sc_e_keypad == NULL)
1211 		sc_e_keypad = "";
1212 	kent = ltgetstr("@8", &sp);
1213 
1214 	sc_s_mousecap = ltgetstr("MOUSE_START", &sp);
1215 	if (sc_s_mousecap == NULL)
1216 		sc_s_mousecap = ESCS "[?1000h" ESCS "[?1006h";
1217 	sc_e_mousecap = ltgetstr("MOUSE_END", &sp);
1218 	if (sc_e_mousecap == NULL)
1219 		sc_e_mousecap = ESCS "[?1006l" ESCS "[?1000l";
1220 
1221 	sc_init = ltgetstr("ti", &sp);
1222 	if (sc_init == NULL)
1223 		sc_init = "";
1224 
1225 	sc_deinit= ltgetstr("te", &sp);
1226 	if (sc_deinit == NULL)
1227 		sc_deinit = "";
1228 
1229 	sc_eol_clear = ltgetstr("ce", &sp);
1230 	if (sc_eol_clear == NULL || *sc_eol_clear == '\0')
1231 	{
1232 		missing_cap = 1;
1233 		sc_eol_clear = "";
1234 	}
1235 
1236 	sc_eos_clear = ltgetstr("cd", &sp);
1237 	if (below_mem && (sc_eos_clear == NULL || *sc_eos_clear == '\0'))
1238 	{
1239 		missing_cap = 1;
1240 		sc_eos_clear = "";
1241 	}
1242 
1243 	sc_clear = ltgetstr("cl", &sp);
1244 	if (sc_clear == NULL || *sc_clear == '\0')
1245 	{
1246 		missing_cap = 1;
1247 		sc_clear = "\n\n";
1248 	}
1249 
1250 	sc_move = ltgetstr("cm", &sp);
1251 	if (sc_move == NULL || *sc_move == '\0')
1252 	{
1253 		/*
1254 		 * This is not an error here, because we don't
1255 		 * always need sc_move.
1256 		 * We need it only if we don't have home or lower-left.
1257 		 */
1258 		sc_move = "";
1259 		can_goto_line = 0;
1260 	} else
1261 		can_goto_line = 1;
1262 
1263 	tmodes("so", "se", &sc_s_in, &sc_s_out, "", "", &sp);
1264 	tmodes("us", "ue", &sc_u_in, &sc_u_out, sc_s_in, sc_s_out, &sp);
1265 	tmodes("md", "me", &sc_b_in, &sc_b_out, sc_s_in, sc_s_out, &sp);
1266 	tmodes("mb", "me", &sc_bl_in, &sc_bl_out, sc_s_in, sc_s_out, &sp);
1267 
1268 	sc_visual_bell = ltgetstr("vb", &sp);
1269 	if (sc_visual_bell == NULL)
1270 		sc_visual_bell = "";
1271 
1272 	if (ltgetflag("bs"))
1273 		sc_backspace = "\b";
1274 	else
1275 	{
1276 		sc_backspace = ltgetstr("bc", &sp);
1277 		if (sc_backspace == NULL || *sc_backspace == '\0')
1278 			sc_backspace = "\b";
1279 	}
1280 
1281 	/*
1282 	 * Choose between using "ho" and "cm" ("home" and "cursor move")
1283 	 * to move the cursor to the upper left corner of the screen.
1284 	 */
1285 	t1 = ltgetstr("ho", &sp);
1286 	if (t1 == NULL)
1287 		t1 = "";
1288 	if (*sc_move == '\0')
1289 		t2 = "";
1290 	else
1291 	{
1292 		strcpy(sp, tgoto(sc_move, 0, 0));
1293 		t2 = sp;
1294 		sp += strlen(sp) + 1;
1295 	}
1296 	sc_home = cheaper(t1, t2, "|\b^");
1297 
1298 	/*
1299 	 * Choose between using "ll" and "cm"  ("lower left" and "cursor move")
1300 	 * to move the cursor to the lower left corner of the screen.
1301 	 */
1302 	t1 = ltgetstr("ll", &sp);
1303 	if (t1 == NULL)
1304 		t1 = "";
1305 	if (*sc_move == '\0')
1306 		t2 = "";
1307 	else
1308 	{
1309 		strcpy(sp, tgoto(sc_move, 0, sc_height-1));
1310 		t2 = sp;
1311 		sp += strlen(sp) + 1;
1312 	}
1313 	sc_lower_left = cheaper(t1, t2, "\r");
1314 
1315 	/*
1316 	 * Get carriage return string.
1317 	 */
1318 	sc_return = ltgetstr("cr", &sp);
1319 	if (sc_return == NULL)
1320 		sc_return = "\r";
1321 
1322 	/*
1323 	 * Choose between using "al" or "sr" ("add line" or "scroll reverse")
1324 	 * to add a line at the top of the screen.
1325 	 */
1326 	t1 = ltgetstr("al", &sp);
1327 	if (t1 == NULL)
1328 		t1 = "";
1329 	t2 = ltgetstr("sr", &sp);
1330 	if (t2 == NULL)
1331 		t2 = "";
1332 #if OS2
1333 	if (*t1 == '\0' && *t2 == '\0')
1334 		sc_addline = "";
1335 	else
1336 #endif
1337 	if (above_mem)
1338 		sc_addline = t1;
1339 	else
1340 		sc_addline = cheaper(t1, t2, "");
1341 	if (*sc_addline == '\0')
1342 	{
1343 		/*
1344 		 * Force repaint on any backward movement.
1345 		 */
1346 		no_back_scroll = 1;
1347 	}
1348 }
1349 #endif /* MSDOS_COMPILER */
1350 }
1351 
1352 #if !MSDOS_COMPILER
1353 /*
1354  * Return the cost of displaying a termcap string.
1355  * We use the trick of calling tputs, but as a char printing function
1356  * we give it inc_costcount, which just increments "costcount".
1357  * This tells us how many chars would be printed by using this string.
1358  * {{ Couldn't we just use strlen? }}
1359  */
1360 static int costcount;
1361 
1362 /*ARGSUSED*/
1363 	static int
1364 inc_costcount(c)
1365 	int c;
1366 {
1367 	costcount++;
1368 	return (c);
1369 }
1370 
1371 	static int
1372 cost(t)
1373 	char *t;
1374 {
1375 	costcount = 0;
1376 	tputs(t, sc_height, inc_costcount);
1377 	return (costcount);
1378 }
1379 
1380 /*
1381  * Return the "best" of the two given termcap strings.
1382  * The best, if both exist, is the one with the lower
1383  * cost (see cost() function).
1384  */
1385 	static char *
1386 cheaper(t1, t2, def)
1387 	char *t1, *t2;
1388 	char *def;
1389 {
1390 	if (*t1 == '\0' && *t2 == '\0')
1391 	{
1392 		missing_cap = 1;
1393 		return (def);
1394 	}
1395 	if (*t1 == '\0')
1396 		return (t2);
1397 	if (*t2 == '\0')
1398 		return (t1);
1399 	if (cost(t1) < cost(t2))
1400 		return (t1);
1401 	return (t2);
1402 }
1403 
1404 	static void
1405 tmodes(incap, outcap, instr, outstr, def_instr, def_outstr, spp)
1406 	char *incap;
1407 	char *outcap;
1408 	char **instr;
1409 	char **outstr;
1410 	char *def_instr;
1411 	char *def_outstr;
1412 	char **spp;
1413 {
1414 	*instr = ltgetstr(incap, spp);
1415 	if (*instr == NULL)
1416 	{
1417 		/* Use defaults. */
1418 		*instr = def_instr;
1419 		*outstr = def_outstr;
1420 		return;
1421 	}
1422 
1423 	*outstr = ltgetstr(outcap, spp);
1424 	if (*outstr == NULL)
1425 		/* No specific out capability; use "me". */
1426 		*outstr = ltgetstr("me", spp);
1427 	if (*outstr == NULL)
1428 		/* Don't even have "me"; use a null string. */
1429 		*outstr = "";
1430 }
1431 
1432 #endif /* MSDOS_COMPILER */
1433 
1434 
1435 /*
1436  * Below are the functions which perform all the
1437  * terminal-specific screen manipulation.
1438  */
1439 
1440 
1441 #if MSDOS_COMPILER
1442 
1443 #if MSDOS_COMPILER==WIN32C
1444 	static void
1445 _settextposition(int row, int col)
1446 {
1447 	COORD cpos;
1448 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1449 
1450 	GetConsoleScreenBufferInfo(con_out, &csbi);
1451 	cpos.X = csbi.srWindow.Left + (col - 1);
1452 	cpos.Y = csbi.srWindow.Top + (row - 1);
1453 	SetConsoleCursorPosition(con_out, cpos);
1454 }
1455 #endif
1456 
1457 /*
1458  * Initialize the screen to the correct color at startup.
1459  */
1460 	static void
1461 initcolor(VOID_PARAM)
1462 {
1463 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1464 	intensevideo();
1465 #endif
1466 	SETCOLORS(nm_fg_color, nm_bg_color);
1467 #if 0
1468 	/*
1469 	 * This clears the screen at startup.  This is different from
1470 	 * the behavior of other versions of less.  Disable it for now.
1471 	 */
1472 	char *blanks;
1473 	int row;
1474 	int col;
1475 
1476 	/*
1477 	 * Create a complete, blank screen using "normal" colors.
1478 	 */
1479 	SETCOLORS(nm_fg_color, nm_bg_color);
1480 	blanks = (char *) ecalloc(width+1, sizeof(char));
1481 	for (col = 0;  col < sc_width;  col++)
1482 		blanks[col] = ' ';
1483 	blanks[sc_width] = '\0';
1484 	for (row = 0;  row < sc_height;  row++)
1485 		_outtext(blanks);
1486 	free(blanks);
1487 #endif
1488 }
1489 #endif
1490 
1491 #if MSDOS_COMPILER==WIN32C
1492 
1493 /*
1494  * Termcap-like init with a private win32 console.
1495  */
1496 	static void
1497 win32_init_term(VOID_PARAM)
1498 {
1499 	CONSOLE_SCREEN_BUFFER_INFO scr;
1500 	COORD size;
1501 
1502 	if (con_out_save == INVALID_HANDLE_VALUE)
1503 		return;
1504 
1505 	GetConsoleScreenBufferInfo(con_out_save, &scr);
1506 
1507 	if (con_out_ours == INVALID_HANDLE_VALUE)
1508 	{
1509 		DWORD output_mode;
1510 
1511 		/*
1512 		 * Create our own screen buffer, so that we
1513 		 * may restore the original when done.
1514 		 */
1515 		con_out_ours = CreateConsoleScreenBuffer(
1516 			GENERIC_WRITE | GENERIC_READ,
1517 			FILE_SHARE_WRITE | FILE_SHARE_READ,
1518 			(LPSECURITY_ATTRIBUTES) NULL,
1519 			CONSOLE_TEXTMODE_BUFFER,
1520 			(LPVOID) NULL);
1521 		/*
1522 		 * Enable underline, if available.
1523 		 */
1524 		GetConsoleMode(con_out_ours, &output_mode);
1525 		have_ul = SetConsoleMode(con_out_ours,
1526 			    output_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1527 	}
1528 
1529 	size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1530 	size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1531 	SetConsoleScreenBufferSize(con_out_ours, size);
1532 	SetConsoleActiveScreenBuffer(con_out_ours);
1533 	con_out = con_out_ours;
1534 }
1535 
1536 /*
1537  * Restore the startup console.
1538  */
1539 	static void
1540 win32_deinit_term(VOID_PARAM)
1541 {
1542 	if (con_out_save == INVALID_HANDLE_VALUE)
1543 		return;
1544 	if (quitting)
1545 		(void) CloseHandle(con_out_ours);
1546 	SetConsoleActiveScreenBuffer(con_out_save);
1547 	con_out = con_out_save;
1548 }
1549 
1550 #endif
1551 
1552 /*
1553  * Configure the termimal so mouse clicks and wheel moves
1554  * produce input to less.
1555  */
1556 	public void
1557 init_mouse(VOID_PARAM)
1558 {
1559 	if (!mousecap)
1560 		return;
1561 #if !MSDOS_COMPILER
1562 	tputs(sc_s_mousecap, sc_height, putchr);
1563 #else
1564 #if MSDOS_COMPILER==WIN32C
1565 	SetConsoleMode(tty, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT);
1566 #endif
1567 #endif
1568 }
1569 
1570 /*
1571  * Configure the terminal so mouse clicks and wheel moves
1572  * are handled by the system (so text can be selected, etc).
1573  */
1574 	public void
1575 deinit_mouse(VOID_PARAM)
1576 {
1577 	if (!mousecap)
1578 		return;
1579 #if !MSDOS_COMPILER
1580 	tputs(sc_e_mousecap, sc_height, putchr);
1581 #else
1582 #if MSDOS_COMPILER==WIN32C
1583 	SetConsoleMode(tty, ENABLE_PROCESSED_INPUT);
1584 #endif
1585 #endif
1586 }
1587 
1588 /*
1589  * Initialize terminal
1590  */
1591 	public void
1592 init(VOID_PARAM)
1593 {
1594 #if !MSDOS_COMPILER
1595 	if (!(quit_if_one_screen && one_screen))
1596 	{
1597 		if (!no_init)
1598 			tputs(sc_init, sc_height, putchr);
1599 		if (!no_keypad)
1600 			tputs(sc_s_keypad, sc_height, putchr);
1601 		init_mouse();
1602 	}
1603 	if (top_scroll)
1604 	{
1605 		int i;
1606 
1607 		/*
1608 		 * This is nice to terminals with no alternate screen,
1609 		 * but with saved scrolled-off-the-top lines.  This way,
1610 		 * no previous line is lost, but we start with a whole
1611 		 * screen to ourself.
1612 		 */
1613 		for (i = 1; i < sc_height; i++)
1614 			putchr('\n');
1615 	} else
1616 		line_left();
1617 #else
1618 #if MSDOS_COMPILER==WIN32C
1619 	if (!no_init)
1620 		win32_init_term();
1621 #endif
1622 	initcolor();
1623 	flush();
1624 #endif
1625 	init_done = 1;
1626 }
1627 
1628 /*
1629  * Deinitialize terminal
1630  */
1631 	public void
1632 deinit(VOID_PARAM)
1633 {
1634 	if (!init_done)
1635 		return;
1636 #if !MSDOS_COMPILER
1637 	if (!(quit_if_one_screen && one_screen))
1638 	{
1639 		deinit_mouse();
1640 		if (!no_keypad)
1641 			tputs(sc_e_keypad, sc_height, putchr);
1642 		if (!no_init)
1643 			tputs(sc_deinit, sc_height, putchr);
1644 	}
1645 #else
1646 	/* Restore system colors. */
1647 	SETCOLORS(sy_fg_color, sy_bg_color);
1648 #if MSDOS_COMPILER==WIN32C
1649 	if (!no_init)
1650 		win32_deinit_term();
1651 #else
1652 	/* Need clreol to make SETCOLORS take effect. */
1653 	clreol();
1654 #endif
1655 #endif
1656 	init_done = 0;
1657 }
1658 
1659 /*
1660  * Home cursor (move to upper left corner of screen).
1661  */
1662 	public void
1663 home(VOID_PARAM)
1664 {
1665 #if !MSDOS_COMPILER
1666 	tputs(sc_home, 1, putchr);
1667 #else
1668 	flush();
1669 	_settextposition(1,1);
1670 #endif
1671 }
1672 
1673 /*
1674  * Add a blank line (called with cursor at home).
1675  * Should scroll the display down.
1676  */
1677 	public void
1678 add_line(VOID_PARAM)
1679 {
1680 #if !MSDOS_COMPILER
1681 	tputs(sc_addline, sc_height, putchr);
1682 #else
1683 	flush();
1684 #if MSDOS_COMPILER==MSOFTC
1685 	_scrolltextwindow(_GSCROLLDOWN);
1686 	_settextposition(1,1);
1687 #else
1688 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1689 	movetext(1,1, sc_width,sc_height-1, 1,2);
1690 	gotoxy(1,1);
1691 	clreol();
1692 #else
1693 #if MSDOS_COMPILER==WIN32C
1694     {
1695 	CHAR_INFO fillchar;
1696 	SMALL_RECT rcSrc, rcClip;
1697 	COORD new_org;
1698 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1699 
1700 	GetConsoleScreenBufferInfo(con_out,&csbi);
1701 
1702 	/* The clip rectangle is the entire visible screen. */
1703 	rcClip.Left = csbi.srWindow.Left;
1704 	rcClip.Top = csbi.srWindow.Top;
1705 	rcClip.Right = csbi.srWindow.Right;
1706 	rcClip.Bottom = csbi.srWindow.Bottom;
1707 
1708 	/* The source rectangle is the visible screen minus the last line. */
1709 	rcSrc = rcClip;
1710 	rcSrc.Bottom--;
1711 
1712 	/* Move the top left corner of the source window down one row. */
1713 	new_org.X = rcSrc.Left;
1714 	new_org.Y = rcSrc.Top + 1;
1715 
1716 	/* Fill the right character and attributes. */
1717 	fillchar.Char.AsciiChar = ' ';
1718 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1719 	fillchar.Attributes = curr_attr;
1720 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1721 	_settextposition(1,1);
1722     }
1723 #endif
1724 #endif
1725 #endif
1726 #endif
1727 }
1728 
1729 #if 0
1730 /*
1731  * Remove the n topmost lines and scroll everything below it in the
1732  * window upward.  This is needed to stop leaking the topmost line
1733  * into the scrollback buffer when we go down-one-line (in WIN32).
1734  */
1735 	public void
1736 remove_top(n)
1737 	int n;
1738 {
1739 #if MSDOS_COMPILER==WIN32C
1740 	SMALL_RECT rcSrc, rcClip;
1741 	CHAR_INFO fillchar;
1742 	COORD new_org;
1743 	CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
1744 
1745 	if (n >= sc_height - 1)
1746 	{
1747 		clear();
1748 		home();
1749 		return;
1750 	}
1751 
1752 	flush();
1753 
1754 	GetConsoleScreenBufferInfo(con_out, &csbi);
1755 
1756 	/* Get the extent of all-visible-rows-but-the-last. */
1757 	rcSrc.Left    = csbi.srWindow.Left;
1758 	rcSrc.Top     = csbi.srWindow.Top + n;
1759 	rcSrc.Right   = csbi.srWindow.Right;
1760 	rcSrc.Bottom  = csbi.srWindow.Bottom;
1761 
1762 	/* Get the clip rectangle. */
1763 	rcClip.Left   = rcSrc.Left;
1764 	rcClip.Top    = csbi.srWindow.Top;
1765 	rcClip.Right  = rcSrc.Right;
1766 	rcClip.Bottom = rcSrc.Bottom ;
1767 
1768 	/* Move the source window up n rows. */
1769 	new_org.X = rcSrc.Left;
1770 	new_org.Y = rcSrc.Top - n;
1771 
1772 	/* Fill the right character and attributes. */
1773 	fillchar.Char.AsciiChar = ' ';
1774 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1775 	fillchar.Attributes = curr_attr;
1776 
1777 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1778 
1779 	/* Position cursor on first blank line. */
1780 	goto_line(sc_height - n - 1);
1781 #endif
1782 }
1783 #endif
1784 
1785 #if MSDOS_COMPILER==WIN32C
1786 /*
1787  * Clear the screen.
1788  */
1789 	static void
1790 win32_clear(VOID_PARAM)
1791 {
1792 	/*
1793 	 * This will clear only the currently visible rows of the NT
1794 	 * console buffer, which means none of the precious scrollback
1795 	 * rows are touched making for faster scrolling.  Note that, if
1796 	 * the window has fewer columns than the console buffer (i.e.
1797 	 * there is a horizontal scrollbar as well), the entire width
1798 	 * of the visible rows will be cleared.
1799 	 */
1800 	COORD topleft;
1801 	DWORD nchars;
1802 	DWORD winsz;
1803 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1804 
1805 	/* get the number of cells in the current buffer */
1806 	GetConsoleScreenBufferInfo(con_out, &csbi);
1807 	winsz = csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
1808 	topleft.X = 0;
1809 	topleft.Y = csbi.srWindow.Top;
1810 
1811 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
1812 	FillConsoleOutputCharacter(con_out, ' ', winsz, topleft, &nchars);
1813 	FillConsoleOutputAttribute(con_out, curr_attr, winsz, topleft, &nchars);
1814 }
1815 
1816 /*
1817  * Remove the n topmost lines and scroll everything below it in the
1818  * window upward.
1819  */
1820 	public void
1821 win32_scroll_up(n)
1822 	int n;
1823 {
1824 	SMALL_RECT rcSrc, rcClip;
1825 	CHAR_INFO fillchar;
1826 	COORD topleft;
1827 	COORD new_org;
1828 	DWORD nchars;
1829 	DWORD size;
1830 	CONSOLE_SCREEN_BUFFER_INFO csbi;
1831 
1832 	if (n <= 0)
1833 		return;
1834 
1835 	if (n >= sc_height - 1)
1836 	{
1837 		win32_clear();
1838 		_settextposition(1,1);
1839 		return;
1840 	}
1841 
1842 	/* Get the extent of what will remain visible after scrolling. */
1843 	GetConsoleScreenBufferInfo(con_out, &csbi);
1844 	rcSrc.Left    = csbi.srWindow.Left;
1845 	rcSrc.Top     = csbi.srWindow.Top + n;
1846 	rcSrc.Right   = csbi.srWindow.Right;
1847 	rcSrc.Bottom  = csbi.srWindow.Bottom;
1848 
1849 	/* Get the clip rectangle. */
1850 	rcClip.Left   = rcSrc.Left;
1851 	rcClip.Top    = csbi.srWindow.Top;
1852 	rcClip.Right  = rcSrc.Right;
1853 	rcClip.Bottom = rcSrc.Bottom ;
1854 
1855 	/* Move the source text to the top of the screen. */
1856 	new_org.X = rcSrc.Left;
1857 	new_org.Y = rcClip.Top;
1858 
1859 	/* Fill the right character and attributes. */
1860 	fillchar.Char.AsciiChar = ' ';
1861 	fillchar.Attributes = MAKEATTR(nm_fg_color, nm_bg_color);
1862 
1863 	/* Scroll the window. */
1864 	SetConsoleTextAttribute(con_out, fillchar.Attributes);
1865 	ScrollConsoleScreenBuffer(con_out, &rcSrc, &rcClip, new_org, &fillchar);
1866 
1867 	/* Clear remaining lines at bottom. */
1868 	topleft.X = csbi.dwCursorPosition.X;
1869 	topleft.Y = rcSrc.Bottom - n;
1870 	size = (n * csbi.dwSize.X) + (rcSrc.Right - topleft.X);
1871 	FillConsoleOutputCharacter(con_out, ' ', size, topleft,
1872 		&nchars);
1873 	FillConsoleOutputAttribute(con_out, fillchar.Attributes, size, topleft,
1874 		&nchars);
1875 	SetConsoleTextAttribute(con_out, curr_attr);
1876 
1877 	/* Move cursor n lines up from where it was. */
1878 	csbi.dwCursorPosition.Y -= n;
1879 	SetConsoleCursorPosition(con_out, csbi.dwCursorPosition);
1880 }
1881 #endif
1882 
1883 /*
1884  * Move cursor to lower left corner of screen.
1885  */
1886 	public void
1887 lower_left(VOID_PARAM)
1888 {
1889 	if (!init_done)
1890 		return;
1891 #if !MSDOS_COMPILER
1892 	tputs(sc_lower_left, 1, putchr);
1893 #else
1894 	flush();
1895 	_settextposition(sc_height, 1);
1896 #endif
1897 }
1898 
1899 /*
1900  * Move cursor to left position of current line.
1901  */
1902 	public void
1903 line_left(VOID_PARAM)
1904 {
1905 #if !MSDOS_COMPILER
1906 	tputs(sc_return, 1, putchr);
1907 #else
1908 	int row;
1909 	flush();
1910 #if MSDOS_COMPILER==WIN32C
1911 	{
1912 		CONSOLE_SCREEN_BUFFER_INFO scr;
1913 		GetConsoleScreenBufferInfo(con_out, &scr);
1914 		row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
1915 	}
1916 #else
1917 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
1918 		row = wherey();
1919 #else
1920 	{
1921 		struct rccoord tpos = _gettextposition();
1922 		row = tpos.row;
1923 	}
1924 #endif
1925 #endif
1926 	_settextposition(row, 1);
1927 #endif
1928 }
1929 
1930 /*
1931  * Check if the console size has changed and reset internals
1932  * (in lieu of SIGWINCH for WIN32).
1933  */
1934 	public void
1935 check_winch(VOID_PARAM)
1936 {
1937 #if MSDOS_COMPILER==WIN32C
1938 	CONSOLE_SCREEN_BUFFER_INFO scr;
1939 	COORD size;
1940 
1941 	if (con_out == INVALID_HANDLE_VALUE)
1942 		return;
1943 
1944 	flush();
1945 	GetConsoleScreenBufferInfo(con_out, &scr);
1946 	size.Y = scr.srWindow.Bottom - scr.srWindow.Top + 1;
1947 	size.X = scr.srWindow.Right - scr.srWindow.Left + 1;
1948 	if (size.Y != sc_height || size.X != sc_width)
1949 	{
1950 		sc_height = size.Y;
1951 		sc_width = size.X;
1952 		if (!no_init && con_out_ours == con_out)
1953 			SetConsoleScreenBufferSize(con_out, size);
1954 		pos_init();
1955 		wscroll = (sc_height + 1) / 2;
1956 		screen_trashed = 1;
1957 	}
1958 #endif
1959 }
1960 
1961 /*
1962  * Goto a specific line on the screen.
1963  */
1964 	public void
1965 goto_line(sindex)
1966 	int sindex;
1967 {
1968 #if !MSDOS_COMPILER
1969 	tputs(tgoto(sc_move, 0, sindex), 1, putchr);
1970 #else
1971 	flush();
1972 	_settextposition(sindex+1, 1);
1973 #endif
1974 }
1975 
1976 #if MSDOS_COMPILER==MSOFTC || MSDOS_COMPILER==BORLANDC
1977 /*
1978  * Create an alternate screen which is all white.
1979  * This screen is used to create a "flash" effect, by displaying it
1980  * briefly and then switching back to the normal screen.
1981  * {{ Yuck!  There must be a better way to get a visual bell. }}
1982  */
1983 	static void
1984 create_flash(VOID_PARAM)
1985 {
1986 #if MSDOS_COMPILER==MSOFTC
1987 	struct videoconfig w;
1988 	char *blanks;
1989 	int row, col;
1990 
1991 	_getvideoconfig(&w);
1992 	videopages = w.numvideopages;
1993 	if (videopages < 2)
1994 	{
1995 		at_enter(AT_STANDOUT);
1996 		at_exit();
1997 	} else
1998 	{
1999 		_setactivepage(1);
2000 		at_enter(AT_STANDOUT);
2001 		blanks = (char *) ecalloc(w.numtextcols, sizeof(char));
2002 		for (col = 0;  col < w.numtextcols;  col++)
2003 			blanks[col] = ' ';
2004 		for (row = w.numtextrows;  row > 0;  row--)
2005 			_outmem(blanks, w.numtextcols);
2006 		_setactivepage(0);
2007 		_setvisualpage(0);
2008 		free(blanks);
2009 		at_exit();
2010 	}
2011 #else
2012 #if MSDOS_COMPILER==BORLANDC
2013 	int n;
2014 
2015 	whitescreen = (unsigned short *)
2016 		malloc(sc_width * sc_height * sizeof(short));
2017 	if (whitescreen == NULL)
2018 		return;
2019 	for (n = 0;  n < sc_width * sc_height;  n++)
2020 		whitescreen[n] = 0x7020;
2021 #endif
2022 #endif
2023 	flash_created = 1;
2024 }
2025 #endif /* MSDOS_COMPILER */
2026 
2027 /*
2028  * Output the "visual bell", if there is one.
2029  */
2030 	public void
2031 vbell(VOID_PARAM)
2032 {
2033 #if !MSDOS_COMPILER
2034 	if (*sc_visual_bell == '\0')
2035 		return;
2036 	tputs(sc_visual_bell, sc_height, putchr);
2037 #else
2038 #if MSDOS_COMPILER==DJGPPC
2039 	ScreenVisualBell();
2040 #else
2041 #if MSDOS_COMPILER==MSOFTC
2042 	/*
2043 	 * Create a flash screen on the second video page.
2044 	 * Switch to that page, then switch back.
2045 	 */
2046 	if (!flash_created)
2047 		create_flash();
2048 	if (videopages < 2)
2049 		return;
2050 	_setvisualpage(1);
2051 	delay(100);
2052 	_setvisualpage(0);
2053 #else
2054 #if MSDOS_COMPILER==BORLANDC
2055 	unsigned short *currscreen;
2056 
2057 	/*
2058 	 * Get a copy of the current screen.
2059 	 * Display the flash screen.
2060 	 * Then restore the old screen.
2061 	 */
2062 	if (!flash_created)
2063 		create_flash();
2064 	if (whitescreen == NULL)
2065 		return;
2066 	currscreen = (unsigned short *)
2067 		malloc(sc_width * sc_height * sizeof(short));
2068 	if (currscreen == NULL) return;
2069 	gettext(1, 1, sc_width, sc_height, currscreen);
2070 	puttext(1, 1, sc_width, sc_height, whitescreen);
2071 	delay(100);
2072 	puttext(1, 1, sc_width, sc_height, currscreen);
2073 	free(currscreen);
2074 #else
2075 #if MSDOS_COMPILER==WIN32C
2076 	/* paint screen with an inverse color */
2077 	clear();
2078 
2079 	/* leave it displayed for 100 msec. */
2080 	Sleep(100);
2081 
2082 	/* restore with a redraw */
2083 	repaint();
2084 #endif
2085 #endif
2086 #endif
2087 #endif
2088 #endif
2089 }
2090 
2091 /*
2092  * Make a noise.
2093  */
2094 	static void
2095 beep(VOID_PARAM)
2096 {
2097 #if !MSDOS_COMPILER
2098 	putchr(CONTROL('G'));
2099 #else
2100 #if MSDOS_COMPILER==WIN32C
2101 	MessageBeep(0);
2102 #else
2103 	write(1, "\7", 1);
2104 #endif
2105 #endif
2106 }
2107 
2108 /*
2109  * Ring the terminal bell.
2110  */
2111 	public void
2112 bell(VOID_PARAM)
2113 {
2114 	if (quiet == VERY_QUIET)
2115 		vbell();
2116 	else
2117 		beep();
2118 }
2119 
2120 /*
2121  * Clear the screen.
2122  */
2123 	public void
2124 clear(VOID_PARAM)
2125 {
2126 #if !MSDOS_COMPILER
2127 	tputs(sc_clear, sc_height, putchr);
2128 #else
2129 	flush();
2130 #if MSDOS_COMPILER==WIN32C
2131 	win32_clear();
2132 #else
2133 	_clearscreen(_GCLEARSCREEN);
2134 #endif
2135 #endif
2136 }
2137 
2138 /*
2139  * Clear from the cursor to the end of the cursor's line.
2140  * {{ This must not move the cursor. }}
2141  */
2142 	public void
2143 clear_eol(VOID_PARAM)
2144 {
2145 #if !MSDOS_COMPILER
2146 	tputs(sc_eol_clear, 1, putchr);
2147 #else
2148 #if MSDOS_COMPILER==MSOFTC
2149 	short top, left;
2150 	short bot, right;
2151 	struct rccoord tpos;
2152 
2153 	flush();
2154 	/*
2155 	 * Save current state.
2156 	 */
2157 	tpos = _gettextposition();
2158 	_gettextwindow(&top, &left, &bot, &right);
2159 	/*
2160 	 * Set a temporary window to the current line,
2161 	 * from the cursor's position to the right edge of the screen.
2162 	 * Then clear that window.
2163 	 */
2164 	_settextwindow(tpos.row, tpos.col, tpos.row, sc_width);
2165 	_clearscreen(_GWINDOW);
2166 	/*
2167 	 * Restore state.
2168 	 */
2169 	_settextwindow(top, left, bot, right);
2170 	_settextposition(tpos.row, tpos.col);
2171 #else
2172 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2173 	flush();
2174 	clreol();
2175 #else
2176 #if MSDOS_COMPILER==WIN32C
2177 	DWORD           nchars;
2178 	COORD           cpos;
2179 	CONSOLE_SCREEN_BUFFER_INFO scr;
2180 
2181 	flush();
2182 	memset(&scr, 0, sizeof(scr));
2183 	GetConsoleScreenBufferInfo(con_out, &scr);
2184 	cpos.X = scr.dwCursorPosition.X;
2185 	cpos.Y = scr.dwCursorPosition.Y;
2186 	curr_attr = MAKEATTR(nm_fg_color, nm_bg_color);
2187 	FillConsoleOutputAttribute(con_out, curr_attr,
2188 		scr.dwSize.X - cpos.X, cpos, &nchars);
2189 	FillConsoleOutputCharacter(con_out, ' ',
2190 		scr.dwSize.X - cpos.X, cpos, &nchars);
2191 #endif
2192 #endif
2193 #endif
2194 #endif
2195 }
2196 
2197 /*
2198  * Clear the current line.
2199  * Clear the screen if there's off-screen memory below the display.
2200  */
2201 	static void
2202 clear_eol_bot(VOID_PARAM)
2203 {
2204 #if MSDOS_COMPILER
2205 	clear_eol();
2206 #else
2207 	if (below_mem)
2208 		tputs(sc_eos_clear, 1, putchr);
2209 	else
2210 		tputs(sc_eol_clear, 1, putchr);
2211 #endif
2212 }
2213 
2214 /*
2215  * Clear the bottom line of the display.
2216  * Leave the cursor at the beginning of the bottom line.
2217  */
2218 	public void
2219 clear_bot(VOID_PARAM)
2220 {
2221 	/*
2222 	 * If we're in a non-normal attribute mode, temporarily exit
2223 	 * the mode while we do the clear.  Some terminals fill the
2224 	 * cleared area with the current attribute.
2225 	 */
2226 	if (oldbot)
2227 		lower_left();
2228 	else
2229 		line_left();
2230 
2231 	if (attrmode == AT_NORMAL)
2232 		clear_eol_bot();
2233 	else
2234 	{
2235 		int saved_attrmode = attrmode;
2236 
2237 		at_exit();
2238 		clear_eol_bot();
2239 		at_enter(saved_attrmode);
2240 	}
2241 }
2242 
2243 	public void
2244 at_enter(attr)
2245 	int attr;
2246 {
2247 	attr = apply_at_specials(attr);
2248 
2249 #if !MSDOS_COMPILER
2250 	/* The one with the most priority is last.  */
2251 	if (attr & AT_UNDERLINE)
2252 		tputs(sc_u_in, 1, putchr);
2253 	if (attr & AT_BOLD)
2254 		tputs(sc_b_in, 1, putchr);
2255 	if (attr & AT_BLINK)
2256 		tputs(sc_bl_in, 1, putchr);
2257 	if (attr & AT_STANDOUT)
2258 		tputs(sc_s_in, 1, putchr);
2259 #else
2260 	flush();
2261 	/* The one with the most priority is first.  */
2262 	if (attr & AT_STANDOUT)
2263 	{
2264 		SETCOLORS(so_fg_color, so_bg_color);
2265 	} else if (attr & AT_BLINK)
2266 	{
2267 		SETCOLORS(bl_fg_color, bl_bg_color);
2268 	}
2269 	else if (attr & AT_BOLD)
2270 	{
2271 		SETCOLORS(bo_fg_color, bo_bg_color);
2272 	}
2273 	else if (attr & AT_UNDERLINE)
2274 	{
2275 		SETCOLORS(ul_fg_color, ul_bg_color);
2276 	}
2277 #endif
2278 
2279 	attrmode = attr;
2280 }
2281 
2282 	public void
2283 at_exit(VOID_PARAM)
2284 {
2285 #if !MSDOS_COMPILER
2286 	/* Undo things in the reverse order we did them.  */
2287 	if (attrmode & AT_STANDOUT)
2288 		tputs(sc_s_out, 1, putchr);
2289 	if (attrmode & AT_BLINK)
2290 		tputs(sc_bl_out, 1, putchr);
2291 	if (attrmode & AT_BOLD)
2292 		tputs(sc_b_out, 1, putchr);
2293 	if (attrmode & AT_UNDERLINE)
2294 		tputs(sc_u_out, 1, putchr);
2295 #else
2296 	flush();
2297 	SETCOLORS(nm_fg_color, nm_bg_color);
2298 #endif
2299 
2300 	attrmode = AT_NORMAL;
2301 }
2302 
2303 	public void
2304 at_switch(attr)
2305 	int attr;
2306 {
2307 	int new_attrmode = apply_at_specials(attr);
2308 	int ignore_modes = AT_ANSI;
2309 
2310 	if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes))
2311 	{
2312 		at_exit();
2313 		at_enter(attr);
2314 	}
2315 }
2316 
2317 	public int
2318 is_at_equiv(attr1, attr2)
2319 	int attr1;
2320 	int attr2;
2321 {
2322 	attr1 = apply_at_specials(attr1);
2323 	attr2 = apply_at_specials(attr2);
2324 
2325 	return (attr1 == attr2);
2326 }
2327 
2328 	public int
2329 apply_at_specials(attr)
2330 	int attr;
2331 {
2332 	if (attr & AT_BINARY)
2333 		attr |= binattr;
2334 	if (attr & AT_HILITE)
2335 		attr |= AT_STANDOUT;
2336 	attr &= ~(AT_BINARY|AT_HILITE);
2337 
2338 	return attr;
2339 }
2340 
2341 #if 0 /* No longer used */
2342 /*
2343  * Erase the character to the left of the cursor
2344  * and move the cursor left.
2345  */
2346 	public void
2347 backspace(VOID_PARAM)
2348 {
2349 #if !MSDOS_COMPILER
2350 	/*
2351 	 * Erase the previous character by overstriking with a space.
2352 	 */
2353 	tputs(sc_backspace, 1, putchr);
2354 	putchr(' ');
2355 	tputs(sc_backspace, 1, putchr);
2356 #else
2357 #if MSDOS_COMPILER==MSOFTC
2358 	struct rccoord tpos;
2359 
2360 	flush();
2361 	tpos = _gettextposition();
2362 	if (tpos.col <= 1)
2363 		return;
2364 	_settextposition(tpos.row, tpos.col-1);
2365 	_outtext(" ");
2366 	_settextposition(tpos.row, tpos.col-1);
2367 #else
2368 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2369 	cputs("\b");
2370 #else
2371 #if MSDOS_COMPILER==WIN32C
2372 	COORD cpos;
2373 	DWORD cChars;
2374 	CONSOLE_SCREEN_BUFFER_INFO scr;
2375 
2376 	flush();
2377 	GetConsoleScreenBufferInfo(con_out, &scr);
2378 	cpos = scr.dwCursorPosition;
2379 	if (cpos.X <= 0)
2380 		return;
2381 	cpos.X--;
2382 	SetConsoleCursorPosition(con_out, cpos);
2383 	FillConsoleOutputCharacter(con_out, (TCHAR)' ', 1, cpos, &cChars);
2384 	SetConsoleCursorPosition(con_out, cpos);
2385 #endif
2386 #endif
2387 #endif
2388 #endif
2389 }
2390 #endif /* 0 */
2391 
2392 /*
2393  * Output a plain backspace, without erasing the previous char.
2394  */
2395 	public void
2396 putbs(VOID_PARAM)
2397 {
2398 	if (termcap_debug)
2399 		putstr("<bs>");
2400 	else
2401 	{
2402 #if !MSDOS_COMPILER
2403 	tputs(sc_backspace, 1, putchr);
2404 #else
2405 	int row, col;
2406 
2407 	flush();
2408 	{
2409 #if MSDOS_COMPILER==MSOFTC
2410 		struct rccoord tpos;
2411 		tpos = _gettextposition();
2412 		row = tpos.row;
2413 		col = tpos.col;
2414 #else
2415 #if MSDOS_COMPILER==BORLANDC || MSDOS_COMPILER==DJGPPC
2416 		row = wherey();
2417 		col = wherex();
2418 #else
2419 #if MSDOS_COMPILER==WIN32C
2420 		CONSOLE_SCREEN_BUFFER_INFO scr;
2421 		GetConsoleScreenBufferInfo(con_out, &scr);
2422 		row = scr.dwCursorPosition.Y - scr.srWindow.Top + 1;
2423 		col = scr.dwCursorPosition.X - scr.srWindow.Left + 1;
2424 #endif
2425 #endif
2426 #endif
2427 	}
2428 	if (col <= 1)
2429 		return;
2430 	_settextposition(row, col-1);
2431 #endif /* MSDOS_COMPILER */
2432 	}
2433 }
2434 
2435 #if MSDOS_COMPILER==WIN32C
2436 /*
2437  * Determine whether an input character is waiting to be read.
2438  */
2439 	public int
2440 win32_kbhit(VOID_PARAM)
2441 {
2442 	INPUT_RECORD ip;
2443 	DWORD read;
2444 
2445 	if (keyCount > 0)
2446 		return (TRUE);
2447 
2448 	currentKey.ascii = 0;
2449 	currentKey.scan = 0;
2450 
2451 	if (x11mouseCount > 0)
2452 	{
2453 		currentKey.ascii = x11mousebuf[x11mousePos++];
2454 		--x11mouseCount;
2455 		keyCount = 1;
2456 		return (TRUE);
2457 	}
2458 
2459 	/*
2460 	 * Wait for a real key-down event, but
2461 	 * ignore SHIFT and CONTROL key events.
2462 	 */
2463 	do
2464 	{
2465 		PeekConsoleInput(tty, &ip, 1, &read);
2466 		if (read == 0)
2467 			return (FALSE);
2468 		ReadConsoleInput(tty, &ip, 1, &read);
2469 		/* generate an X11 mouse sequence from the mouse event */
2470 		if (mousecap && ip.EventType == MOUSE_EVENT &&
2471 		    ip.Event.MouseEvent.dwEventFlags != MOUSE_MOVED)
2472 		{
2473 			x11mousebuf[3] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.X + 1;
2474 			x11mousebuf[4] = X11MOUSE_OFFSET + ip.Event.MouseEvent.dwMousePosition.Y + 1;
2475 			switch (ip.Event.MouseEvent.dwEventFlags)
2476 			{
2477 			case 0: /* press or release */
2478 				if (ip.Event.MouseEvent.dwButtonState == 0)
2479 					x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON_REL;
2480 				else if (ip.Event.MouseEvent.dwButtonState & (FROM_LEFT_3RD_BUTTON_PRESSED | FROM_LEFT_4TH_BUTTON_PRESSED))
2481 					continue;
2482 				else
2483 					x11mousebuf[2] = X11MOUSE_OFFSET + X11MOUSE_BUTTON1 + ((int)ip.Event.MouseEvent.dwButtonState << 1);
2484 				break;
2485 			case MOUSE_WHEELED:
2486 				x11mousebuf[2] = X11MOUSE_OFFSET + (((int)ip.Event.MouseEvent.dwButtonState < 0) ? X11MOUSE_WHEEL_DOWN : X11MOUSE_WHEEL_UP);
2487 				break;
2488 			default:
2489 				continue;
2490 			}
2491 			x11mousePos = 0;
2492 			x11mouseCount = 5;
2493 			currentKey.ascii = ESC;
2494 			keyCount = 1;
2495 			return (TRUE);
2496 		}
2497 	} while (ip.EventType != KEY_EVENT ||
2498 		ip.Event.KeyEvent.bKeyDown != TRUE ||
2499 		ip.Event.KeyEvent.wVirtualScanCode == 0 ||
2500 		ip.Event.KeyEvent.wVirtualKeyCode == VK_SHIFT ||
2501 		ip.Event.KeyEvent.wVirtualKeyCode == VK_CONTROL ||
2502 		ip.Event.KeyEvent.wVirtualKeyCode == VK_MENU);
2503 
2504 	currentKey.ascii = ip.Event.KeyEvent.uChar.AsciiChar;
2505 	currentKey.scan = ip.Event.KeyEvent.wVirtualScanCode;
2506 	keyCount = ip.Event.KeyEvent.wRepeatCount;
2507 
2508 	if (ip.Event.KeyEvent.dwControlKeyState &
2509 		(LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED))
2510 	{
2511 		switch (currentKey.scan)
2512 		{
2513 		case PCK_ALT_E:     /* letter 'E' */
2514 			currentKey.ascii = 0;
2515 			break;
2516 		}
2517 	} else if (ip.Event.KeyEvent.dwControlKeyState &
2518 		(LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
2519 	{
2520 		switch (currentKey.scan)
2521 		{
2522 		case PCK_RIGHT: /* right arrow */
2523 			currentKey.scan = PCK_CTL_RIGHT;
2524 			break;
2525 		case PCK_LEFT: /* left arrow */
2526 			currentKey.scan = PCK_CTL_LEFT;
2527 			break;
2528 		case PCK_DELETE: /* delete */
2529 			currentKey.scan = PCK_CTL_DELETE;
2530 			break;
2531 		}
2532 	} else if (ip.Event.KeyEvent.dwControlKeyState & SHIFT_PRESSED)
2533 	{
2534 		switch (currentKey.scan)
2535 		{
2536 		case PCK_SHIFT_TAB: /* tab */
2537 			currentKey.ascii = 0;
2538 			break;
2539 		}
2540 	}
2541 
2542 	return (TRUE);
2543 }
2544 
2545 /*
2546  * Read a character from the keyboard.
2547  */
2548 	public char
2549 WIN32getch(VOID_PARAM)
2550 {
2551 	int ascii;
2552 
2553 	if (pending_scancode)
2554 	{
2555 		pending_scancode = 0;
2556 		return ((char)(currentKey.scan & 0x00FF));
2557 	}
2558 
2559 	do {
2560 		while (win32_kbhit() == FALSE)
2561 		{
2562 			Sleep(20);
2563 			if (ABORT_SIGS())
2564 				return ('\003');
2565 			continue;
2566 		}
2567 		keyCount --;
2568 		ascii = currentKey.ascii;
2569 		/*
2570 		 * On PC's, the extended keys return a 2 byte sequence beginning
2571 		 * with '00', so if the ascii code is 00, the next byte will be
2572 		 * the lsb of the scan code.
2573 		 */
2574 		pending_scancode = (ascii == 0x00);
2575 	} while (pending_scancode &&
2576 		(currentKey.scan == PCK_CAPS_LOCK || currentKey.scan == PCK_NUM_LOCK));
2577 
2578 	return ((char)ascii);
2579 }
2580 #endif
2581 
2582 #if MSDOS_COMPILER
2583 /*
2584  */
2585 	public void
2586 WIN32setcolors(fg, bg)
2587 	int fg;
2588 	int bg;
2589 {
2590 	SETCOLORS(fg, bg);
2591 }
2592 
2593 /*
2594  */
2595 	public void
2596 WIN32textout(text, len)
2597 	char *text;
2598 	int len;
2599 {
2600 #if MSDOS_COMPILER==WIN32C
2601 	DWORD written;
2602 	if (utf_mode == 2)
2603 	{
2604 		/*
2605 		 * We've got UTF-8 text in a non-UTF-8 console.  Convert it to
2606 		 * wide and use WriteConsoleW.
2607 		 */
2608 		WCHAR wtext[1024];
2609 		len = MultiByteToWideChar(CP_UTF8, 0, text, len, wtext,
2610 					  sizeof(wtext)/sizeof(*wtext));
2611 		WriteConsoleW(con_out, wtext, len, &written, NULL);
2612 	} else
2613 		WriteConsole(con_out, text, len, &written, NULL);
2614 #else
2615 	char c = text[len];
2616 	text[len] = '\0';
2617 	cputs(text);
2618 	text[len] = c;
2619 #endif
2620 }
2621 #endif
2622