Merge branch 'master' into comment-cache
[emacs.git] / src / term.c
blobc067a86d184034c767d45115bd2ed99a4e12ecdc
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2017 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <sys/file.h>
28 #include <sys/time.h>
29 #include <unistd.h>
31 #include "lisp.h"
32 #include "termchar.h"
33 #include "tparam.h"
34 #include "character.h"
35 #include "buffer.h"
36 #include "charset.h"
37 #include "coding.h"
38 #include "composite.h"
39 #include "keyboard.h"
40 #include "frame.h"
41 #include "disptab.h"
42 #include "termhooks.h"
43 #include "dispextern.h"
44 #include "window.h"
45 #include "keymap.h"
46 #include "blockinput.h"
47 #include "syssignal.h"
48 #ifdef MSDOS
49 #include "msdos.h"
50 static int been_here = -1;
51 #endif
53 #ifdef USE_X_TOOLKIT
54 #include "../lwlib/lwlib.h"
55 #endif
57 #include "cm.h"
58 #include "menu.h"
60 /* The name of the default console device. */
61 #ifdef WINDOWSNT
62 #include "w32term.h"
63 #endif
65 static void tty_set_scroll_region (struct frame *f, int start, int stop);
66 static void turn_on_face (struct frame *, int face_id);
67 static void turn_off_face (struct frame *, int face_id);
68 static void tty_turn_off_highlight (struct tty_display_info *);
69 static void tty_show_cursor (struct tty_display_info *);
70 static void tty_hide_cursor (struct tty_display_info *);
71 static void tty_background_highlight (struct tty_display_info *tty);
72 static void clear_tty_hooks (struct terminal *terminal);
73 static void set_tty_hooks (struct terminal *terminal);
74 static void dissociate_if_controlling_tty (int fd);
75 static void delete_tty (struct terminal *);
76 static _Noreturn void maybe_fatal (bool, struct terminal *,
77 const char *, const char *, ...)
78 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
79 static _Noreturn void vfatal (const char *str, va_list ap)
80 ATTRIBUTE_FORMAT_PRINTF (1, 0);
83 #define OUTPUT(tty, a) \
84 emacs_tputs ((tty), a, \
85 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
86 cmputc)
88 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
89 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
91 #define OUTPUT_IF(tty, a) \
92 do { \
93 if (a) \
94 OUTPUT (tty, a); \
95 } while (0)
97 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
99 /* Display space properties. */
101 /* Chain of all tty device parameters. */
102 struct tty_display_info *tty_list;
104 /* Meaning of bits in no_color_video. Each bit set means that the
105 corresponding attribute cannot be combined with colors. */
107 enum no_color_bit
109 NC_STANDOUT = 1 << 0,
110 NC_UNDERLINE = 1 << 1,
111 NC_REVERSE = 1 << 2,
112 NC_ITALIC = 1 << 3,
113 NC_DIM = 1 << 4,
114 NC_BOLD = 1 << 5,
115 NC_INVIS = 1 << 6,
116 NC_PROTECT = 1 << 7
119 /* internal state */
121 /* The largest frame width in any call to calculate_costs. */
123 static int max_frame_cols;
127 #ifdef HAVE_GPM
128 #include <sys/fcntl.h>
130 /* The device for which we have enabled gpm support (or NULL). */
131 struct tty_display_info *gpm_tty = NULL;
133 /* Last recorded mouse coordinates. */
134 static int last_mouse_x, last_mouse_y;
135 #endif /* HAVE_GPM */
137 /* Ring the bell on a tty. */
139 static void
140 tty_ring_bell (struct frame *f)
142 struct tty_display_info *tty = FRAME_TTY (f);
144 if (tty->output)
146 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
147 ? tty->TS_visible_bell
148 : tty->TS_bell));
149 fflush (tty->output);
153 /* Set up termcap modes for Emacs. */
155 static void
156 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
158 Lisp_Object lisp_terminal;
159 Lisp_Object extra_codes;
160 struct tty_display_info *tty = terminal->display_info.tty;
162 XSETTERMINAL (lisp_terminal, terminal);
163 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
164 CONSP (extra_codes);
165 extra_codes = XCDR (extra_codes))
167 Lisp_Object string = XCAR (extra_codes);
168 if (STRINGP (string))
170 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
171 if (tty->termscript)
172 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
177 static void
178 tty_set_terminal_modes (struct terminal *terminal)
180 struct tty_display_info *tty = terminal->display_info.tty;
182 if (tty->output)
184 if (tty->TS_termcap_modes)
185 OUTPUT (tty, tty->TS_termcap_modes);
186 else
188 /* Output enough newlines to scroll all the old screen contents
189 off the screen, so it won't be overwritten and lost. */
190 int i;
191 current_tty = tty;
192 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
193 cmputc ('\n');
196 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
197 OUTPUT_IF (tty, tty->TS_keypad_mode);
198 losecursor (tty);
199 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
200 fflush (tty->output);
204 /* Reset termcap modes before exiting Emacs. */
206 static void
207 tty_reset_terminal_modes (struct terminal *terminal)
209 struct tty_display_info *tty = terminal->display_info.tty;
211 if (tty->output)
213 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
214 tty_turn_off_highlight (tty);
215 tty_turn_off_insert (tty);
216 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
217 OUTPUT_IF (tty, tty->TS_cursor_normal);
218 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
219 OUTPUT_IF (tty, tty->TS_orig_pair);
220 /* Output raw CR so kernel can track the cursor hpos. */
221 current_tty = tty;
222 cmputc ('\r');
223 fflush (tty->output);
227 /* Flag the end of a display update on a termcap terminal. */
229 static void
230 tty_update_end (struct frame *f)
232 struct tty_display_info *tty = FRAME_TTY (f);
234 if (!XWINDOW (selected_window)->cursor_off_p)
235 tty_show_cursor (tty);
236 tty_turn_off_insert (tty);
237 tty_background_highlight (tty);
238 fflush (tty->output);
241 /* The implementation of set_terminal_window for termcap frames. */
243 static void
244 tty_set_terminal_window (struct frame *f, int size)
246 struct tty_display_info *tty = FRAME_TTY (f);
248 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
249 if (FRAME_SCROLL_REGION_OK (f))
250 tty_set_scroll_region (f, 0, tty->specified_window);
253 static void
254 tty_set_scroll_region (struct frame *f, int start, int stop)
256 char *buf;
257 struct tty_display_info *tty = FRAME_TTY (f);
259 if (tty->TS_set_scroll_region)
260 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
261 else if (tty->TS_set_scroll_region_1)
262 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
263 FRAME_TOTAL_LINES (f), start,
264 FRAME_TOTAL_LINES (f) - stop,
265 FRAME_TOTAL_LINES (f));
266 else
267 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
269 OUTPUT (tty, buf);
270 xfree (buf);
271 losecursor (tty);
275 static void
276 tty_turn_on_insert (struct tty_display_info *tty)
278 if (!tty->insert_mode)
279 OUTPUT (tty, tty->TS_insert_mode);
280 tty->insert_mode = 1;
283 void
284 tty_turn_off_insert (struct tty_display_info *tty)
286 if (tty->insert_mode)
287 OUTPUT (tty, tty->TS_end_insert_mode);
288 tty->insert_mode = 0;
291 /* Handle highlighting. */
293 static void
294 tty_turn_off_highlight (struct tty_display_info *tty)
296 if (tty->standout_mode)
297 OUTPUT_IF (tty, tty->TS_end_standout_mode);
298 tty->standout_mode = 0;
301 static void
302 tty_turn_on_highlight (struct tty_display_info *tty)
304 if (!tty->standout_mode)
305 OUTPUT_IF (tty, tty->TS_standout_mode);
306 tty->standout_mode = 1;
309 static void
310 tty_toggle_highlight (struct tty_display_info *tty)
312 if (tty->standout_mode)
313 tty_turn_off_highlight (tty);
314 else
315 tty_turn_on_highlight (tty);
319 /* Make cursor invisible. */
321 static void
322 tty_hide_cursor (struct tty_display_info *tty)
324 if (tty->cursor_hidden == 0)
326 tty->cursor_hidden = 1;
327 #ifdef WINDOWSNT
328 w32con_hide_cursor ();
329 #else
330 OUTPUT_IF (tty, tty->TS_cursor_invisible);
331 #endif
336 /* Ensure that cursor is visible. */
338 static void
339 tty_show_cursor (struct tty_display_info *tty)
341 if (tty->cursor_hidden)
343 tty->cursor_hidden = 0;
344 #ifdef WINDOWSNT
345 w32con_show_cursor ();
346 #else
347 OUTPUT_IF (tty, tty->TS_cursor_normal);
348 if (visible_cursor)
349 OUTPUT_IF (tty, tty->TS_cursor_visible);
350 #endif
355 /* Set standout mode to the state it should be in for
356 empty space inside windows. What this is,
357 depends on the user option inverse-video. */
359 static void
360 tty_background_highlight (struct tty_display_info *tty)
362 if (inverse_video)
363 tty_turn_on_highlight (tty);
364 else
365 tty_turn_off_highlight (tty);
368 /* Set standout mode to the mode specified for the text to be output. */
370 static void
371 tty_highlight_if_desired (struct tty_display_info *tty)
373 if (inverse_video)
374 tty_turn_on_highlight (tty);
375 else
376 tty_turn_off_highlight (tty);
380 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
381 frame-relative coordinates. */
383 static void
384 tty_cursor_to (struct frame *f, int vpos, int hpos)
386 struct tty_display_info *tty = FRAME_TTY (f);
388 /* Detect the case where we are called from reset_sys_modes
389 and the costs have never been calculated. Do nothing. */
390 if (! tty->costs_set)
391 return;
393 if (curY (tty) == vpos
394 && curX (tty) == hpos)
395 return;
396 if (!tty->TF_standout_motion)
397 tty_background_highlight (tty);
398 if (!tty->TF_insmode_motion)
399 tty_turn_off_insert (tty);
400 cmgoto (tty, vpos, hpos);
403 /* Similar but don't take any account of the wasted characters. */
405 static void
406 tty_raw_cursor_to (struct frame *f, int row, int col)
408 struct tty_display_info *tty = FRAME_TTY (f);
410 if (curY (tty) == row
411 && curX (tty) == col)
412 return;
413 if (!tty->TF_standout_motion)
414 tty_background_highlight (tty);
415 if (!tty->TF_insmode_motion)
416 tty_turn_off_insert (tty);
417 cmgoto (tty, row, col);
420 /* Erase operations */
422 /* Clear from cursor to end of frame on a termcap device. */
424 static void
425 tty_clear_to_end (struct frame *f)
427 register int i;
428 struct tty_display_info *tty = FRAME_TTY (f);
430 if (tty->TS_clr_to_bottom)
432 tty_background_highlight (tty);
433 OUTPUT (tty, tty->TS_clr_to_bottom);
435 else
437 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
439 cursor_to (f, i, 0);
440 clear_end_of_line (f, FRAME_COLS (f));
445 /* Clear an entire termcap frame. */
447 static void
448 tty_clear_frame (struct frame *f)
450 struct tty_display_info *tty = FRAME_TTY (f);
452 if (tty->TS_clr_frame)
454 tty_background_highlight (tty);
455 OUTPUT (tty, tty->TS_clr_frame);
456 cmat (tty, 0, 0);
458 else
460 cursor_to (f, 0, 0);
461 clear_to_end (f);
465 /* An implementation of clear_end_of_line for termcap frames.
467 Note that the cursor may be moved, on terminals lacking a `ce' string. */
469 static void
470 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
472 register int i;
473 struct tty_display_info *tty = FRAME_TTY (f);
475 /* Detect the case where we are called from reset_sys_modes
476 and the costs have never been calculated. Do nothing. */
477 if (! tty->costs_set)
478 return;
480 if (curX (tty) >= first_unused_hpos)
481 return;
482 tty_background_highlight (tty);
483 if (tty->TS_clr_line)
485 OUTPUT1 (tty, tty->TS_clr_line);
487 else
488 { /* have to do it the hard way */
489 tty_turn_off_insert (tty);
491 /* Do not write in last row last col with Auto-wrap on. */
492 if (AutoWrap (tty)
493 && curY (tty) == FrameRows (tty) - 1
494 && first_unused_hpos == FrameCols (tty))
495 first_unused_hpos--;
497 for (i = curX (tty); i < first_unused_hpos; i++)
499 if (tty->termscript)
500 fputc (' ', tty->termscript);
501 fputc (' ', tty->output);
503 cmplus (tty, first_unused_hpos - curX (tty));
507 /* Buffers to store the source and result of code conversion for terminal. */
508 static unsigned char *encode_terminal_src;
509 static unsigned char *encode_terminal_dst;
510 /* Allocated sizes of the above buffers. */
511 static ptrdiff_t encode_terminal_src_size;
512 static ptrdiff_t encode_terminal_dst_size;
514 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
515 Set CODING->produced to the byte-length of the resulting byte
516 sequence, and return a pointer to that byte sequence. */
518 unsigned char *
519 encode_terminal_code (struct glyph *src, int src_len,
520 struct coding_system *coding)
522 struct glyph *src_end = src + src_len;
523 unsigned char *buf;
524 ptrdiff_t nchars, nbytes, required;
525 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
526 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
527 Lisp_Object charset_list;
529 /* Allocate sufficient size of buffer to store all characters in
530 multibyte-form. But, it may be enlarged on demand if
531 Vglyph_table contains a string or a composite glyph is
532 encountered. */
533 if (INT_MULTIPLY_WRAPV (src_len, MAX_MULTIBYTE_LENGTH, &required))
534 memory_full (SIZE_MAX);
535 if (encode_terminal_src_size < required)
536 encode_terminal_src = xpalloc (encode_terminal_src,
537 &encode_terminal_src_size,
538 required - encode_terminal_src_size,
539 -1, sizeof *encode_terminal_src);
541 charset_list = coding_charset_list (coding);
543 buf = encode_terminal_src;
544 nchars = 0;
545 while (src < src_end)
547 if (src->type == COMPOSITE_GLYPH)
549 struct composition *cmp UNINIT;
550 Lisp_Object gstring UNINIT;
551 int i;
553 nbytes = buf - encode_terminal_src;
554 if (src->u.cmp.automatic)
556 gstring = composition_gstring_from_id (src->u.cmp.id);
557 required = src->slice.cmp.to - src->slice.cmp.from + 1;
559 else
561 cmp = composition_table[src->u.cmp.id];
562 required = cmp->glyph_len;
563 required *= MAX_MULTIBYTE_LENGTH;
566 if (encode_terminal_src_size - nbytes < required)
568 encode_terminal_src =
569 xpalloc (encode_terminal_src, &encode_terminal_src_size,
570 required - (encode_terminal_src_size - nbytes),
571 -1, 1);
572 buf = encode_terminal_src + nbytes;
575 if (src->u.cmp.automatic)
576 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
578 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
579 int c = LGLYPH_CHAR (g);
581 if (! char_charset (c, charset_list, NULL))
582 c = '?';
583 buf += CHAR_STRING (c, buf);
584 nchars++;
586 else
587 for (i = 0; i < cmp->glyph_len; i++)
589 int c = COMPOSITION_GLYPH (cmp, i);
591 /* TAB in a composition means display glyphs with
592 padding space on the left or right. */
593 if (c == '\t')
594 continue;
595 if (char_charset (c, charset_list, NULL))
597 if (CHARACTER_WIDTH (c) == 0
598 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
599 /* Should be left-padded */
601 buf += CHAR_STRING (' ', buf);
602 nchars++;
605 else
606 c = '?';
607 buf += CHAR_STRING (c, buf);
608 nchars++;
611 /* We must skip glyphs to be padded for a wide character. */
612 else if (! CHAR_GLYPH_PADDING_P (*src))
614 GLYPH g;
615 int c UNINIT;
616 Lisp_Object string;
618 string = Qnil;
619 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
621 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
623 /* This glyph doesn't have an entry in Vglyph_table. */
624 c = src->u.ch;
626 else
628 /* This glyph has an entry in Vglyph_table,
629 so process any alias before testing for simpleness. */
630 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
632 if (GLYPH_SIMPLE_P (tbase, tlen, g))
633 /* We set the multi-byte form of a character in G
634 (that should be an ASCII character) at WORKBUF. */
635 c = GLYPH_CHAR (g);
636 else
637 /* We have a string in Vglyph_table. */
638 string = tbase[GLYPH_CHAR (g)];
641 if (NILP (string))
643 nbytes = buf - encode_terminal_src;
644 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
646 encode_terminal_src =
647 xpalloc (encode_terminal_src, &encode_terminal_src_size,
648 MAX_MULTIBYTE_LENGTH, -1, 1);
649 buf = encode_terminal_src + nbytes;
651 if (CHAR_BYTE8_P (c)
652 || char_charset (c, charset_list, NULL))
654 /* Store the multibyte form of C at BUF. */
655 buf += CHAR_STRING (c, buf);
656 nchars++;
658 else
660 /* C is not encodable. */
661 *buf++ = '?';
662 nchars++;
663 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
665 *buf++ = '?';
666 nchars++;
667 src++;
671 else
673 if (! STRING_MULTIBYTE (string))
674 string = string_to_multibyte (string);
675 nbytes = buf - encode_terminal_src;
676 if (encode_terminal_src_size - nbytes < SBYTES (string))
678 encode_terminal_src =
679 xpalloc (encode_terminal_src, &encode_terminal_src_size,
680 (SBYTES (string)
681 - (encode_terminal_src_size - nbytes)),
682 -1, 1);
683 buf = encode_terminal_src + nbytes;
685 memcpy (buf, SDATA (string), SBYTES (string));
686 buf += SBYTES (string);
687 nchars += SCHARS (string);
690 src++;
693 if (nchars == 0)
695 coding->produced = 0;
696 return NULL;
699 nbytes = buf - encode_terminal_src;
700 coding->source = encode_terminal_src;
701 if (encode_terminal_dst_size == 0)
703 encode_terminal_dst = xrealloc (encode_terminal_dst,
704 encode_terminal_src_size);
705 encode_terminal_dst_size = encode_terminal_src_size;
707 coding->destination = encode_terminal_dst;
708 coding->dst_bytes = encode_terminal_dst_size;
709 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
710 /* coding->destination may have been reallocated. */
711 encode_terminal_dst = coding->destination;
712 encode_terminal_dst_size = coding->dst_bytes;
714 return (encode_terminal_dst);
719 /* An implementation of write_glyphs for termcap frames. */
721 static void
722 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
724 unsigned char *conversion_buffer;
725 struct coding_system *coding;
726 int n, stringlen;
728 struct tty_display_info *tty = FRAME_TTY (f);
730 tty_turn_off_insert (tty);
731 tty_hide_cursor (tty);
733 /* Don't dare write in last column of bottom line, if Auto-Wrap,
734 since that would scroll the whole frame on some terminals. */
736 if (AutoWrap (tty)
737 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
738 && (curX (tty) + len) == FRAME_COLS (f))
739 len --;
740 if (len <= 0)
741 return;
743 cmplus (tty, len);
745 /* If terminal_coding does any conversion, use it, otherwise use
746 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
747 because it always return 1 if the member src_multibyte is 1. */
748 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
749 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
750 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
751 the tail. */
752 coding->mode &= ~CODING_MODE_LAST_BLOCK;
754 for (stringlen = len; stringlen != 0; stringlen -= n)
756 /* Identify a run of glyphs with the same face. */
757 int face_id = string->face_id;
759 for (n = 1; n < stringlen; ++n)
760 if (string[n].face_id != face_id)
761 break;
763 /* Turn appearance modes of the face of the run on. */
764 tty_highlight_if_desired (tty);
765 turn_on_face (f, face_id);
767 if (n == stringlen)
768 /* This is the last run. */
769 coding->mode |= CODING_MODE_LAST_BLOCK;
770 conversion_buffer = encode_terminal_code (string, n, coding);
771 if (coding->produced > 0)
773 block_input ();
774 fwrite (conversion_buffer, 1, coding->produced, tty->output);
775 if (ferror (tty->output))
776 clearerr (tty->output);
777 if (tty->termscript)
778 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
779 unblock_input ();
781 string += n;
783 /* Turn appearance modes off. */
784 turn_off_face (f, face_id);
785 tty_turn_off_highlight (tty);
788 cmcheckmagic (tty);
791 #ifdef HAVE_GPM /* Only used by GPM code. */
793 static void
794 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
795 register int len, register int face_id)
797 unsigned char *conversion_buffer;
798 struct coding_system *coding;
800 struct tty_display_info *tty = FRAME_TTY (f);
802 tty_turn_off_insert (tty);
803 tty_hide_cursor (tty);
805 /* Don't dare write in last column of bottom line, if Auto-Wrap,
806 since that would scroll the whole frame on some terminals. */
808 if (AutoWrap (tty)
809 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
810 && (curX (tty) + len) == FRAME_COLS (f))
811 len --;
812 if (len <= 0)
813 return;
815 cmplus (tty, len);
817 /* If terminal_coding does any conversion, use it, otherwise use
818 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
819 because it always return 1 if the member src_multibyte is 1. */
820 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
821 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
822 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
823 the tail. */
824 coding->mode &= ~CODING_MODE_LAST_BLOCK;
826 /* Turn appearance modes of the face. */
827 tty_highlight_if_desired (tty);
828 turn_on_face (f, face_id);
830 coding->mode |= CODING_MODE_LAST_BLOCK;
831 conversion_buffer = encode_terminal_code (string, len, coding);
832 if (coding->produced > 0)
834 block_input ();
835 fwrite (conversion_buffer, 1, coding->produced, tty->output);
836 if (ferror (tty->output))
837 clearerr (tty->output);
838 if (tty->termscript)
839 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
840 unblock_input ();
843 /* Turn appearance modes off. */
844 turn_off_face (f, face_id);
845 tty_turn_off_highlight (tty);
847 cmcheckmagic (tty);
849 #endif
851 /* An implementation of insert_glyphs for termcap frames. */
853 static void
854 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
856 char *buf;
857 struct glyph *glyph = NULL;
858 unsigned char *conversion_buffer;
859 unsigned char space[1];
860 struct coding_system *coding;
862 struct tty_display_info *tty = FRAME_TTY (f);
864 if (tty->TS_ins_multi_chars)
866 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
867 OUTPUT1 (tty, buf);
868 xfree (buf);
869 if (start)
870 write_glyphs (f, start, len);
871 return;
874 tty_turn_on_insert (tty);
875 cmplus (tty, len);
877 if (! start)
878 space[0] = SPACEGLYPH;
880 /* If terminal_coding does any conversion, use it, otherwise use
881 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
882 because it always return 1 if the member src_multibyte is 1. */
883 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
884 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
885 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
886 the tail. */
887 coding->mode &= ~CODING_MODE_LAST_BLOCK;
889 while (len-- > 0)
891 OUTPUT1_IF (tty, tty->TS_ins_char);
892 if (!start)
894 conversion_buffer = space;
895 coding->produced = 1;
897 else
899 tty_highlight_if_desired (tty);
900 turn_on_face (f, start->face_id);
901 glyph = start;
902 ++start;
903 /* We must open sufficient space for a character which
904 occupies more than one column. */
905 while (len && CHAR_GLYPH_PADDING_P (*start))
907 OUTPUT1_IF (tty, tty->TS_ins_char);
908 start++, len--;
911 if (len <= 0)
912 /* This is the last glyph. */
913 coding->mode |= CODING_MODE_LAST_BLOCK;
915 conversion_buffer = encode_terminal_code (glyph, 1, coding);
918 if (coding->produced > 0)
920 block_input ();
921 fwrite (conversion_buffer, 1, coding->produced, tty->output);
922 if (ferror (tty->output))
923 clearerr (tty->output);
924 if (tty->termscript)
925 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
926 unblock_input ();
929 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
930 if (start)
932 turn_off_face (f, glyph->face_id);
933 tty_turn_off_highlight (tty);
937 cmcheckmagic (tty);
940 /* An implementation of delete_glyphs for termcap frames. */
942 static void
943 tty_delete_glyphs (struct frame *f, int n)
945 char *buf;
946 register int i;
948 struct tty_display_info *tty = FRAME_TTY (f);
950 if (tty->delete_in_insert_mode)
952 tty_turn_on_insert (tty);
954 else
956 tty_turn_off_insert (tty);
957 OUTPUT_IF (tty, tty->TS_delete_mode);
960 if (tty->TS_del_multi_chars)
962 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
963 OUTPUT1 (tty, buf);
964 xfree (buf);
966 else
967 for (i = 0; i < n; i++)
968 OUTPUT1 (tty, tty->TS_del_char);
969 if (!tty->delete_in_insert_mode)
970 OUTPUT_IF (tty, tty->TS_end_delete_mode);
973 /* An implementation of ins_del_lines for termcap frames. */
975 static void
976 tty_ins_del_lines (struct frame *f, int vpos, int n)
978 struct tty_display_info *tty = FRAME_TTY (f);
979 const char *multi =
980 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
981 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
982 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
984 int i = eabs (n);
985 char *buf;
987 /* If the lines below the insertion are being pushed
988 into the end of the window, this is the same as clearing;
989 and we know the lines are already clear, since the matching
990 deletion has already been done. So can ignore this. */
991 /* If the lines below the deletion are blank lines coming
992 out of the end of the window, don't bother,
993 as there will be a matching inslines later that will flush them. */
994 if (FRAME_SCROLL_REGION_OK (f)
995 && vpos + i >= tty->specified_window)
996 return;
997 if (!FRAME_MEMORY_BELOW_FRAME (f)
998 && vpos + i >= FRAME_TOTAL_LINES (f))
999 return;
1001 if (multi)
1003 raw_cursor_to (f, vpos, 0);
1004 tty_background_highlight (tty);
1005 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1006 OUTPUT (tty, buf);
1007 xfree (buf);
1009 else if (single)
1011 raw_cursor_to (f, vpos, 0);
1012 tty_background_highlight (tty);
1013 while (--i >= 0)
1014 OUTPUT (tty, single);
1015 if (tty->TF_teleray)
1016 curX (tty) = 0;
1018 else
1020 tty_set_scroll_region (f, vpos, tty->specified_window);
1021 if (n < 0)
1022 raw_cursor_to (f, tty->specified_window - 1, 0);
1023 else
1024 raw_cursor_to (f, vpos, 0);
1025 tty_background_highlight (tty);
1026 while (--i >= 0)
1027 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1028 tty_set_scroll_region (f, 0, tty->specified_window);
1031 if (!FRAME_SCROLL_REGION_OK (f)
1032 && FRAME_MEMORY_BELOW_FRAME (f)
1033 && n < 0)
1035 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1036 clear_to_end (f);
1040 /* Compute cost of sending "str", in characters,
1041 not counting any line-dependent padding. */
1044 string_cost (const char *str)
1046 cost = 0;
1047 if (str)
1048 tputs (str, 0, evalcost);
1049 return cost;
1052 /* Compute cost of sending "str", in characters,
1053 counting any line-dependent padding at one line. */
1055 static int
1056 string_cost_one_line (const char *str)
1058 cost = 0;
1059 if (str)
1060 tputs (str, 1, evalcost);
1061 return cost;
1064 /* Compute per line amount of line-dependent padding,
1065 in tenths of characters. */
1068 per_line_cost (const char *str)
1070 cost = 0;
1071 if (str)
1072 tputs (str, 0, evalcost);
1073 cost = - cost;
1074 if (str)
1075 tputs (str, 10, evalcost);
1076 return cost;
1079 /* char_ins_del_cost[n] is cost of inserting N characters.
1080 char_ins_del_cost[-n] is cost of deleting N characters.
1081 The length of this vector is based on max_frame_cols. */
1083 int *char_ins_del_vector;
1085 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1087 /* ARGSUSED */
1088 static void
1089 calculate_ins_del_char_costs (struct frame *f)
1091 struct tty_display_info *tty = FRAME_TTY (f);
1092 int ins_startup_cost, del_startup_cost;
1093 int ins_cost_per_char, del_cost_per_char;
1094 register int i;
1095 register int *p;
1097 if (tty->TS_ins_multi_chars)
1099 ins_cost_per_char = 0;
1100 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1102 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1103 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1105 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1106 + string_cost (tty->TS_end_insert_mode))) / 100;
1107 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1108 + string_cost_one_line (tty->TS_pad_inserted_char));
1110 else
1112 ins_startup_cost = 9999;
1113 ins_cost_per_char = 0;
1116 if (tty->TS_del_multi_chars)
1118 del_cost_per_char = 0;
1119 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1121 else if (tty->TS_del_char)
1123 del_startup_cost = (string_cost (tty->TS_delete_mode)
1124 + string_cost (tty->TS_end_delete_mode));
1125 if (tty->delete_in_insert_mode)
1126 del_startup_cost /= 2;
1127 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1129 else
1131 del_startup_cost = 9999;
1132 del_cost_per_char = 0;
1135 /* Delete costs are at negative offsets */
1136 p = &char_ins_del_cost (f)[0];
1137 for (i = FRAME_COLS (f); --i >= 0;)
1138 *--p = (del_startup_cost += del_cost_per_char);
1140 /* Doing nothing is free */
1141 p = &char_ins_del_cost (f)[0];
1142 *p++ = 0;
1144 /* Insert costs are at positive offsets */
1145 for (i = FRAME_COLS (f); --i >= 0;)
1146 *p++ = (ins_startup_cost += ins_cost_per_char);
1149 void
1150 calculate_costs (struct frame *frame)
1152 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1154 if (FRAME_TERMCAP_P (frame))
1156 struct tty_display_info *tty = FRAME_TTY (frame);
1157 register const char *f = (tty->TS_set_scroll_region
1158 ? tty->TS_set_scroll_region
1159 : tty->TS_set_scroll_region_1);
1161 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1163 tty->costs_set = 1;
1165 /* These variables are only used for terminal stuff. They are
1166 allocated once for the terminal frame of X-windows emacs, but not
1167 used afterwards.
1169 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1170 X turns off char_ins_del_ok. */
1172 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1173 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1174 < max_frame_cols)
1175 memory_full (SIZE_MAX);
1177 char_ins_del_vector =
1178 xrealloc (char_ins_del_vector,
1179 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1181 memset (char_ins_del_vector, 0,
1182 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1185 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1186 do_line_insertion_deletion_costs (frame,
1187 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1188 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1189 f, f, 1);
1190 else
1191 do_line_insertion_deletion_costs (frame,
1192 tty->TS_ins_line, tty->TS_ins_multi_lines,
1193 tty->TS_del_line, tty->TS_del_multi_lines,
1194 0, 0, 1);
1196 calculate_ins_del_char_costs (frame);
1198 /* Don't use TS_repeat if its padding is worse than sending the chars */
1199 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1200 tty->RPov = string_cost (tty->TS_repeat);
1201 else
1202 tty->RPov = FRAME_COLS (frame) * 2;
1204 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1208 struct fkey_table {
1209 const char *cap, *name;
1212 /* Termcap capability names that correspond directly to X keysyms.
1213 Some of these (marked "terminfo") aren't supplied by old-style
1214 (Berkeley) termcap entries. They're listed in X keysym order;
1215 except we put the keypad keys first, so that if they clash with
1216 other keys (as on the IBM PC keyboard) they get overridden.
1219 static const struct fkey_table keys[] =
1221 {"kh", "home"}, /* termcap */
1222 {"kl", "left"}, /* termcap */
1223 {"ku", "up"}, /* termcap */
1224 {"kr", "right"}, /* termcap */
1225 {"kd", "down"}, /* termcap */
1226 {"%8", "prior"}, /* terminfo */
1227 {"%5", "next"}, /* terminfo */
1228 {"@7", "end"}, /* terminfo */
1229 {"@1", "begin"}, /* terminfo */
1230 {"*6", "select"}, /* terminfo */
1231 {"%9", "print"}, /* terminfo */
1232 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1234 * "insert" --- see below
1236 {"&8", "undo"}, /* terminfo */
1237 {"%0", "redo"}, /* terminfo */
1238 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1239 {"@0", "find"}, /* terminfo */
1240 {"@2", "cancel"}, /* terminfo */
1241 {"%1", "help"}, /* terminfo */
1243 * "break" goes here, but can't be reliably intercepted with termcap
1245 {"&4", "reset"}, /* terminfo --- actually `restart' */
1247 * "system" and "user" --- no termcaps
1249 {"kE", "clearline"}, /* terminfo */
1250 {"kA", "insertline"}, /* terminfo */
1251 {"kL", "deleteline"}, /* terminfo */
1252 {"kI", "insertchar"}, /* terminfo */
1253 {"kD", "deletechar"}, /* terminfo */
1254 {"kB", "backtab"}, /* terminfo */
1256 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1258 {"@8", "kp-enter"}, /* terminfo */
1260 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1261 * "kp-multiply", "kp-add", "kp-separator",
1262 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1263 * --- no termcaps for any of these.
1265 {"K4", "kp-1"}, /* terminfo */
1267 * "kp-2" --- no termcap
1269 {"K5", "kp-3"}, /* terminfo */
1271 * "kp-4" --- no termcap
1273 {"K2", "kp-5"}, /* terminfo */
1275 * "kp-6" --- no termcap
1277 {"K1", "kp-7"}, /* terminfo */
1279 * "kp-8" --- no termcap
1281 {"K3", "kp-9"}, /* terminfo */
1283 * "kp-equal" --- no termcap
1285 {"k1", "f1"},
1286 {"k2", "f2"},
1287 {"k3", "f3"},
1288 {"k4", "f4"},
1289 {"k5", "f5"},
1290 {"k6", "f6"},
1291 {"k7", "f7"},
1292 {"k8", "f8"},
1293 {"k9", "f9"},
1295 {"&0", "S-cancel"}, /*shifted cancel key*/
1296 {"&9", "S-begin"}, /*shifted begin key*/
1297 {"*0", "S-find"}, /*shifted find key*/
1298 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1299 {"*4", "S-delete"}, /*shifted delete-character key*/
1300 {"*7", "S-end"}, /*shifted end key*/
1301 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1302 {"#1", "S-help"}, /*shifted help key*/
1303 {"#2", "S-home"}, /*shifted home key*/
1304 {"#3", "S-insert"}, /*shifted insert-character key*/
1305 {"#4", "S-left"}, /*shifted left-arrow key*/
1306 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1307 {"%c", "S-next"}, /*shifted next key*/
1308 {"%e", "S-prior"}, /*shifted previous key*/
1309 {"%f", "S-print"}, /*shifted print key*/
1310 {"%g", "S-redo"}, /*shifted redo key*/
1311 {"%i", "S-right"}, /*shifted right-arrow key*/
1312 {"!3", "S-undo"} /*shifted undo key*/
1315 #ifndef DOS_NT
1316 static char **term_get_fkeys_address;
1317 static KBOARD *term_get_fkeys_kboard;
1318 static Lisp_Object term_get_fkeys_1 (void);
1320 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1321 This function scans the termcap function key sequence entries, and
1322 adds entries to Vinput_decode_map for each function key it finds. */
1324 static void
1325 term_get_fkeys (char **address, KBOARD *kboard)
1327 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1328 errors during the call. The only errors should be from Fdefine_key
1329 when given a key sequence containing an invalid prefix key. If the
1330 termcap defines function keys which use a prefix that is already bound
1331 to a command by the default bindings, we should silently ignore that
1332 function key specification, rather than giving the user an error and
1333 refusing to run at all on such a terminal. */
1335 term_get_fkeys_address = address;
1336 term_get_fkeys_kboard = kboard;
1337 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1340 static Lisp_Object
1341 term_get_fkeys_1 (void)
1343 int i;
1345 char **address = term_get_fkeys_address;
1346 KBOARD *kboard = term_get_fkeys_kboard;
1348 /* This can happen if CANNOT_DUMP or with strange options. */
1349 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1350 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1352 for (i = 0; i < ARRAYELTS (keys); i++)
1354 char *sequence = tgetstr (keys[i].cap, address);
1355 if (sequence)
1356 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1357 Fmake_vector (make_number (1),
1358 intern (keys[i].name)));
1361 /* The uses of the "k0" capability are inconsistent; sometimes it
1362 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1363 We will attempt to politely accommodate both systems by testing for
1364 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1367 const char *k_semi = tgetstr ("k;", address);
1368 const char *k0 = tgetstr ("k0", address);
1369 const char *k0_name = "f10";
1371 if (k_semi)
1373 if (k0)
1374 /* Define f0 first, so that f10 takes precedence in case the
1375 key sequences happens to be the same. */
1376 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1377 Fmake_vector (make_number (1), intern ("f0")));
1378 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1379 Fmake_vector (make_number (1), intern ("f10")));
1381 else if (k0)
1382 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1383 Fmake_vector (make_number (1), intern (k0_name)));
1386 /* Set up cookies for numbered function keys above f10. */
1388 char fcap[3], fkey[4];
1390 fcap[0] = 'F'; fcap[2] = '\0';
1391 for (i = 11; i < 64; i++)
1393 if (i <= 19)
1394 fcap[1] = '1' + i - 11;
1395 else if (i <= 45)
1396 fcap[1] = 'A' + i - 20;
1397 else
1398 fcap[1] = 'a' + i - 46;
1401 char *sequence = tgetstr (fcap, address);
1402 if (sequence)
1404 sprintf (fkey, "f%d", i);
1405 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1406 Fmake_vector (make_number (1),
1407 intern (fkey)));
1414 * Various mappings to try and get a better fit.
1417 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1418 if (!tgetstr (cap1, address)) \
1420 char *sequence = tgetstr (cap2, address); \
1421 if (sequence) \
1422 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1423 Fmake_vector (make_number (1), \
1424 intern (sym))); \
1427 /* if there's no key_next keycap, map key_npage to `next' keysym */
1428 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1429 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1430 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1431 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1432 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1433 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1434 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1435 #undef CONDITIONAL_REASSIGN
1438 return Qnil;
1440 #endif /* not DOS_NT */
1443 /***********************************************************************
1444 Character Display Information
1445 ***********************************************************************/
1446 static void append_glyph (struct it *);
1447 static void append_composite_glyph (struct it *);
1448 static void produce_composite_glyph (struct it *);
1449 static void append_glyphless_glyph (struct it *, int, const char *);
1450 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1452 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1453 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1454 the character for which to produce glyphs; IT->face_id contains the
1455 character's face. Padding glyphs are appended if IT->c has a
1456 IT->pixel_width > 1. */
1458 static void
1459 append_glyph (struct it *it)
1461 struct glyph *glyph, *end;
1462 int i;
1464 eassert (it->glyph_row);
1465 glyph = (it->glyph_row->glyphs[it->area]
1466 + it->glyph_row->used[it->area]);
1467 end = it->glyph_row->glyphs[1 + it->area];
1469 /* If the glyph row is reversed, we need to prepend the glyph rather
1470 than append it. */
1471 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1473 struct glyph *g;
1474 int move_by = it->pixel_width;
1476 /* Make room for the new glyphs. */
1477 if (move_by > end - glyph) /* don't overstep end of this area */
1478 move_by = end - glyph;
1479 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1480 g[move_by] = *g;
1481 glyph = it->glyph_row->glyphs[it->area];
1482 end = glyph + move_by;
1485 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1486 right, even in the REVERSED_P case, since (a) all of its u.ch are
1487 identical, and (b) the PADDING_P flag needs to be set for the
1488 leftmost one, because we write to the terminal left-to-right. */
1489 for (i = 0;
1490 i < it->pixel_width && glyph < end;
1491 ++i)
1493 glyph->type = CHAR_GLYPH;
1494 glyph->pixel_width = 1;
1495 glyph->u.ch = it->char_to_display;
1496 glyph->face_id = it->face_id;
1497 glyph->avoid_cursor_p = it->avoid_cursor_p;
1498 glyph->multibyte_p = it->multibyte_p;
1499 glyph->padding_p = i > 0;
1500 glyph->charpos = CHARPOS (it->position);
1501 glyph->object = it->object;
1502 if (it->bidi_p)
1504 glyph->resolved_level = it->bidi_it.resolved_level;
1505 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1506 glyph->bidi_type = it->bidi_it.type;
1508 else
1510 glyph->resolved_level = 0;
1511 glyph->bidi_type = UNKNOWN_BT;
1514 ++it->glyph_row->used[it->area];
1515 ++glyph;
1519 /* For external use. */
1520 void
1521 tty_append_glyph (struct it *it)
1523 append_glyph (it);
1527 /* Produce glyphs for the display element described by IT. *IT
1528 specifies what we want to produce a glyph for (character, image, ...),
1529 and where in the glyph matrix we currently are (glyph row and hpos).
1530 produce_glyphs fills in output fields of *IT with information such as the
1531 pixel width and height of a character, and maybe output actual glyphs at
1532 the same time if IT->glyph_row is non-null. For an overview, see
1533 the explanation in dispextern.h, before the definition of the
1534 display_element_type enumeration.
1536 produce_glyphs also stores the result of glyph width, ascent
1537 etc. computations in *IT.
1539 IT->glyph_row may be null, in which case produce_glyphs does not
1540 actually fill in the glyphs. This is used in the move_* functions
1541 in xdisp.c for text width and height computations.
1543 Callers usually don't call produce_glyphs directly;
1544 instead they use the macro PRODUCE_GLYPHS. */
1546 void
1547 produce_glyphs (struct it *it)
1549 /* If a hook is installed, let it do the work. */
1551 /* Nothing but characters are supported on terminal frames. */
1552 eassert (it->what == IT_CHARACTER
1553 || it->what == IT_COMPOSITION
1554 || it->what == IT_STRETCH
1555 || it->what == IT_GLYPHLESS);
1557 if (it->what == IT_STRETCH)
1559 produce_stretch_glyph (it);
1560 goto done;
1563 if (it->what == IT_COMPOSITION)
1565 produce_composite_glyph (it);
1566 goto done;
1569 if (it->what == IT_GLYPHLESS)
1571 produce_glyphless_glyph (it, Qnil);
1572 goto done;
1575 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1577 it->pixel_width = it->nglyphs = 1;
1578 if (it->glyph_row)
1579 append_glyph (it);
1581 else if (it->char_to_display == '\n')
1582 it->pixel_width = it->nglyphs = 0;
1583 else if (it->char_to_display == '\t')
1585 int absolute_x = (it->current_x
1586 + it->continuation_lines_width);
1587 int next_tab_x
1588 = (((1 + absolute_x + it->tab_width - 1)
1589 / it->tab_width)
1590 * it->tab_width);
1591 int nspaces;
1593 /* If part of the TAB has been displayed on the previous line
1594 which is continued now, continuation_lines_width will have
1595 been incremented already by the part that fitted on the
1596 continued line. So, we will get the right number of spaces
1597 here. */
1598 nspaces = next_tab_x - absolute_x;
1600 if (it->glyph_row)
1602 int n = nspaces;
1604 it->char_to_display = ' ';
1605 it->pixel_width = it->len = 1;
1607 while (n--)
1608 append_glyph (it);
1611 it->pixel_width = nspaces;
1612 it->nglyphs = nspaces;
1614 else if (CHAR_BYTE8_P (it->char_to_display))
1616 /* Coming here means that we must send the raw 8-bit byte as is
1617 to the terminal. Although there's no way to know how many
1618 columns it occupies on a screen, it is a good assumption that
1619 a single byte code has 1-column width. */
1620 it->pixel_width = it->nglyphs = 1;
1621 if (it->glyph_row)
1622 append_glyph (it);
1624 else
1626 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1628 if (char_charset (it->char_to_display, charset_list, NULL))
1630 it->pixel_width = CHARACTER_WIDTH (it->char_to_display);
1631 it->nglyphs = it->pixel_width;
1632 if (it->glyph_row)
1633 append_glyph (it);
1635 else
1637 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1639 eassert (it->what == IT_GLYPHLESS);
1640 produce_glyphless_glyph (it, acronym);
1644 done:
1645 /* Advance current_x by the pixel width as a convenience for
1646 the caller. */
1647 if (it->area == TEXT_AREA)
1648 it->current_x += it->pixel_width;
1649 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1650 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1653 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1654 Called from produce_composite_glyph for terminal frames if
1655 IT->glyph_row != NULL. IT->face_id contains the character's
1656 face. */
1658 static void
1659 append_composite_glyph (struct it *it)
1661 struct glyph *glyph;
1663 eassert (it->glyph_row);
1664 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1665 if (glyph < it->glyph_row->glyphs[1 + it->area])
1667 /* If the glyph row is reversed, we need to prepend the glyph
1668 rather than append it. */
1669 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1671 struct glyph *g;
1673 /* Make room for the new glyph. */
1674 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1675 g[1] = *g;
1676 glyph = it->glyph_row->glyphs[it->area];
1678 glyph->type = COMPOSITE_GLYPH;
1679 eassert (it->pixel_width <= SHRT_MAX);
1680 glyph->pixel_width = it->pixel_width;
1681 glyph->u.cmp.id = it->cmp_it.id;
1682 if (it->cmp_it.ch < 0)
1684 glyph->u.cmp.automatic = 0;
1685 glyph->u.cmp.id = it->cmp_it.id;
1687 else
1689 glyph->u.cmp.automatic = 1;
1690 glyph->u.cmp.id = it->cmp_it.id;
1691 glyph->slice.cmp.from = it->cmp_it.from;
1692 glyph->slice.cmp.to = it->cmp_it.to - 1;
1695 glyph->avoid_cursor_p = it->avoid_cursor_p;
1696 glyph->multibyte_p = it->multibyte_p;
1697 glyph->face_id = it->face_id;
1698 glyph->padding_p = false;
1699 glyph->charpos = CHARPOS (it->position);
1700 glyph->object = it->object;
1701 if (it->bidi_p)
1703 glyph->resolved_level = it->bidi_it.resolved_level;
1704 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1705 glyph->bidi_type = it->bidi_it.type;
1707 else
1709 glyph->resolved_level = 0;
1710 glyph->bidi_type = UNKNOWN_BT;
1713 ++it->glyph_row->used[it->area];
1714 ++glyph;
1719 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1720 the composition. We simply produces components of the composition
1721 assuming that the terminal has a capability to layout/render it
1722 correctly. */
1724 static void
1725 produce_composite_glyph (struct it *it)
1727 if (it->cmp_it.ch < 0)
1729 struct composition *cmp = composition_table[it->cmp_it.id];
1731 it->pixel_width = cmp->width;
1733 else
1735 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1737 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1738 it->cmp_it.to, NULL);
1740 it->nglyphs = 1;
1741 if (it->glyph_row)
1742 append_composite_glyph (it);
1746 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1747 is a face ID to be used for the glyph. What is actually appended
1748 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1749 comes from it->nglyphs bytes). */
1751 static void
1752 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1754 struct glyph *glyph, *end;
1755 int i;
1757 eassert (it->glyph_row);
1758 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1759 end = it->glyph_row->glyphs[1 + it->area];
1761 /* If the glyph row is reversed, we need to prepend the glyph rather
1762 than append it. */
1763 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1765 struct glyph *g;
1766 int move_by = it->pixel_width;
1768 /* Make room for the new glyphs. */
1769 if (move_by > end - glyph) /* don't overstep end of this area */
1770 move_by = end - glyph;
1771 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1772 g[move_by] = *g;
1773 glyph = it->glyph_row->glyphs[it->area];
1774 end = glyph + move_by;
1777 if (glyph >= end)
1778 return;
1779 glyph->type = CHAR_GLYPH;
1780 glyph->pixel_width = 1;
1781 glyph->avoid_cursor_p = it->avoid_cursor_p;
1782 glyph->multibyte_p = it->multibyte_p;
1783 glyph->face_id = face_id;
1784 glyph->padding_p = false;
1785 glyph->charpos = CHARPOS (it->position);
1786 glyph->object = it->object;
1787 if (it->bidi_p)
1789 glyph->resolved_level = it->bidi_it.resolved_level;
1790 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1791 glyph->bidi_type = it->bidi_it.type;
1793 else
1795 glyph->resolved_level = 0;
1796 glyph->bidi_type = UNKNOWN_BT;
1799 /* BIDI Note: we put the glyphs of characters left to right, even in
1800 the REVERSED_P case because we write to the terminal
1801 left-to-right. */
1802 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1804 if (i > 0)
1805 glyph[0] = glyph[-1];
1806 glyph->u.ch = str[i];
1807 ++it->glyph_row->used[it->area];
1808 ++glyph;
1812 /* Produce glyphs for a glyphless character for iterator IT.
1813 IT->glyphless_method specifies which method to use for displaying
1814 the character. See the description of enum
1815 glyphless_display_method in dispextern.h for the details.
1817 ACRONYM, if non-nil, is an acronym string for the character.
1819 The glyphs actually produced are of type CHAR_GLYPH. */
1821 static void
1822 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1824 int len, face_id = merge_glyphless_glyph_face (it);
1825 char buf[sizeof "\\x" + max (6, (INT_WIDTH + 3) / 4)];
1826 char const *str = " ";
1828 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1830 /* As there's no way to produce a thin space, we produce a space
1831 of canonical width. */
1832 len = 1;
1834 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1836 len = CHARACTER_WIDTH (it->c);
1837 if (len == 0)
1838 len = 1;
1839 else if (len > 4)
1840 len = 4;
1841 len = sprintf (buf, "[%.*s]", len, str);
1842 str = buf;
1844 else
1846 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1848 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1849 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1850 if (CONSP (acronym))
1851 acronym = XCDR (acronym);
1852 buf[0] = '[';
1853 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1854 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1855 buf[1 + len] = str[len];
1856 buf[1 + len] = ']';
1857 len += 2;
1859 else
1861 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1862 len = sprintf (buf,
1863 (it->c < 0x10000 ? "\\u%04X"
1864 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1865 : "\\x%06X"),
1866 it->c + 0u);
1868 str = buf;
1871 it->pixel_width = len;
1872 it->nglyphs = len;
1873 if (it->glyph_row)
1874 append_glyphless_glyph (it, face_id, str);
1878 /***********************************************************************
1879 Faces
1880 ***********************************************************************/
1882 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1883 one of the enumerators from enum no_color_bit, or a bit set built
1884 from them. Some display attributes may not be used together with
1885 color; the termcap capability `NC' specifies which ones. */
1887 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1888 (tty->TN_max_colors > 0 \
1889 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1890 : 1)
1892 /* Turn appearances of face FACE_ID on tty frame F on.
1893 FACE_ID is a realized face ID number, in the face cache. */
1895 static void
1896 turn_on_face (struct frame *f, int face_id)
1898 struct face *face = FACE_FROM_ID (f, face_id);
1899 unsigned long fg = face->foreground;
1900 unsigned long bg = face->background;
1901 struct tty_display_info *tty = FRAME_TTY (f);
1903 /* Use reverse video if the face specifies that.
1904 Do this first because TS_end_standout_mode may be the same
1905 as TS_exit_attribute_mode, which turns all appearances off. */
1906 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1907 && (inverse_video
1908 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1909 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1910 tty_toggle_highlight (tty);
1912 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1913 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1915 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1917 if (tty->TS_enter_italic_mode)
1918 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1919 else
1920 /* Italics mode is unavailable on many terminals. In that
1921 case, map slant to dimmed text; we want italic text to
1922 appear different and dimming is not otherwise used. */
1923 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1926 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1927 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1929 if (tty->TN_max_colors > 0)
1931 const char *ts;
1932 char *p;
1934 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1935 if (face_tty_specified_color (fg) && ts)
1937 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1938 OUTPUT (tty, p);
1939 xfree (p);
1942 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1943 if (face_tty_specified_color (bg) && ts)
1945 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1946 OUTPUT (tty, p);
1947 xfree (p);
1953 /* Turn off appearances of face FACE_ID on tty frame F. */
1955 static void
1956 turn_off_face (struct frame *f, int face_id)
1958 struct face *face = FACE_FROM_ID (f, face_id);
1959 struct tty_display_info *tty = FRAME_TTY (f);
1961 if (tty->TS_exit_attribute_mode)
1963 /* Capability "me" will turn off appearance modes double-bright,
1964 half-bright, reverse-video, standout, underline. It may or
1965 may not turn off alt-char-mode. */
1966 if (face->tty_bold_p
1967 || face->tty_italic_p
1968 || face->tty_reverse_p
1969 || face->tty_underline_p)
1971 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1972 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1973 tty->standout_mode = 0;
1976 else
1978 /* If we don't have "me" we can only have those appearances
1979 that have exit sequences defined. */
1980 if (face->tty_underline_p)
1981 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1984 /* Switch back to default colors. */
1985 if (tty->TN_max_colors > 0
1986 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1987 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1988 || (face->background != FACE_TTY_DEFAULT_COLOR
1989 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1990 OUTPUT1_IF (tty, tty->TS_orig_pair);
1994 /* Return true if the terminal on frame F supports all of the
1995 capabilities in CAPS simultaneously. */
1997 bool
1998 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2000 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2001 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2002 return 0;
2004 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2005 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2006 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2008 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2010 /* We can do it! */
2011 return 1;
2014 /* Return non-zero if the terminal is capable to display colors. */
2016 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2017 0, 1, 0,
2018 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2020 TERMINAL can be a terminal object, a frame, or nil (meaning the
2021 selected frame's terminal). This function always returns nil if
2022 TERMINAL does not refer to a text terminal. */)
2023 (Lisp_Object terminal)
2025 struct terminal *t = decode_tty_terminal (terminal);
2027 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2030 /* Return the number of supported colors. */
2031 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2032 Stty_display_color_cells, 0, 1, 0,
2033 doc: /* Return the number of colors supported by the tty device TERMINAL.
2035 TERMINAL can be a terminal object, a frame, or nil (meaning the
2036 selected frame's terminal). This function always returns 0 if
2037 TERMINAL does not refer to a text terminal. */)
2038 (Lisp_Object terminal)
2040 struct terminal *t = decode_tty_terminal (terminal);
2042 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2045 #ifndef DOS_NT
2047 /* Declare here rather than in the function, as in the rest of Emacs,
2048 to work around an HPUX compiler bug (?). See
2049 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2050 static int default_max_colors;
2051 static int default_max_pairs;
2052 static int default_no_color_video;
2053 static char *default_orig_pair;
2054 static char *default_set_foreground;
2055 static char *default_set_background;
2057 /* Save or restore the default color-related capabilities of this
2058 terminal. */
2059 static void
2060 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2063 if (save)
2065 dupstring (&default_orig_pair, tty->TS_orig_pair);
2066 dupstring (&default_set_foreground, tty->TS_set_foreground);
2067 dupstring (&default_set_background, tty->TS_set_background);
2068 default_max_colors = tty->TN_max_colors;
2069 default_max_pairs = tty->TN_max_pairs;
2070 default_no_color_video = tty->TN_no_color_video;
2072 else
2074 tty->TS_orig_pair = default_orig_pair;
2075 tty->TS_set_foreground = default_set_foreground;
2076 tty->TS_set_background = default_set_background;
2077 tty->TN_max_colors = default_max_colors;
2078 tty->TN_max_pairs = default_max_pairs;
2079 tty->TN_no_color_video = default_no_color_video;
2083 /* Setup one of the standard tty color schemes according to MODE.
2084 MODE's value is generally the number of colors which we want to
2085 support; zero means set up for the default capabilities, the ones
2086 we saw at init_tty time; -1 means turn off color support. */
2087 static void
2088 tty_setup_colors (struct tty_display_info *tty, int mode)
2090 /* Canonicalize all negative values of MODE. */
2091 if (mode < -1)
2092 mode = -1;
2094 switch (mode)
2096 case -1: /* no colors at all */
2097 tty->TN_max_colors = 0;
2098 tty->TN_max_pairs = 0;
2099 tty->TN_no_color_video = 0;
2100 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2101 break;
2102 case 0: /* default colors, if any */
2103 default:
2104 tty_default_color_capabilities (tty, 0);
2105 break;
2106 case 8: /* 8 standard ANSI colors */
2107 tty->TS_orig_pair = "\033[0m";
2108 #ifdef TERMINFO
2109 tty->TS_set_foreground = "\033[3%p1%dm";
2110 tty->TS_set_background = "\033[4%p1%dm";
2111 #else
2112 tty->TS_set_foreground = "\033[3%dm";
2113 tty->TS_set_background = "\033[4%dm";
2114 #endif
2115 tty->TN_max_colors = 8;
2116 tty->TN_max_pairs = 64;
2117 tty->TN_no_color_video = 0;
2118 break;
2122 void
2123 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2125 Lisp_Object tem, val;
2126 Lisp_Object color_mode;
2127 int mode;
2128 Lisp_Object tty_color_mode_alist
2129 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2131 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2132 val = CONSP (tem) ? XCDR (tem) : Qnil;
2134 if (INTEGERP (val))
2135 color_mode = val;
2136 else if (SYMBOLP (tty_color_mode_alist))
2138 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2139 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2141 else
2142 color_mode = Qnil;
2144 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2146 if (mode != tty->previous_color_mode)
2148 tty->previous_color_mode = mode;
2149 tty_setup_colors (tty , mode);
2150 /* This recomputes all the faces given the new color definitions. */
2151 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2155 #endif /* !DOS_NT */
2157 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2158 doc: /* Return the type of the tty device that TERMINAL uses.
2159 Returns nil if TERMINAL is not on a tty device.
2161 TERMINAL can be a terminal object, a frame, or nil (meaning the
2162 selected frame's terminal). */)
2163 (Lisp_Object terminal)
2165 struct terminal *t = decode_tty_terminal (terminal);
2167 return (t && t->display_info.tty->type
2168 ? build_string (t->display_info.tty->type) : Qnil);
2171 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2172 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2174 TERMINAL can be a terminal object, a frame, or nil (meaning the
2175 selected frame's terminal). This function always returns nil if
2176 TERMINAL is not on a tty device. */)
2177 (Lisp_Object terminal)
2179 struct terminal *t = decode_tty_terminal (terminal);
2181 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2184 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2185 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2186 This is used to override the terminfo data, for certain terminals that
2187 do not really do underlining, but say that they do. This function has
2188 no effect if used on a non-tty terminal.
2190 TERMINAL can be a terminal object, a frame or nil (meaning the
2191 selected frame's terminal). This function always returns nil if
2192 TERMINAL does not refer to a text terminal. */)
2193 (Lisp_Object terminal)
2195 struct terminal *t = decode_live_terminal (terminal);
2197 if (t->type == output_termcap)
2198 t->display_info.tty->TS_enter_underline_mode = 0;
2199 return Qnil;
2202 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2203 doc: /* Return the topmost terminal frame on TERMINAL.
2204 TERMINAL can be a terminal object, a frame or nil (meaning the
2205 selected frame's terminal). This function returns nil if TERMINAL
2206 does not refer to a text terminal. Otherwise, it returns the
2207 top-most frame on the text terminal. */)
2208 (Lisp_Object terminal)
2210 struct terminal *t = decode_live_terminal (terminal);
2212 if (t->type == output_termcap)
2213 return t->display_info.tty->top_frame;
2214 return Qnil;
2219 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2220 doc: /* Suspend the terminal device TTY.
2222 The device is restored to its default state, and Emacs ceases all
2223 access to the tty device. Frames that use the device are not deleted,
2224 but input is not read from them and if they change, their display is
2225 not updated.
2227 TTY may be a terminal object, a frame, or nil for the terminal device
2228 of the currently selected frame.
2230 This function runs `suspend-tty-functions' after suspending the
2231 device. The functions are run with one arg, the id of the suspended
2232 terminal device.
2234 `suspend-tty' does nothing if it is called on a device that is already
2235 suspended.
2237 A suspended tty may be resumed by calling `resume-tty' on it. */)
2238 (Lisp_Object tty)
2240 struct terminal *t = decode_tty_terminal (tty);
2241 FILE *f;
2243 if (!t)
2244 error ("Attempt to suspend a non-text terminal device");
2246 f = t->display_info.tty->input;
2248 if (f)
2250 /* First run `suspend-tty-functions' and then clean up the tty
2251 state because `suspend-tty-functions' might need to change
2252 the tty state. */
2253 Lisp_Object term;
2254 XSETTERMINAL (term, t);
2255 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2257 reset_sys_modes (t->display_info.tty);
2258 delete_keyboard_wait_descriptor (fileno (f));
2260 #ifndef MSDOS
2261 fclose (f);
2262 if (f != t->display_info.tty->output)
2263 fclose (t->display_info.tty->output);
2264 #endif
2266 t->display_info.tty->input = 0;
2267 t->display_info.tty->output = 0;
2269 if (FRAMEP (t->display_info.tty->top_frame))
2270 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2274 /* Clear display hooks to prevent further output. */
2275 clear_tty_hooks (t);
2277 return Qnil;
2280 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2281 doc: /* Resume the previously suspended terminal device TTY.
2282 The terminal is opened and reinitialized. Frames that are on the
2283 suspended terminal are revived.
2285 It is an error to resume a terminal while another terminal is active
2286 on the same device.
2288 This function runs `resume-tty-functions' after resuming the terminal.
2289 The functions are run with one arg, the id of the resumed terminal
2290 device.
2292 `resume-tty' does nothing if it is called on a device that is not
2293 suspended.
2295 TTY may be a terminal object, a frame, or nil (meaning the selected
2296 frame's terminal). */)
2297 (Lisp_Object tty)
2299 struct terminal *t = decode_tty_terminal (tty);
2300 int fd;
2302 if (!t)
2303 error ("Attempt to resume a non-text terminal device");
2305 if (!t->display_info.tty->input)
2307 if (get_named_terminal (t->display_info.tty->name))
2308 error ("Cannot resume display while another display is active on the same device");
2310 #ifdef MSDOS
2311 t->display_info.tty->output = stdout;
2312 t->display_info.tty->input = stdin;
2313 #else /* !MSDOS */
2314 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2315 t->display_info.tty->input = t->display_info.tty->output
2316 = fd < 0 ? 0 : fdopen (fd, "w+");
2318 if (! t->display_info.tty->input)
2320 int open_errno = errno;
2321 emacs_close (fd);
2322 report_file_errno ("Cannot reopen tty device",
2323 build_string (t->display_info.tty->name),
2324 open_errno);
2327 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2328 dissociate_if_controlling_tty (fd);
2329 #endif
2331 add_keyboard_wait_descriptor (fd);
2333 if (FRAMEP (t->display_info.tty->top_frame))
2335 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2336 int width, height;
2337 int old_height = FRAME_COLS (f);
2338 int old_width = FRAME_TOTAL_LINES (f);
2340 /* Check if terminal/window size has changed while the frame
2341 was suspended. */
2342 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2343 if (width != old_width || height != old_height)
2344 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2345 0, 0, 0, 0);
2346 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2349 set_tty_hooks (t);
2350 init_sys_modes (t->display_info.tty);
2352 /* Run `resume-tty-functions'. */
2353 Lisp_Object term;
2354 XSETTERMINAL (term, t);
2355 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2358 set_tty_hooks (t);
2360 return Qnil;
2364 /***********************************************************************
2365 Mouse
2366 ***********************************************************************/
2368 #ifdef HAVE_GPM
2370 #ifndef HAVE_WINDOW_SYSTEM
2371 void
2372 term_mouse_moveto (int x, int y)
2374 /* TODO: how to set mouse position?
2375 const char *name;
2376 int fd;
2377 name = (const char *) ttyname (0);
2378 fd = emacs_open (name, O_WRONLY, 0);
2379 SOME_FUNCTION (x, y, fd);
2380 emacs_close (fd);
2381 last_mouse_x = x;
2382 last_mouse_y = y; */
2384 #endif /* HAVE_WINDOW_SYSTEM */
2386 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2387 void
2388 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2389 int start_hpos, int end_hpos,
2390 enum draw_glyphs_face draw)
2392 int nglyphs = end_hpos - start_hpos;
2393 struct frame *f = XFRAME (WINDOW_FRAME (w));
2394 struct tty_display_info *tty = FRAME_TTY (f);
2395 int face_id = tty->mouse_highlight.mouse_face_face_id;
2396 int save_x, save_y, pos_x, pos_y;
2398 if (end_hpos >= row->used[TEXT_AREA])
2399 nglyphs = row->used[TEXT_AREA] - start_hpos;
2401 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2402 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2404 /* Save current cursor co-ordinates. */
2405 save_y = curY (tty);
2406 save_x = curX (tty);
2407 cursor_to (f, pos_y, pos_x);
2409 if (draw == DRAW_MOUSE_FACE)
2410 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2411 nglyphs, face_id);
2412 else if (draw == DRAW_NORMAL_TEXT)
2413 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2415 cursor_to (f, save_y, save_x);
2418 static bool
2419 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2421 /* Has the mouse moved off the glyph it was on at the last sighting? */
2422 if (event->x != last_mouse_x || event->y != last_mouse_y)
2424 frame->mouse_moved = 1;
2425 note_mouse_highlight (frame, event->x, event->y);
2426 /* Remember which glyph we're now on. */
2427 last_mouse_x = event->x;
2428 last_mouse_y = event->y;
2429 return 1;
2431 return 0;
2434 /* Return the Time that corresponds to T. Wrap around on overflow. */
2435 static Time
2436 timeval_to_Time (struct timeval const *t)
2438 Time s_1000, ms;
2440 s_1000 = t->tv_sec;
2441 s_1000 *= 1000;
2442 ms = t->tv_usec / 1000;
2443 return s_1000 + ms;
2446 /* Return the current position of the mouse.
2448 Set *f to the frame the mouse is in, or zero if the mouse is in no
2449 Emacs frame. If it is set to zero, all the other arguments are
2450 garbage.
2452 Set *bar_window to Qnil, and *x and *y to the column and
2453 row of the character cell the mouse is over.
2455 Set *timeptr to the time the mouse was at the returned position.
2457 This clears mouse_moved until the next motion
2458 event arrives. */
2459 static void
2460 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2461 enum scroll_bar_part *part, Lisp_Object *x,
2462 Lisp_Object *y, Time *timeptr)
2464 struct timeval now;
2466 *fp = SELECTED_FRAME ();
2467 (*fp)->mouse_moved = 0;
2469 *bar_window = Qnil;
2470 *part = scroll_bar_above_handle;
2472 XSETINT (*x, last_mouse_x);
2473 XSETINT (*y, last_mouse_y);
2474 gettimeofday(&now, 0);
2475 *timeptr = timeval_to_Time (&now);
2478 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2480 If the event is a button press, then note that we have grabbed
2481 the mouse. */
2483 static Lisp_Object
2484 term_mouse_click (struct input_event *result, Gpm_Event *event,
2485 struct frame *f)
2487 struct timeval now;
2488 int i, j;
2490 result->kind = GPM_CLICK_EVENT;
2491 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2493 if (event->buttons & j) {
2494 result->code = i; /* button number */
2495 break;
2498 gettimeofday(&now, 0);
2499 result->timestamp = timeval_to_Time (&now);
2501 if (event->type & GPM_UP)
2502 result->modifiers = up_modifier;
2503 else if (event->type & GPM_DOWN)
2504 result->modifiers = down_modifier;
2505 else
2506 result->modifiers = 0;
2508 if (event->type & GPM_SINGLE)
2509 result->modifiers |= click_modifier;
2511 if (event->type & GPM_DOUBLE)
2512 result->modifiers |= double_modifier;
2514 if (event->type & GPM_TRIPLE)
2515 result->modifiers |= triple_modifier;
2517 if (event->type & GPM_DRAG)
2518 result->modifiers |= drag_modifier;
2520 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2522 /* 1 << KG_SHIFT */
2523 if (event->modifiers & (1 << 0))
2524 result->modifiers |= shift_modifier;
2526 /* 1 << KG_CTRL */
2527 if (event->modifiers & (1 << 2))
2528 result->modifiers |= ctrl_modifier;
2530 /* 1 << KG_ALT || KG_ALTGR */
2531 if (event->modifiers & (1 << 3)
2532 || event->modifiers & (1 << 1))
2533 result->modifiers |= meta_modifier;
2536 XSETINT (result->x, event->x);
2537 XSETINT (result->y, event->y);
2538 XSETFRAME (result->frame_or_window, f);
2539 result->arg = Qnil;
2540 return Qnil;
2544 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2546 struct frame *f = XFRAME (tty->top_frame);
2547 struct input_event ie;
2548 bool do_help = 0;
2549 int count = 0;
2551 EVENT_INIT (ie);
2552 ie.kind = NO_EVENT;
2553 ie.arg = Qnil;
2555 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2556 previous_help_echo_string = help_echo_string;
2557 help_echo_string = Qnil;
2559 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2561 if (!term_mouse_movement (f, event))
2562 help_echo_string = previous_help_echo_string;
2564 /* If the contents of the global variable help_echo_string
2565 has changed, generate a HELP_EVENT. */
2566 if (!NILP (help_echo_string)
2567 || !NILP (previous_help_echo_string))
2568 do_help = 1;
2570 goto done;
2572 else {
2573 f->mouse_moved = 0;
2574 term_mouse_click (&ie, event, f);
2577 done:
2578 if (ie.kind != NO_EVENT)
2580 kbd_buffer_store_event_hold (&ie, hold_quit);
2581 count++;
2584 if (do_help
2585 && !(hold_quit && hold_quit->kind != NO_EVENT))
2587 Lisp_Object frame;
2589 if (f)
2590 XSETFRAME (frame, f);
2591 else
2592 frame = Qnil;
2594 gen_help_event (help_echo_string, frame, help_echo_window,
2595 help_echo_object, help_echo_pos);
2596 count++;
2599 return count;
2602 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2603 0, 0, 0,
2604 doc: /* Open a connection to Gpm.
2605 Gpm-mouse can only be activated for one tty at a time. */)
2606 (void)
2608 struct frame *f = SELECTED_FRAME ();
2609 struct tty_display_info *tty
2610 = ((f)->output_method == output_termcap
2611 ? (f)->terminal->display_info.tty : NULL);
2612 Gpm_Connect connection;
2614 if (!tty)
2615 error ("Gpm-mouse only works in the GNU/Linux console");
2616 if (gpm_tty == tty)
2617 return Qnil; /* Already activated, nothing to do. */
2618 if (gpm_tty)
2619 error ("Gpm-mouse can only be activated for one tty at a time");
2621 connection.eventMask = ~0;
2622 connection.defaultMask = ~GPM_HARD;
2623 connection.maxMod = ~0;
2624 connection.minMod = 0;
2625 gpm_zerobased = 1;
2627 if (Gpm_Open (&connection, 0) < 0)
2628 error ("Gpm-mouse failed to connect to the gpm daemon");
2629 else
2631 gpm_tty = tty;
2632 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2633 to generate SIGIOs. Apparently we need to call reset_sys_modes
2634 before calling init_sys_modes. */
2635 reset_sys_modes (tty);
2636 init_sys_modes (tty);
2637 add_gpm_wait_descriptor (gpm_fd);
2638 return Qnil;
2642 void
2643 close_gpm (int fd)
2645 if (fd >= 0)
2646 delete_gpm_wait_descriptor (fd);
2647 while (Gpm_Close()); /* close all the stack */
2648 gpm_tty = NULL;
2651 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2652 0, 0, 0,
2653 doc: /* Close a connection to Gpm. */)
2654 (void)
2656 struct frame *f = SELECTED_FRAME ();
2657 struct tty_display_info *tty
2658 = ((f)->output_method == output_termcap
2659 ? (f)->terminal->display_info.tty : NULL);
2661 if (!tty || gpm_tty != tty)
2662 return Qnil; /* Not activated on this terminal, nothing to do. */
2664 close_gpm (gpm_fd);
2665 return Qnil;
2667 #endif /* HAVE_GPM */
2670 /***********************************************************************
2671 Menus
2672 ***********************************************************************/
2674 #if !defined (MSDOS)
2676 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2678 However, unlike on MSDOS, where the menu text is drawn directly to
2679 the display video memory, on a TTY we use display_string (see
2680 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2681 the menu items into the frame's 'desired_matrix' glyph matrix, and
2682 then call update_frame_with_menu to deliver the results to the
2683 glass. The previous contents of the screen, in the form of the
2684 current_matrix, is stashed away, and used to restore screen
2685 contents when the menu selection changes or when the final
2686 selection is made and the menu should be popped down.
2688 The idea of this implementation was suggested by Gerd Moellmann. */
2690 #define TTYM_FAILURE -1
2691 #define TTYM_SUCCESS 1
2692 #define TTYM_NO_SELECT 2
2693 #define TTYM_IA_SELECT 3
2694 #define TTYM_NEXT 4
2695 #define TTYM_PREV 5
2697 /* These hold text of the current and the previous menu help messages. */
2698 static const char *menu_help_message, *prev_menu_help_message;
2699 /* Pane number and item number of the menu item which generated the
2700 last menu help message. */
2701 static int menu_help_paneno, menu_help_itemno;
2703 typedef struct tty_menu_struct
2705 int count;
2706 char **text;
2707 struct tty_menu_struct **submenu;
2708 int *panenumber; /* Also used as enabled flag. */
2709 ptrdiff_t allocated;
2710 int panecount;
2711 int width;
2712 const char **help_text;
2713 } tty_menu;
2715 /* Create a brand new menu structure. */
2717 static tty_menu *
2718 tty_menu_create (void)
2720 return xzalloc (sizeof *tty_menu_create ());
2723 /* Allocate some (more) memory for MENU ensuring that there is room for one
2724 more item. */
2726 static void
2727 tty_menu_make_room (tty_menu *menu)
2729 if (menu->allocated == menu->count)
2731 ptrdiff_t allocated = menu->allocated;
2732 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2733 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2734 menu->submenu = xrealloc (menu->submenu,
2735 allocated * sizeof *menu->submenu);
2736 menu->panenumber = xrealloc (menu->panenumber,
2737 allocated * sizeof *menu->panenumber);
2738 menu->help_text = xrealloc (menu->help_text,
2739 allocated * sizeof *menu->help_text);
2740 menu->allocated = allocated;
2744 /* Search the given menu structure for a given pane number. */
2746 static tty_menu *
2747 tty_menu_search_pane (tty_menu *menu, int pane)
2749 int i;
2750 tty_menu *try;
2752 for (i = 0; i < menu->count; i++)
2753 if (menu->submenu[i])
2755 if (pane == menu->panenumber[i])
2756 return menu->submenu[i];
2757 try = tty_menu_search_pane (menu->submenu[i], pane);
2758 if (try)
2759 return try;
2761 return (tty_menu *) 0;
2764 /* Determine how much screen space a given menu needs. */
2766 static void
2767 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2769 int i, h2, w2, maxsubwidth, maxheight;
2771 maxsubwidth = menu->width;
2772 maxheight = menu->count;
2773 for (i = 0; i < menu->count; i++)
2775 if (menu->submenu[i])
2777 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2778 if (w2 > maxsubwidth) maxsubwidth = w2;
2779 if (i + h2 > maxheight) maxheight = i + h2;
2782 *width = maxsubwidth;
2783 *height = maxheight;
2786 static void
2787 mouse_get_xy (int *x, int *y)
2789 struct frame *sf = SELECTED_FRAME ();
2790 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2791 enum scroll_bar_part part_dummy;
2792 Time time_dummy;
2794 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2795 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2796 &lisp_dummy, &part_dummy,
2797 &lmx, &lmy,
2798 &time_dummy);
2799 if (!NILP (lmx))
2801 *x = XINT (lmx);
2802 *y = XINT (lmy);
2806 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2807 (zero-based). */
2809 static void
2810 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2811 int mx, int my, int first_item, bool disp_help)
2813 int i, face, width, enabled, mousehere, row, col;
2814 struct frame *sf = SELECTED_FRAME ();
2815 struct tty_display_info *tty = FRAME_TTY (sf);
2816 /* Don't try to display more menu items than the console can display
2817 using the available screen lines. Exclude the echo area line, as
2818 it will be overwritten by the help-echo anyway. */
2819 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2821 menu_help_message = NULL;
2823 width = menu->width;
2824 col = cursorX (tty);
2825 row = cursorY (tty);
2826 for (i = 0; i < max_items; i++)
2828 int max_width = width + 2; /* +2 for padding blanks on each side */
2829 int j = i + first_item;
2831 if (menu->submenu[j])
2832 max_width += 2; /* for displaying " >" after the item */
2833 enabled
2834 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2835 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2836 face = faces[enabled + mousehere * 2];
2837 /* Display the menu help string for the i-th menu item even if
2838 the menu item is currently disabled. That's what the GUI
2839 code does. */
2840 if (disp_help && enabled + mousehere * 2 >= 2)
2842 menu_help_message = menu->help_text[j];
2843 menu_help_paneno = pn - 1;
2844 menu_help_itemno = j;
2846 /* Take note of the coordinates of the active menu item, to
2847 display the cursor there. */
2848 if (mousehere)
2850 row = y + i;
2851 col = x;
2853 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2854 menu->submenu[j] != NULL);
2856 update_frame_with_menu (sf, row, col);
2859 /* --------------------------- X Menu emulation ---------------------- */
2861 /* Create a new pane and place it on the outer-most level. */
2863 static int
2864 tty_menu_add_pane (tty_menu *menu, const char *txt)
2866 int len;
2868 tty_menu_make_room (menu);
2869 menu->submenu[menu->count] = tty_menu_create ();
2870 menu->text[menu->count] = (char *)txt;
2871 menu->panenumber[menu->count] = ++menu->panecount;
2872 menu->help_text[menu->count] = NULL;
2873 menu->count++;
2875 /* Update the menu width, if necessary. */
2876 len = menu_item_width ((const unsigned char *) txt);
2877 if (len > menu->width)
2878 menu->width = len;
2880 return menu->panecount;
2883 /* Create a new item in a menu pane. */
2885 static bool
2886 tty_menu_add_selection (tty_menu *menu, int pane,
2887 char *txt, bool enable, char const *help_text)
2889 int len;
2891 if (pane)
2893 menu = tty_menu_search_pane (menu, pane);
2894 if (! menu)
2895 return 0;
2897 tty_menu_make_room (menu);
2898 menu->submenu[menu->count] = (tty_menu *) 0;
2899 menu->text[menu->count] = txt;
2900 menu->panenumber[menu->count] = enable;
2901 menu->help_text[menu->count] = help_text;
2902 menu->count++;
2904 /* Update the menu width, if necessary. */
2905 len = menu_item_width ((const unsigned char *) txt);
2906 if (len > menu->width)
2907 menu->width = len;
2909 return 1;
2912 /* Decide where the menu would be placed if requested at (X,Y). */
2914 static void
2915 tty_menu_locate (tty_menu *menu, int x, int y,
2916 int *ulx, int *uly, int *width, int *height)
2918 tty_menu_calc_size (menu, width, height);
2919 *ulx = x + 1;
2920 *uly = y;
2921 *width += 2;
2924 struct tty_menu_state
2926 struct glyph_matrix *screen_behind;
2927 tty_menu *menu;
2928 int pane;
2929 int x, y;
2932 /* Save away the contents of frame F's current frame matrix, and
2933 enable all its rows. Value is a glyph matrix holding the contents
2934 of F's current frame matrix with all its glyph rows enabled. */
2936 static struct glyph_matrix *
2937 save_and_enable_current_matrix (struct frame *f)
2939 int i;
2940 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2941 saved->nrows = f->current_matrix->nrows;
2942 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2944 for (i = 0; i < saved->nrows; ++i)
2946 struct glyph_row *from = f->current_matrix->rows + i;
2947 struct glyph_row *to = saved->rows + i;
2948 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2950 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2951 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2952 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2953 /* Make sure every row is enabled, or else update_frame will not
2954 redraw them. (Rows that are identical to what is already on
2955 screen will not be redrawn anyway.) */
2956 to->enabled_p = true;
2957 to->hash = from->hash;
2960 return saved;
2963 /* Restore the contents of frame F's desired frame matrix from SAVED,
2964 and free memory associated with SAVED. */
2966 static void
2967 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2969 int i;
2971 for (i = 0; i < saved->nrows; ++i)
2973 struct glyph_row *from = saved->rows + i;
2974 struct glyph_row *to = f->desired_matrix->rows + i;
2975 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2977 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2978 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2979 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2980 to->enabled_p = from->enabled_p;
2981 to->hash = from->hash;
2985 static void
2986 free_saved_screen (struct glyph_matrix *saved)
2988 int i;
2990 if (!saved)
2991 return; /* Already freed! */
2993 for (i = 0; i < saved->nrows; ++i)
2995 struct glyph_row *from = saved->rows + i;
2997 xfree (from->glyphs[TEXT_AREA]);
3000 xfree (saved->rows);
3001 xfree (saved);
3004 /* Update the display of frame F from its saved contents. */
3005 static void
3006 screen_update (struct frame *f, struct glyph_matrix *mtx)
3008 restore_desired_matrix (f, mtx);
3009 update_frame_with_menu (f, -1, -1);
3012 typedef enum {
3013 MI_QUIT_MENU = -1,
3014 MI_CONTINUE = 0,
3015 MI_ITEM_SELECTED = 1,
3016 MI_NEXT_ITEM = 2,
3017 MI_PREV_ITEM = 3,
3018 MI_SCROLL_FORWARD = 4,
3019 MI_SCROLL_BACK = 5
3020 } mi_result;
3022 /* Read user input and return X and Y coordinates where that input
3023 puts us. We only consider mouse movement and click events, and
3024 keyboard movement commands; the rest are ignored. */
3025 static mi_result
3026 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3027 bool *first_time)
3029 if (*first_time)
3031 *first_time = false;
3032 sf->mouse_moved = 1;
3034 else
3036 Lisp_Object cmd;
3037 bool usable_input = 1;
3038 mi_result st = MI_CONTINUE;
3039 struct tty_display_info *tty = FRAME_TTY (sf);
3040 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3042 /* Signal the keyboard reading routines we are displaying a menu
3043 on this terminal. */
3044 tty->showing_menu = 1;
3045 /* We want mouse movements be reported by read_menu_command. */
3046 do_mouse_tracking = Qt;
3047 do {
3048 cmd = read_menu_command ();
3049 } while (NILP (cmd));
3050 tty->showing_menu = 0;
3051 do_mouse_tracking = saved_mouse_tracking;
3053 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3054 /* If some input switched frames under our feet, exit the
3055 menu, since the menu faces are no longer valid, and the
3056 menu is no longer relevant anyway. */
3057 || sf != SELECTED_FRAME ())
3058 return MI_QUIT_MENU;
3059 if (EQ (cmd, Qtty_menu_mouse_movement))
3060 mouse_get_xy (x, y);
3061 else if (EQ (cmd, Qtty_menu_next_menu))
3063 usable_input = 0;
3064 st = MI_NEXT_ITEM;
3066 else if (EQ (cmd, Qtty_menu_prev_menu))
3068 usable_input = 0;
3069 st = MI_PREV_ITEM;
3071 else if (EQ (cmd, Qtty_menu_next_item))
3073 if (*y < max_y)
3074 *y += 1;
3075 else
3076 st = MI_SCROLL_FORWARD;
3078 else if (EQ (cmd, Qtty_menu_prev_item))
3080 if (*y > min_y)
3081 *y -= 1;
3082 else
3083 st = MI_SCROLL_BACK;
3085 else if (EQ (cmd, Qtty_menu_select))
3086 st = MI_ITEM_SELECTED;
3087 else if (!EQ (cmd, Qtty_menu_ignore))
3088 usable_input = 0;
3089 if (usable_input)
3090 sf->mouse_moved = 1;
3091 return st;
3093 return MI_CONTINUE;
3096 /* Display menu, wait for user's response, and return that response. */
3097 static int
3098 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3099 int x0, int y0, char **txt,
3100 void (*help_callback)(char const *, int, int),
3101 bool kbd_navigation)
3103 struct tty_menu_state *state;
3104 int statecount, x, y, i;
3105 bool leave, onepane;
3106 int result UNINIT;
3107 int title_faces[4]; /* Face to display the menu title. */
3108 int faces[4], buffers_num_deleted = 0;
3109 struct frame *sf = SELECTED_FRAME ();
3110 struct tty_display_info *tty = FRAME_TTY (sf);
3111 bool first_time;
3112 Lisp_Object selectface;
3113 int first_item = 0;
3114 int col, row;
3115 Lisp_Object prev_inhibit_redisplay = Vinhibit_redisplay;
3116 USE_SAFE_ALLOCA;
3118 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3119 around the display. */
3120 if (x0 <= 0)
3121 x0 = 1;
3122 if (y0 <= 0)
3123 y0 = 1;
3125 SAFE_NALLOCA (state, 1, menu->panecount);
3126 memset (state, 0, sizeof (*state));
3127 faces[0]
3128 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3129 DEFAULT_FACE_ID, 1);
3130 faces[1]
3131 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3132 DEFAULT_FACE_ID, 1);
3133 selectface = intern ("tty-menu-selected-face");
3134 faces[2] = lookup_derived_face (sf, selectface,
3135 faces[0], 1);
3136 faces[3] = lookup_derived_face (sf, selectface,
3137 faces[1], 1);
3139 /* Make sure the menu title is always displayed with
3140 `tty-menu-selected-face', no matter where the mouse pointer is. */
3141 for (i = 0; i < 4; i++)
3142 title_faces[i] = faces[3];
3144 statecount = 1;
3146 /* Don't let the title for the "Buffers" popup menu include a
3147 digit (which is ugly).
3149 This is a terrible kludge, but I think the "Buffers" case is
3150 the only one where the title includes a number, so it doesn't
3151 seem to be necessary to make this more general. */
3152 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3154 menu->text[0][7] = '\0';
3155 buffers_num_deleted = 1;
3158 /* Inhibit redisplay for as long as the menu is active, to avoid
3159 messing the screen if some timer calls sit-for or a similar
3160 function. */
3161 Vinhibit_redisplay = Qt;
3163 /* Force update of the current frame, so that the desired and the
3164 current matrices are identical. */
3165 update_frame_with_menu (sf, -1, -1);
3166 state[0].menu = menu;
3167 state[0].screen_behind = save_and_enable_current_matrix (sf);
3169 /* Display the menu title. We subtract 1 from x0 and y0 because we
3170 want to interpret them as zero-based column and row coordinates,
3171 and also because we want the first item of the menu, not its
3172 title, to appear at x0,y0. */
3173 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3175 /* Turn off the cursor. Otherwise it shows through the menu
3176 panes, which is ugly. */
3177 col = cursorX (tty);
3178 row = cursorY (tty);
3179 tty_hide_cursor (tty);
3181 if (buffers_num_deleted)
3182 menu->text[0][7] = ' ';
3183 onepane = menu->count == 1 && menu->submenu[0];
3184 if (onepane)
3186 menu->width = menu->submenu[0]->width;
3187 state[0].menu = menu->submenu[0];
3189 else
3191 state[0].menu = menu;
3193 state[0].x = x0 - 1;
3194 state[0].y = y0;
3195 state[0].pane = onepane;
3197 x = state[0].x;
3198 y = state[0].y;
3199 first_time = true;
3201 leave = 0;
3202 while (!leave)
3204 mi_result input_status;
3205 int min_y = state[0].y;
3206 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3208 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3209 if (input_status)
3211 leave = 1;
3212 switch (input_status)
3214 case MI_QUIT_MENU:
3215 /* Remove the last help-echo, so that it doesn't
3216 re-appear after "Quit". */
3217 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3218 result = TTYM_NO_SELECT;
3219 break;
3220 case MI_NEXT_ITEM:
3221 if (kbd_navigation)
3222 result = TTYM_NEXT;
3223 else
3224 leave = 0;
3225 break;
3226 case MI_PREV_ITEM:
3227 if (kbd_navigation)
3228 result = TTYM_PREV;
3229 else
3230 leave = 0;
3231 break;
3232 case MI_SCROLL_FORWARD:
3233 if (y - min_y == state[0].menu->count - 1 - first_item)
3235 y = min_y;
3236 first_item = 0;
3238 else
3239 first_item++;
3240 leave = 0;
3241 break;
3242 case MI_SCROLL_BACK:
3243 if (first_item == 0)
3245 y = max_y;
3246 first_item = state[0].menu->count - 1 - (y - min_y);
3248 else
3249 first_item--;
3250 leave = 0;
3251 break;
3252 default:
3253 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3254 break;
3257 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3259 sf->mouse_moved = 0;
3260 result = TTYM_IA_SELECT;
3261 for (i = 0; i < statecount; i++)
3262 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3264 int dy = y - state[i].y + first_item;
3265 if (0 <= dy && dy < state[i].menu->count)
3267 if (!state[i].menu->submenu[dy])
3269 if (state[i].menu->panenumber[dy])
3270 result = TTYM_SUCCESS;
3271 else
3272 result = TTYM_IA_SELECT;
3274 *pane = state[i].pane - 1;
3275 *selidx = dy;
3276 /* We hit some part of a menu, so drop extra menus that
3277 have been opened. That does not include an open and
3278 active submenu. */
3279 if (i != statecount - 2
3280 || state[i].menu->submenu[dy] != state[i + 1].menu)
3281 while (i != statecount - 1)
3283 statecount--;
3284 screen_update (sf, state[statecount].screen_behind);
3285 state[statecount].screen_behind = NULL;
3287 if (i == statecount - 1 && state[i].menu->submenu[dy])
3289 tty_menu_display (state[i].menu,
3290 state[i].x,
3291 state[i].y,
3292 state[i].pane,
3293 faces, x, y, first_item, 1);
3294 state[statecount].menu = state[i].menu->submenu[dy];
3295 state[statecount].pane = state[i].menu->panenumber[dy];
3296 state[statecount].screen_behind
3297 = save_and_enable_current_matrix (sf);
3298 state[statecount].x
3299 = state[i].x + state[i].menu->width + 2;
3300 state[statecount].y = y;
3301 statecount++;
3305 tty_menu_display (state[statecount - 1].menu,
3306 state[statecount - 1].x,
3307 state[statecount - 1].y,
3308 state[statecount - 1].pane,
3309 faces, x, y, first_item, 1);
3310 /* The call to display help-echo below will move the cursor,
3311 so remember its current position as computed by
3312 tty_menu_display. */
3313 col = cursorX (tty);
3314 row = cursorY (tty);
3317 /* Display the help-echo message for the currently-selected menu
3318 item. */
3319 if ((menu_help_message || prev_menu_help_message)
3320 && menu_help_message != prev_menu_help_message)
3322 help_callback (menu_help_message,
3323 menu_help_paneno, menu_help_itemno);
3324 /* Move the cursor to the beginning of the current menu
3325 item, so that screen readers and other accessibility aids
3326 know where the active region is. */
3327 cursor_to (sf, row, col);
3328 prev_menu_help_message = menu_help_message;
3330 /* Both tty_menu_display and help_callback invoke update_end,
3331 which calls tty_show_cursor. Re-hide it, so it doesn't show
3332 through the menus. */
3333 tty_hide_cursor (tty);
3334 fflush (tty->output);
3337 sf->mouse_moved = 0;
3338 screen_update (sf, state[0].screen_behind);
3339 while (statecount--)
3340 free_saved_screen (state[statecount].screen_behind);
3341 tty_show_cursor (tty); /* Turn cursor back on. */
3342 fflush (tty->output);
3344 /* Clean up any mouse events that are waiting inside Emacs event queue.
3345 These events are likely to be generated before the menu was even
3346 displayed, probably because the user pressed and released the button
3347 (which invoked the menu) too quickly. If we don't remove these events,
3348 Emacs will process them after we return and surprise the user. */
3349 discard_mouse_events ();
3350 if (!kbd_buffer_events_waiting ())
3351 clear_input_pending ();
3352 SAFE_FREE ();
3353 Vinhibit_redisplay = prev_inhibit_redisplay;
3354 return result;
3357 /* Dispose of a menu. */
3359 static void
3360 tty_menu_destroy (tty_menu *menu)
3362 int i;
3363 if (menu->allocated)
3365 for (i = 0; i < menu->count; i++)
3366 if (menu->submenu[i])
3367 tty_menu_destroy (menu->submenu[i]);
3368 xfree (menu->text);
3369 xfree (menu->submenu);
3370 xfree (menu->panenumber);
3371 xfree (menu->help_text);
3373 xfree (menu);
3374 menu_help_message = prev_menu_help_message = NULL;
3377 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3379 PANE is the pane number, and ITEM is the menu item number in
3380 the menu (currently not used). */
3382 static void
3383 tty_menu_help_callback (char const *help_string, int pane, int item)
3385 Lisp_Object *first_item;
3386 Lisp_Object pane_name;
3387 Lisp_Object menu_object;
3389 first_item = XVECTOR (menu_items)->contents;
3390 if (EQ (first_item[0], Qt))
3391 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3392 else if (EQ (first_item[0], Qquote))
3393 /* This shouldn't happen, see xmenu_show. */
3394 pane_name = empty_unibyte_string;
3395 else
3396 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3398 /* (menu-item MENU-NAME PANE-NUMBER) */
3399 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3400 show_help_echo (help_string ? build_string (help_string) : Qnil,
3401 Qnil, menu_object, make_number (item));
3404 static void
3405 tty_pop_down_menu (Lisp_Object arg)
3407 tty_menu *menu = XSAVE_POINTER (arg, 0);
3408 struct buffer *orig_buffer = XSAVE_POINTER (arg, 1);
3410 block_input ();
3411 tty_menu_destroy (menu);
3412 set_buffer_internal (orig_buffer);
3413 unblock_input ();
3416 /* Return the zero-based index of the last menu-bar item on frame F. */
3417 static int
3418 tty_menu_last_menubar_item (struct frame *f)
3420 int i = 0;
3422 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3423 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3425 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3427 while (i < ASIZE (items))
3429 Lisp_Object str;
3431 str = AREF (items, i + 1);
3432 if (NILP (str))
3433 break;
3434 i += 4;
3436 i -= 4; /* Went one too far! */
3438 return i;
3441 /* Find in frame F's menu bar the menu item that is next or previous
3442 to the item at X/Y, and return that item's position in X/Y. WHICH
3443 says which one--next or previous--item to look for. X and Y are
3444 measured in character cells. This should only be called on TTY
3445 frames. */
3446 static void
3447 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3449 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3450 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3452 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3453 int last_i = tty_menu_last_menubar_item (f);
3454 int i, prev_x;
3456 /* This loop assumes a single menu-bar line, and will fail to
3457 find an item if it is not in the first line. Note that
3458 make_lispy_event in keyboard.c makes the same assumption. */
3459 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3461 Lisp_Object pos, str;
3462 int ix;
3464 str = AREF (items, i + 1);
3465 pos = AREF (items, i + 3);
3466 if (NILP (str))
3467 return;
3468 ix = XINT (pos);
3469 if (ix <= *x
3470 /* We use <= so the blank between 2 items on a TTY is
3471 considered part of the previous item. */
3472 && *x <= ix + menu_item_width (SDATA (str)))
3474 /* Found current item. Now compute the X coordinate of
3475 the previous or next item. */
3476 if (which == TTYM_NEXT)
3478 if (i < last_i)
3479 *x = XINT (AREF (items, i + 4 + 3));
3480 else
3481 *x = 0; /* Wrap around to the first item. */
3483 else if (prev_x < 0)
3485 /* Wrap around to the last item. */
3486 *x = XINT (AREF (items, last_i + 3));
3488 else
3489 *x = prev_x;
3490 return;
3492 prev_x = ix;
3497 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3498 Lisp_Object
3499 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3500 Lisp_Object title, const char **error_name)
3502 tty_menu *menu;
3503 int pane, selidx, lpane, status;
3504 Lisp_Object entry, pane_prefix;
3505 char *datap;
3506 int ulx, uly, width, height;
3507 int item_x, item_y;
3508 int dispwidth, dispheight;
3509 int i, j, lines, maxlines;
3510 int maxwidth;
3511 ptrdiff_t specpdl_count;
3513 eassert (FRAME_TERMCAP_P (f));
3515 *error_name = 0;
3516 if (menu_items_n_panes == 0)
3517 return Qnil;
3519 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3521 *error_name = "Empty menu";
3522 return Qnil;
3525 /* Make the menu on that window. */
3526 menu = tty_menu_create ();
3528 /* Don't GC while we prepare and show the menu, because we give the
3529 menu functions pointers to the contents of strings. */
3530 specpdl_count = inhibit_garbage_collection ();
3532 /* Avoid crashes if, e.g., another client will connect while we
3533 are in a menu. */
3534 temporarily_switch_to_single_kboard (f);
3536 /* Adjust coordinates to be root-window-relative. */
3537 item_x = x += f->left_pos;
3538 item_y = y += f->top_pos;
3540 /* Create all the necessary panes and their items. */
3541 USE_SAFE_ALLOCA;
3542 maxwidth = maxlines = lines = i = 0;
3543 lpane = TTYM_FAILURE;
3544 while (i < menu_items_used)
3546 if (EQ (AREF (menu_items, i), Qt))
3548 /* Create a new pane. */
3549 Lisp_Object pane_name, prefix;
3550 const char *pane_string;
3552 maxlines = max (maxlines, lines);
3553 lines = 0;
3554 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3555 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3556 pane_string = (NILP (pane_name)
3557 ? "" : SSDATA (pane_name));
3558 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3559 pane_string++;
3561 lpane = tty_menu_add_pane (menu, pane_string);
3562 if (lpane == TTYM_FAILURE)
3564 tty_menu_destroy (menu);
3565 *error_name = "Can't create pane";
3566 entry = Qnil;
3567 goto tty_menu_end;
3569 i += MENU_ITEMS_PANE_LENGTH;
3571 /* Find the width of the widest item in this pane. */
3572 j = i;
3573 while (j < menu_items_used)
3575 Lisp_Object item;
3576 item = AREF (menu_items, j);
3577 if (EQ (item, Qt))
3578 break;
3579 if (NILP (item))
3581 j++;
3582 continue;
3584 width = SBYTES (item);
3585 if (width > maxwidth)
3586 maxwidth = width;
3588 j += MENU_ITEMS_ITEM_LENGTH;
3591 /* Ignore a nil in the item list.
3592 It's meaningful only for dialog boxes. */
3593 else if (EQ (AREF (menu_items, i), Qquote))
3594 i += 1;
3595 else
3597 /* Create a new item within current pane. */
3598 Lisp_Object item_name, enable, descrip, help;
3599 char *item_data;
3600 char const *help_string;
3602 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3603 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3604 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3605 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3606 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3608 if (!NILP (descrip))
3610 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3611 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3612 for (j = SCHARS (item_name); j < maxwidth; j++)
3613 item_data[j] = ' ';
3614 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3615 item_data[j + SBYTES (descrip)] = 0;
3617 else
3618 item_data = SSDATA (item_name);
3620 if (lpane == TTYM_FAILURE
3621 || (! tty_menu_add_selection (menu, lpane, item_data,
3622 !NILP (enable), help_string)))
3624 tty_menu_destroy (menu);
3625 *error_name = "Can't add selection to menu";
3626 entry = Qnil;
3627 goto tty_menu_end;
3629 i += MENU_ITEMS_ITEM_LENGTH;
3630 lines++;
3634 maxlines = max (maxlines, lines);
3636 /* All set and ready to fly. */
3637 dispwidth = f->text_cols;
3638 dispheight = f->text_lines;
3639 x = min (x, dispwidth);
3640 y = min (y, dispheight);
3641 x = max (x, 1);
3642 y = max (y, 1);
3643 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3644 if (ulx + width > dispwidth)
3646 x -= (ulx + width) - dispwidth;
3647 ulx = dispwidth - width;
3649 if (uly + height > dispheight)
3651 y -= (uly + height) - dispheight;
3652 uly = dispheight - height;
3655 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3657 /* Move the menu away of the echo area, to avoid overwriting the
3658 menu with help echo messages or vice versa. */
3659 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3661 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3662 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3664 else
3666 y -= 2;
3667 uly -= 2;
3671 if (ulx < 0) x -= ulx;
3672 if (uly < 0) y -= uly;
3674 #if 0
3675 /* This code doesn't make sense on a TTY, since it can easily annul
3676 the adjustments above that carefully avoid truncation of the menu
3677 items. I think it was written to fix some problem that only
3678 happens on X11. */
3679 if (! for_click)
3681 /* If position was not given by a mouse click, adjust so upper left
3682 corner of the menu as a whole ends up at given coordinates. This
3683 is what x-popup-menu says in its documentation. */
3684 x += width / 2;
3685 y += 1.5 * height / (maxlines + 2);
3687 #endif
3689 pane = selidx = 0;
3691 /* We save and restore the current buffer because tty_menu_activate
3692 triggers redisplay, which switches buffers at will. */
3693 record_unwind_protect (tty_pop_down_menu,
3694 make_save_ptr_ptr (menu, current_buffer));
3696 specbind (Qoverriding_terminal_local_map,
3697 Fsymbol_value (Qtty_menu_navigation_map));
3698 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3699 tty_menu_help_callback,
3700 menuflags & MENU_KBD_NAVIGATION);
3701 entry = pane_prefix = Qnil;
3703 switch (status)
3705 case TTYM_SUCCESS:
3706 /* Find the item number SELIDX in pane number PANE. */
3707 i = 0;
3708 while (i < menu_items_used)
3710 if (EQ (AREF (menu_items, i), Qt))
3712 if (pane == 0)
3713 pane_prefix
3714 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3715 pane--;
3716 i += MENU_ITEMS_PANE_LENGTH;
3718 else
3720 if (pane == -1)
3722 if (selidx == 0)
3724 entry
3725 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3726 if (menuflags & MENU_KEYMAPS)
3728 entry = Fcons (entry, Qnil);
3729 if (!NILP (pane_prefix))
3730 entry = Fcons (pane_prefix, entry);
3732 break;
3734 selidx--;
3736 i += MENU_ITEMS_ITEM_LENGTH;
3739 break;
3741 case TTYM_NEXT:
3742 case TTYM_PREV:
3743 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3744 entry = Fcons (make_number (item_x), make_number (item_y));
3745 break;
3747 case TTYM_FAILURE:
3748 *error_name = "Can't activate menu";
3749 case TTYM_IA_SELECT:
3750 break;
3751 case TTYM_NO_SELECT:
3752 /* If the selected frame was changed while we displayed a menu,
3753 throw to top level in order to undo any temporary settings
3754 made by TTY menu code. */
3755 if (f != SELECTED_FRAME ())
3756 Ftop_level ();
3757 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3758 the menu was invoked with a mouse event as POSITION). */
3759 if (!(menuflags & MENU_FOR_CLICK))
3760 quit ();
3761 break;
3764 tty_menu_end:
3766 SAFE_FREE ();
3767 unbind_to (specpdl_count, Qnil);
3768 return entry;
3771 #endif /* !MSDOS */
3774 #ifndef MSDOS
3775 /***********************************************************************
3776 Initialization
3777 ***********************************************************************/
3779 /* Initialize the tty-dependent part of frame F. The frame must
3780 already have its device initialized. */
3782 void
3783 create_tty_output (struct frame *f)
3785 struct tty_output *t = xzalloc (sizeof *t);
3787 eassert (FRAME_TERMCAP_P (f));
3789 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3791 f->output_data.tty = t;
3794 /* Delete frame F's face cache, and its tty-dependent part. */
3796 static void
3797 tty_free_frame_resources (struct frame *f)
3799 eassert (FRAME_TERMCAP_P (f));
3800 free_frame_faces (f);
3801 xfree (f->output_data.tty);
3804 #else /* MSDOS */
3806 /* Delete frame F's face cache. */
3808 static void
3809 tty_free_frame_resources (struct frame *f)
3811 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3812 free_frame_faces (f);
3814 #endif /* MSDOS */
3816 /* Reset the hooks in TERMINAL. */
3818 static void
3819 clear_tty_hooks (struct terminal *terminal)
3821 terminal->rif = 0;
3822 terminal->cursor_to_hook = 0;
3823 terminal->raw_cursor_to_hook = 0;
3824 terminal->clear_to_end_hook = 0;
3825 terminal->clear_frame_hook = 0;
3826 terminal->clear_end_of_line_hook = 0;
3827 terminal->ins_del_lines_hook = 0;
3828 terminal->insert_glyphs_hook = 0;
3829 terminal->write_glyphs_hook = 0;
3830 terminal->delete_glyphs_hook = 0;
3831 terminal->ring_bell_hook = 0;
3832 terminal->reset_terminal_modes_hook = 0;
3833 terminal->set_terminal_modes_hook = 0;
3834 terminal->update_begin_hook = 0;
3835 terminal->update_end_hook = 0;
3836 terminal->set_terminal_window_hook = 0;
3837 terminal->mouse_position_hook = 0;
3838 terminal->frame_rehighlight_hook = 0;
3839 terminal->frame_raise_lower_hook = 0;
3840 terminal->fullscreen_hook = 0;
3841 terminal->menu_show_hook = 0;
3842 terminal->set_vertical_scroll_bar_hook = 0;
3843 terminal->set_horizontal_scroll_bar_hook = 0;
3844 terminal->condemn_scroll_bars_hook = 0;
3845 terminal->redeem_scroll_bar_hook = 0;
3846 terminal->judge_scroll_bars_hook = 0;
3847 terminal->read_socket_hook = 0;
3848 terminal->frame_up_to_date_hook = 0;
3850 /* Leave these two set, or suspended frames are not deleted
3851 correctly. */
3852 terminal->delete_frame_hook = &tty_free_frame_resources;
3853 terminal->delete_terminal_hook = &delete_tty;
3856 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3858 static void
3859 set_tty_hooks (struct terminal *terminal)
3861 terminal->cursor_to_hook = &tty_cursor_to;
3862 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3863 terminal->clear_to_end_hook = &tty_clear_to_end;
3864 terminal->clear_frame_hook = &tty_clear_frame;
3865 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3866 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3867 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3868 terminal->write_glyphs_hook = &tty_write_glyphs;
3869 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3870 terminal->ring_bell_hook = &tty_ring_bell;
3871 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3872 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3873 terminal->update_end_hook = &tty_update_end;
3874 #ifdef MSDOS
3875 terminal->menu_show_hook = &x_menu_show;
3876 #else
3877 terminal->menu_show_hook = &tty_menu_show;
3878 #endif
3879 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3880 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3881 terminal->delete_frame_hook = &tty_free_frame_resources;
3882 terminal->delete_terminal_hook = &delete_tty;
3883 /* Other hooks are NULL by default. */
3886 /* If FD is the controlling terminal, drop it. */
3887 static void
3888 dissociate_if_controlling_tty (int fd)
3890 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3891 so dissociate it by invoking setsid. */
3892 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3894 #ifdef TIOCNOTTY
3895 /* setsid failed, presumably because Emacs is already a process
3896 group leader. Fall back on the obsolescent way to dissociate
3897 a controlling tty. */
3898 sigset_t oldset;
3899 block_tty_out_signal (&oldset);
3900 ioctl (fd, TIOCNOTTY, 0);
3901 unblock_tty_out_signal (&oldset);
3902 #endif
3906 /* Create a termcap display on the tty device with the given name and
3907 type.
3909 If NAME is NULL, then use the controlling tty, i.e., DEV_TTY.
3910 Otherwise NAME should be a path to the tty device file,
3911 e.g. "/dev/pts/7".
3913 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3915 If MUST_SUCCEED is true, then all errors are fatal. */
3917 struct terminal *
3918 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3920 struct tty_display_info *tty = NULL;
3921 struct terminal *terminal = NULL;
3922 #ifndef DOS_NT
3923 char *area;
3924 char **address = &area;
3925 int status;
3926 sigset_t oldset;
3927 bool ctty = false; /* True if asked to open controlling tty. */
3928 #endif
3930 if (!terminal_type)
3931 maybe_fatal (must_succeed, 0,
3932 "Unknown terminal type",
3933 "Unknown terminal type");
3935 if (name == NULL)
3936 name = DEV_TTY;
3937 #ifndef DOS_NT
3938 if (!strcmp (name, DEV_TTY))
3939 ctty = 1;
3940 #endif
3942 /* If we already have a terminal on the given device, use that. If
3943 all such terminals are suspended, create a new one instead. */
3944 /* XXX Perhaps this should be made explicit by having init_tty
3945 always create a new terminal and separating terminal and frame
3946 creation on Lisp level. */
3947 terminal = get_named_terminal (name);
3948 if (terminal)
3949 return terminal;
3951 terminal = create_terminal (output_termcap, NULL);
3952 #ifdef MSDOS
3953 if (been_here > 0)
3954 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3955 name, "");
3956 been_here = 1;
3957 tty = &the_only_display_info;
3958 #else
3959 tty = xzalloc (sizeof *tty);
3960 #endif
3961 tty->top_frame = Qnil;
3962 tty->next = tty_list;
3963 tty_list = tty;
3965 terminal->display_info.tty = tty;
3966 tty->terminal = terminal;
3968 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3969 Wcm_clear (tty);
3971 encode_terminal_src_size = 0;
3972 encode_terminal_dst_size = 0;
3975 #ifndef DOS_NT
3976 set_tty_hooks (terminal);
3979 /* Open the terminal device. */
3981 /* If !ctty, don't recognize it as our controlling terminal, and
3982 don't make it the controlling tty if we don't have one now.
3984 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3985 defined on Hurd. On other systems, we need to explicitly
3986 dissociate ourselves from the controlling tty when we want to
3987 open a frame on the same terminal. */
3988 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3989 int fd = emacs_open (name, flags, 0);
3990 tty->input = tty->output
3991 = ((fd < 0 || ! isatty (fd))
3992 ? NULL
3993 : fdopen (fd, "w+"));
3995 if (! tty->input)
3997 char const *diagnostic
3998 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3999 emacs_close (fd);
4000 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4003 tty->name = xstrdup (name);
4004 terminal->name = xstrdup (name);
4006 if (!O_IGNORE_CTTY && !ctty)
4007 dissociate_if_controlling_tty (fd);
4010 tty->type = xstrdup (terminal_type);
4012 add_keyboard_wait_descriptor (fileno (tty->input));
4014 Wcm_clear (tty);
4016 /* On some systems, tgetent tries to access the controlling
4017 terminal. */
4018 block_tty_out_signal (&oldset);
4019 status = tgetent (tty->termcap_term_buffer, terminal_type);
4020 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4021 emacs_abort ();
4022 unblock_tty_out_signal (&oldset);
4024 if (status < 0)
4026 #ifdef TERMINFO
4027 maybe_fatal (must_succeed, terminal,
4028 "Cannot open terminfo database file",
4029 "Cannot open terminfo database file");
4030 #else
4031 maybe_fatal (must_succeed, terminal,
4032 "Cannot open termcap database file",
4033 "Cannot open termcap database file");
4034 #endif
4036 if (status == 0)
4038 maybe_fatal (must_succeed, terminal,
4039 "Terminal type %s is not defined",
4040 "Terminal type %s is not defined.\n\
4041 If that is not the actual type of terminal you have,\n\
4042 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4043 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4044 #ifdef TERMINFO
4045 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4046 #else
4047 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4048 #endif
4049 terminal_type);
4052 area = tty->termcap_strings_buffer;
4053 tty->TS_ins_line = tgetstr ("al", address);
4054 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4055 tty->TS_bell = tgetstr ("bl", address);
4056 BackTab (tty) = tgetstr ("bt", address);
4057 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4058 tty->TS_clr_line = tgetstr ("ce", address);
4059 tty->TS_clr_frame = tgetstr ("cl", address);
4060 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4061 AbsPosition (tty) = tgetstr ("cm", address);
4062 CR (tty) = tgetstr ("cr", address);
4063 tty->TS_set_scroll_region = tgetstr ("cs", address);
4064 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4065 RowPosition (tty) = tgetstr ("cv", address);
4066 tty->TS_del_char = tgetstr ("dc", address);
4067 tty->TS_del_multi_chars = tgetstr ("DC", address);
4068 tty->TS_del_line = tgetstr ("dl", address);
4069 tty->TS_del_multi_lines = tgetstr ("DL", address);
4070 tty->TS_delete_mode = tgetstr ("dm", address);
4071 tty->TS_end_delete_mode = tgetstr ("ed", address);
4072 tty->TS_end_insert_mode = tgetstr ("ei", address);
4073 Home (tty) = tgetstr ("ho", address);
4074 tty->TS_ins_char = tgetstr ("ic", address);
4075 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4076 tty->TS_insert_mode = tgetstr ("im", address);
4077 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4078 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4079 tty->TS_keypad_mode = tgetstr ("ks", address);
4080 LastLine (tty) = tgetstr ("ll", address);
4081 Right (tty) = tgetstr ("nd", address);
4082 Down (tty) = tgetstr ("do", address);
4083 if (!Down (tty))
4084 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4085 if (tgetflag ("bs"))
4086 Left (tty) = "\b"; /* Can't possibly be longer! */
4087 else /* (Actually, "bs" is obsolete...) */
4088 Left (tty) = tgetstr ("le", address);
4089 if (!Left (tty))
4090 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4091 tty->TS_pad_char = tgetstr ("pc", address);
4092 tty->TS_repeat = tgetstr ("rp", address);
4093 tty->TS_end_standout_mode = tgetstr ("se", address);
4094 tty->TS_fwd_scroll = tgetstr ("sf", address);
4095 tty->TS_standout_mode = tgetstr ("so", address);
4096 tty->TS_rev_scroll = tgetstr ("sr", address);
4097 tty->Wcm->cm_tab = tgetstr ("ta", address);
4098 tty->TS_end_termcap_modes = tgetstr ("te", address);
4099 tty->TS_termcap_modes = tgetstr ("ti", address);
4100 Up (tty) = tgetstr ("up", address);
4101 tty->TS_visible_bell = tgetstr ("vb", address);
4102 tty->TS_cursor_normal = tgetstr ("ve", address);
4103 tty->TS_cursor_visible = tgetstr ("vs", address);
4104 tty->TS_cursor_invisible = tgetstr ("vi", address);
4105 tty->TS_set_window = tgetstr ("wi", address);
4107 tty->TS_enter_underline_mode = tgetstr ("us", address);
4108 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4109 tty->TS_enter_bold_mode = tgetstr ("md", address);
4110 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4111 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4112 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4113 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4114 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4115 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4117 MultiUp (tty) = tgetstr ("UP", address);
4118 MultiDown (tty) = tgetstr ("DO", address);
4119 MultiLeft (tty) = tgetstr ("LE", address);
4120 MultiRight (tty) = tgetstr ("RI", address);
4122 /* SVr4/ANSI color support. If "op" isn't available, don't support
4123 color because we can't switch back to the default foreground and
4124 background. */
4125 tty->TS_orig_pair = tgetstr ("op", address);
4126 if (tty->TS_orig_pair)
4128 tty->TS_set_foreground = tgetstr ("AF", address);
4129 tty->TS_set_background = tgetstr ("AB", address);
4130 if (!tty->TS_set_foreground)
4132 /* SVr4. */
4133 tty->TS_set_foreground = tgetstr ("Sf", address);
4134 tty->TS_set_background = tgetstr ("Sb", address);
4137 tty->TN_max_colors = tgetnum ("Co");
4138 tty->TN_max_pairs = tgetnum ("pa");
4140 tty->TN_no_color_video = tgetnum ("NC");
4141 if (tty->TN_no_color_video == -1)
4142 tty->TN_no_color_video = 0;
4145 tty_default_color_capabilities (tty, 1);
4147 MagicWrap (tty) = tgetflag ("xn");
4148 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4149 the former flag imply the latter. */
4150 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4151 tty->memory_below_frame = tgetflag ("db");
4152 tty->TF_hazeltine = tgetflag ("hz");
4153 tty->must_write_spaces = tgetflag ("in");
4154 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4155 tty->TF_insmode_motion = tgetflag ("mi");
4156 tty->TF_standout_motion = tgetflag ("ms");
4157 tty->TF_underscore = tgetflag ("ul");
4158 tty->TF_teleray = tgetflag ("xt");
4160 #else /* DOS_NT */
4161 #ifdef WINDOWSNT
4163 struct frame *f = XFRAME (selected_frame);
4164 int height, width;
4166 initialize_w32_display (terminal, &width, &height);
4168 FrameRows (tty) = height;
4169 FrameCols (tty) = width;
4170 tty->specified_window = height;
4172 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4173 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4174 tty->char_ins_del_ok = 1;
4175 baud_rate = 19200;
4177 #else /* MSDOS */
4179 int height, width;
4180 if (strcmp (terminal_type, "internal") == 0)
4181 terminal->type = output_msdos_raw;
4182 initialize_msdos_display (terminal);
4184 get_tty_size (fileno (tty->input), &width, &height);
4185 FrameCols (tty) = width;
4186 FrameRows (tty) = height;
4187 tty->char_ins_del_ok = 0;
4188 init_baud_rate (fileno (tty->input));
4190 #endif /* MSDOS */
4191 tty->output = stdout;
4192 tty->input = stdin;
4193 /* The following two are inaccessible from w32console.c. */
4194 terminal->delete_frame_hook = &tty_free_frame_resources;
4195 terminal->delete_terminal_hook = &delete_tty;
4197 tty->name = xstrdup (name);
4198 terminal->name = xstrdup (name);
4199 tty->type = xstrdup (terminal_type);
4201 add_keyboard_wait_descriptor (0);
4203 tty->delete_in_insert_mode = 1;
4205 UseTabs (tty) = 0;
4206 tty->scroll_region_ok = 0;
4208 /* Seems to insert lines when it's not supposed to, messing up the
4209 display. In doing a trace, it didn't seem to be called much, so I
4210 don't think we're losing anything by turning it off. */
4211 tty->line_ins_del_ok = 0;
4213 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4214 #endif /* DOS_NT */
4216 #ifdef HAVE_GPM
4217 terminal->mouse_position_hook = term_mouse_position;
4218 tty->mouse_highlight.mouse_face_window = Qnil;
4219 #endif
4221 terminal->kboard = allocate_kboard (Qnil);
4222 terminal->kboard->reference_count++;
4223 /* Don't let the initial kboard remain current longer than necessary.
4224 That would cause problems if a file loaded on startup tries to
4225 prompt in the mini-buffer. */
4226 if (current_kboard == initial_kboard)
4227 current_kboard = terminal->kboard;
4228 #ifndef DOS_NT
4229 term_get_fkeys (address, terminal->kboard);
4231 /* Get frame size from system, or else from termcap. */
4233 int height, width;
4234 get_tty_size (fileno (tty->input), &width, &height);
4235 FrameCols (tty) = width;
4236 FrameRows (tty) = height;
4239 if (FrameCols (tty) <= 0)
4240 FrameCols (tty) = tgetnum ("co");
4241 if (FrameRows (tty) <= 0)
4242 FrameRows (tty) = tgetnum ("li");
4244 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4245 maybe_fatal (must_succeed, terminal,
4246 "Screen size %dx%d is too small",
4247 "Screen size %dx%d is too small",
4248 FrameCols (tty), FrameRows (tty));
4250 TabWidth (tty) = tgetnum ("tw");
4252 if (!tty->TS_bell)
4253 tty->TS_bell = "\07";
4255 if (!tty->TS_fwd_scroll)
4256 tty->TS_fwd_scroll = Down (tty);
4258 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4260 if (TabWidth (tty) < 0)
4261 TabWidth (tty) = 8;
4263 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4264 and newer termcap doc does not seem to say there is a default.
4265 if (!tty->Wcm->cm_tab)
4266 tty->Wcm->cm_tab = "\t";
4269 /* We don't support standout modes that use `magic cookies', so
4270 turn off any that do. */
4271 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4273 tty->TS_standout_mode = 0;
4274 tty->TS_end_standout_mode = 0;
4276 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4278 tty->TS_enter_underline_mode = 0;
4279 tty->TS_exit_underline_mode = 0;
4282 /* If there's no standout mode, try to use underlining instead. */
4283 if (tty->TS_standout_mode == 0)
4285 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4286 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4289 /* If no `se' string, try using a `me' string instead.
4290 If that fails, we can't use standout mode at all. */
4291 if (tty->TS_end_standout_mode == 0)
4293 char *s = tgetstr ("me", address);
4294 if (s != 0)
4295 tty->TS_end_standout_mode = s;
4296 else
4297 tty->TS_standout_mode = 0;
4300 if (tty->TF_teleray)
4302 tty->Wcm->cm_tab = 0;
4303 /* We can't support standout mode, because it uses magic cookies. */
4304 tty->TS_standout_mode = 0;
4305 /* But that means we cannot rely on ^M to go to column zero! */
4306 CR (tty) = 0;
4307 /* LF can't be trusted either -- can alter hpos. */
4308 /* If move at column 0 thru a line with TS_standout_mode. */
4309 Down (tty) = 0;
4312 tty->specified_window = FrameRows (tty);
4314 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4316 maybe_fatal (must_succeed, terminal,
4317 "Terminal type \"%s\" is not powerful enough to run Emacs",
4318 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4319 It lacks the ability to position the cursor.\n\
4320 If that is not the actual type of terminal you have,\n\
4321 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4322 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4323 # ifdef TERMINFO
4324 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4325 # else /* TERMCAP */
4326 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4327 # endif /* TERMINFO */
4328 terminal_type);
4331 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4332 maybe_fatal (must_succeed, terminal,
4333 "Could not determine the frame size",
4334 "Could not determine the frame size");
4336 tty->delete_in_insert_mode
4337 = tty->TS_delete_mode && tty->TS_insert_mode
4338 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4340 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4342 tty->scroll_region_ok
4343 = (tty->Wcm->cm_abs
4344 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4346 tty->line_ins_del_ok
4347 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4348 && (tty->TS_del_line || tty->TS_del_multi_lines))
4349 || (tty->scroll_region_ok
4350 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4352 tty->char_ins_del_ok
4353 = ((tty->TS_ins_char || tty->TS_insert_mode
4354 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4355 && (tty->TS_del_char || tty->TS_del_multi_chars));
4357 init_baud_rate (fileno (tty->input));
4359 #endif /* not DOS_NT */
4361 /* Init system terminal modes (RAW or CBREAK, etc.). */
4362 init_sys_modes (tty);
4364 return terminal;
4368 static void
4369 vfatal (const char *str, va_list ap)
4371 fprintf (stderr, "emacs: ");
4372 vfprintf (stderr, str, ap);
4373 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4374 fprintf (stderr, "\n");
4375 fflush (stderr);
4376 exit (1);
4380 /* Auxiliary error-handling function for init_tty.
4381 Delete TERMINAL, then call error or fatal with str1 or str2,
4382 respectively, according to whether MUST_SUCCEED is true. */
4384 static void
4385 maybe_fatal (bool must_succeed, struct terminal *terminal,
4386 const char *str1, const char *str2, ...)
4388 va_list ap;
4389 va_start (ap, str2);
4390 if (terminal)
4391 delete_tty (terminal);
4393 if (must_succeed)
4394 vfatal (str2, ap);
4395 else
4396 verror (str1, ap);
4399 void
4400 fatal (const char *str, ...)
4402 va_list ap;
4403 va_start (ap, str);
4404 vfatal (str, ap);
4409 /* Delete the given tty terminal, closing all frames on it. */
4411 static void
4412 delete_tty (struct terminal *terminal)
4414 struct tty_display_info *tty;
4416 /* Protect against recursive calls. delete_frame in
4417 delete_terminal calls us back when it deletes our last frame. */
4418 if (!terminal->name)
4419 return;
4421 eassert (terminal->type == output_termcap);
4423 tty = terminal->display_info.tty;
4425 if (tty == tty_list)
4426 tty_list = tty->next;
4427 else
4429 struct tty_display_info *p;
4430 for (p = tty_list; p && p->next != tty; p = p->next)
4433 if (! p)
4434 /* This should not happen. */
4435 emacs_abort ();
4437 p->next = tty->next;
4438 tty->next = 0;
4441 /* reset_sys_modes needs a valid device, so this call needs to be
4442 before delete_terminal. */
4443 reset_sys_modes (tty);
4445 delete_terminal (terminal);
4447 xfree (tty->name);
4448 xfree (tty->type);
4450 if (tty->input)
4452 delete_keyboard_wait_descriptor (fileno (tty->input));
4453 if (tty->input != stdin)
4454 fclose (tty->input);
4456 if (tty->output && tty->output != stdout && tty->output != tty->input)
4457 fclose (tty->output);
4458 if (tty->termscript)
4459 fclose (tty->termscript);
4461 xfree (tty->old_tty);
4462 xfree (tty->Wcm);
4463 xfree (tty);
4466 void
4467 syms_of_term (void)
4469 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4470 doc: /* Non-nil means the system uses terminfo rather than termcap.
4471 This variable can be used by terminal emulator packages. */);
4472 #ifdef TERMINFO
4473 system_uses_terminfo = 1;
4474 #else
4475 system_uses_terminfo = 0;
4476 #endif
4478 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4479 doc: /* Functions run after suspending a tty.
4480 The functions are run with one argument, the terminal object to be suspended.
4481 See `suspend-tty'. */);
4482 Vsuspend_tty_functions = Qnil;
4485 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4486 doc: /* Functions run after resuming a tty.
4487 The functions are run with one argument, the terminal object that was revived.
4488 See `resume-tty'. */);
4489 Vresume_tty_functions = Qnil;
4491 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4492 doc: /* Non-nil means to make the cursor very visible.
4493 This only has an effect when running in a text terminal.
4494 What means \"very visible\" is up to your terminal. It may make the cursor
4495 bigger, or it may make it blink, or it may do nothing at all. */);
4496 visible_cursor = 1;
4498 defsubr (&Stty_display_color_p);
4499 defsubr (&Stty_display_color_cells);
4500 defsubr (&Stty_no_underline);
4501 defsubr (&Stty_type);
4502 defsubr (&Scontrolling_tty_p);
4503 defsubr (&Stty_top_frame);
4504 defsubr (&Ssuspend_tty);
4505 defsubr (&Sresume_tty);
4506 #ifdef HAVE_GPM
4507 defsubr (&Sgpm_mouse_start);
4508 defsubr (&Sgpm_mouse_stop);
4509 #endif /* HAVE_GPM */
4511 #ifndef DOS_NT
4512 default_orig_pair = NULL;
4513 default_set_foreground = NULL;
4514 default_set_background = NULL;
4515 #endif /* !DOS_NT */
4517 encode_terminal_src = NULL;
4518 encode_terminal_dst = NULL;
4520 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4521 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4523 #ifndef MSDOS
4524 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4525 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4526 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4527 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4528 DEFSYM (Qtty_menu_select, "tty-menu-select");
4529 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4530 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4531 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4532 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4533 #endif