Fix Bug#21841
[emacs.git] / src / term.c
blob245712ecfc4aa36f41e40088299032d4d77957bf
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2015 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
10 (at 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 <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #ifdef MSDOS
48 #include "msdos.h"
49 static int been_here = -1;
50 #endif
52 #ifdef USE_X_TOOLKIT
53 #include "../lwlib/lwlib.h"
54 #endif
56 #include "cm.h"
57 #include "menu.h"
59 /* The name of the default console device. */
60 #ifdef WINDOWSNT
61 #define DEV_TTY "CONOUT$"
62 #include "w32term.h"
63 #else
64 #define DEV_TTY "/dev/tty"
65 #endif
67 static void tty_set_scroll_region (struct frame *f, int start, int stop);
68 static void turn_on_face (struct frame *, int face_id);
69 static void turn_off_face (struct frame *, int face_id);
70 static void tty_turn_off_highlight (struct tty_display_info *);
71 static void tty_show_cursor (struct tty_display_info *);
72 static void tty_hide_cursor (struct tty_display_info *);
73 static void tty_background_highlight (struct tty_display_info *tty);
74 static void clear_tty_hooks (struct terminal *terminal);
75 static void set_tty_hooks (struct terminal *terminal);
76 static void dissociate_if_controlling_tty (int fd);
77 static void delete_tty (struct terminal *);
78 static _Noreturn void maybe_fatal (bool, struct terminal *,
79 const char *, const char *, ...)
80 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
81 static _Noreturn void vfatal (const char *str, va_list ap)
82 ATTRIBUTE_FORMAT_PRINTF (1, 0);
85 #define OUTPUT(tty, a) \
86 emacs_tputs ((tty), a, \
87 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
88 cmputc)
90 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
91 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
93 #define OUTPUT_IF(tty, a) \
94 do { \
95 if (a) \
96 OUTPUT (tty, a); \
97 } while (0)
99 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
101 /* Display space properties. */
103 /* Chain of all tty device parameters. */
104 struct tty_display_info *tty_list;
106 /* Meaning of bits in no_color_video. Each bit set means that the
107 corresponding attribute cannot be combined with colors. */
109 enum no_color_bit
111 NC_STANDOUT = 1 << 0,
112 NC_UNDERLINE = 1 << 1,
113 NC_REVERSE = 1 << 2,
114 NC_ITALIC = 1 << 3,
115 NC_DIM = 1 << 4,
116 NC_BOLD = 1 << 5,
117 NC_INVIS = 1 << 6,
118 NC_PROTECT = 1 << 7
121 /* internal state */
123 /* The largest frame width in any call to calculate_costs. */
125 static int max_frame_cols;
129 #ifdef HAVE_GPM
130 #include <sys/fcntl.h>
132 /* The device for which we have enabled gpm support (or NULL). */
133 struct tty_display_info *gpm_tty = NULL;
135 /* Last recorded mouse coordinates. */
136 static int last_mouse_x, last_mouse_y;
137 #endif /* HAVE_GPM */
139 /* Ring the bell on a tty. */
141 static void
142 tty_ring_bell (struct frame *f)
144 struct tty_display_info *tty = FRAME_TTY (f);
146 if (tty->output)
148 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
149 ? tty->TS_visible_bell
150 : tty->TS_bell));
151 fflush (tty->output);
155 /* Set up termcap modes for Emacs. */
157 static void
158 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
160 Lisp_Object lisp_terminal;
161 Lisp_Object extra_codes;
162 struct tty_display_info *tty = terminal->display_info.tty;
164 XSETTERMINAL (lisp_terminal, terminal);
165 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
166 CONSP (extra_codes);
167 extra_codes = XCDR (extra_codes))
169 Lisp_Object string = XCAR (extra_codes);
170 if (STRINGP (string))
172 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
173 if (tty->termscript)
174 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
179 static void
180 tty_set_terminal_modes (struct terminal *terminal)
182 struct tty_display_info *tty = terminal->display_info.tty;
184 if (tty->output)
186 if (tty->TS_termcap_modes)
187 OUTPUT (tty, tty->TS_termcap_modes);
188 else
190 /* Output enough newlines to scroll all the old screen contents
191 off the screen, so it won't be overwritten and lost. */
192 int i;
193 current_tty = tty;
194 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
195 cmputc ('\n');
198 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
199 OUTPUT_IF (tty, tty->TS_keypad_mode);
200 losecursor (tty);
201 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
202 fflush (tty->output);
206 /* Reset termcap modes before exiting Emacs. */
208 static void
209 tty_reset_terminal_modes (struct terminal *terminal)
211 struct tty_display_info *tty = terminal->display_info.tty;
213 if (tty->output)
215 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
216 tty_turn_off_highlight (tty);
217 tty_turn_off_insert (tty);
218 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
219 OUTPUT_IF (tty, tty->TS_cursor_normal);
220 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
221 OUTPUT_IF (tty, tty->TS_orig_pair);
222 /* Output raw CR so kernel can track the cursor hpos. */
223 current_tty = tty;
224 cmputc ('\r');
225 fflush (tty->output);
229 /* Flag the end of a display update on a termcap terminal. */
231 static void
232 tty_update_end (struct frame *f)
234 struct tty_display_info *tty = FRAME_TTY (f);
236 if (!XWINDOW (selected_window)->cursor_off_p)
237 tty_show_cursor (tty);
238 tty_turn_off_insert (tty);
239 tty_background_highlight (tty);
240 fflush (tty->output);
243 /* The implementation of set_terminal_window for termcap frames. */
245 static void
246 tty_set_terminal_window (struct frame *f, int size)
248 struct tty_display_info *tty = FRAME_TTY (f);
250 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
251 if (FRAME_SCROLL_REGION_OK (f))
252 tty_set_scroll_region (f, 0, tty->specified_window);
255 static void
256 tty_set_scroll_region (struct frame *f, int start, int stop)
258 char *buf;
259 struct tty_display_info *tty = FRAME_TTY (f);
261 if (tty->TS_set_scroll_region)
262 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
263 else if (tty->TS_set_scroll_region_1)
264 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
265 FRAME_TOTAL_LINES (f), start,
266 FRAME_TOTAL_LINES (f) - stop,
267 FRAME_TOTAL_LINES (f));
268 else
269 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
271 OUTPUT (tty, buf);
272 xfree (buf);
273 losecursor (tty);
277 static void
278 tty_turn_on_insert (struct tty_display_info *tty)
280 if (!tty->insert_mode)
281 OUTPUT (tty, tty->TS_insert_mode);
282 tty->insert_mode = 1;
285 void
286 tty_turn_off_insert (struct tty_display_info *tty)
288 if (tty->insert_mode)
289 OUTPUT (tty, tty->TS_end_insert_mode);
290 tty->insert_mode = 0;
293 /* Handle highlighting. */
295 static void
296 tty_turn_off_highlight (struct tty_display_info *tty)
298 if (tty->standout_mode)
299 OUTPUT_IF (tty, tty->TS_end_standout_mode);
300 tty->standout_mode = 0;
303 static void
304 tty_turn_on_highlight (struct tty_display_info *tty)
306 if (!tty->standout_mode)
307 OUTPUT_IF (tty, tty->TS_standout_mode);
308 tty->standout_mode = 1;
311 static void
312 tty_toggle_highlight (struct tty_display_info *tty)
314 if (tty->standout_mode)
315 tty_turn_off_highlight (tty);
316 else
317 tty_turn_on_highlight (tty);
321 /* Make cursor invisible. */
323 static void
324 tty_hide_cursor (struct tty_display_info *tty)
326 if (tty->cursor_hidden == 0)
328 tty->cursor_hidden = 1;
329 #ifdef WINDOWSNT
330 w32con_hide_cursor ();
331 #else
332 OUTPUT_IF (tty, tty->TS_cursor_invisible);
333 #endif
338 /* Ensure that cursor is visible. */
340 static void
341 tty_show_cursor (struct tty_display_info *tty)
343 if (tty->cursor_hidden)
345 tty->cursor_hidden = 0;
346 #ifdef WINDOWSNT
347 w32con_show_cursor ();
348 #else
349 OUTPUT_IF (tty, tty->TS_cursor_normal);
350 if (visible_cursor)
351 OUTPUT_IF (tty, tty->TS_cursor_visible);
352 #endif
357 /* Set standout mode to the state it should be in for
358 empty space inside windows. What this is,
359 depends on the user option inverse-video. */
361 static void
362 tty_background_highlight (struct tty_display_info *tty)
364 if (inverse_video)
365 tty_turn_on_highlight (tty);
366 else
367 tty_turn_off_highlight (tty);
370 /* Set standout mode to the mode specified for the text to be output. */
372 static void
373 tty_highlight_if_desired (struct tty_display_info *tty)
375 if (inverse_video)
376 tty_turn_on_highlight (tty);
377 else
378 tty_turn_off_highlight (tty);
382 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
383 frame-relative coordinates. */
385 static void
386 tty_cursor_to (struct frame *f, int vpos, int hpos)
388 struct tty_display_info *tty = FRAME_TTY (f);
390 /* Detect the case where we are called from reset_sys_modes
391 and the costs have never been calculated. Do nothing. */
392 if (! tty->costs_set)
393 return;
395 if (curY (tty) == vpos
396 && curX (tty) == hpos)
397 return;
398 if (!tty->TF_standout_motion)
399 tty_background_highlight (tty);
400 if (!tty->TF_insmode_motion)
401 tty_turn_off_insert (tty);
402 cmgoto (tty, vpos, hpos);
405 /* Similar but don't take any account of the wasted characters. */
407 static void
408 tty_raw_cursor_to (struct frame *f, int row, int col)
410 struct tty_display_info *tty = FRAME_TTY (f);
412 if (curY (tty) == row
413 && curX (tty) == col)
414 return;
415 if (!tty->TF_standout_motion)
416 tty_background_highlight (tty);
417 if (!tty->TF_insmode_motion)
418 tty_turn_off_insert (tty);
419 cmgoto (tty, row, col);
422 /* Erase operations */
424 /* Clear from cursor to end of frame on a termcap device. */
426 static void
427 tty_clear_to_end (struct frame *f)
429 register int i;
430 struct tty_display_info *tty = FRAME_TTY (f);
432 if (tty->TS_clr_to_bottom)
434 tty_background_highlight (tty);
435 OUTPUT (tty, tty->TS_clr_to_bottom);
437 else
439 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
441 cursor_to (f, i, 0);
442 clear_end_of_line (f, FRAME_COLS (f));
447 /* Clear an entire termcap frame. */
449 static void
450 tty_clear_frame (struct frame *f)
452 struct tty_display_info *tty = FRAME_TTY (f);
454 if (tty->TS_clr_frame)
456 tty_background_highlight (tty);
457 OUTPUT (tty, tty->TS_clr_frame);
458 cmat (tty, 0, 0);
460 else
462 cursor_to (f, 0, 0);
463 clear_to_end (f);
467 /* An implementation of clear_end_of_line for termcap frames.
469 Note that the cursor may be moved, on terminals lacking a `ce' string. */
471 static void
472 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
474 register int i;
475 struct tty_display_info *tty = FRAME_TTY (f);
477 /* Detect the case where we are called from reset_sys_modes
478 and the costs have never been calculated. Do nothing. */
479 if (! tty->costs_set)
480 return;
482 if (curX (tty) >= first_unused_hpos)
483 return;
484 tty_background_highlight (tty);
485 if (tty->TS_clr_line)
487 OUTPUT1 (tty, tty->TS_clr_line);
489 else
490 { /* have to do it the hard way */
491 tty_turn_off_insert (tty);
493 /* Do not write in last row last col with Auto-wrap on. */
494 if (AutoWrap (tty)
495 && curY (tty) == FrameRows (tty) - 1
496 && first_unused_hpos == FrameCols (tty))
497 first_unused_hpos--;
499 for (i = curX (tty); i < first_unused_hpos; i++)
501 if (tty->termscript)
502 fputc (' ', tty->termscript);
503 fputc (' ', tty->output);
505 cmplus (tty, first_unused_hpos - curX (tty));
509 /* Buffers to store the source and result of code conversion for terminal. */
510 static unsigned char *encode_terminal_src;
511 static unsigned char *encode_terminal_dst;
512 /* Allocated sizes of the above buffers. */
513 static ptrdiff_t encode_terminal_src_size;
514 static ptrdiff_t encode_terminal_dst_size;
516 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
517 Set CODING->produced to the byte-length of the resulting byte
518 sequence, and return a pointer to that byte sequence. */
520 unsigned char *
521 encode_terminal_code (struct glyph *src, int src_len,
522 struct coding_system *coding)
524 struct glyph *src_end = src + src_len;
525 unsigned char *buf;
526 ptrdiff_t nchars, nbytes, required;
527 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
528 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
529 Lisp_Object charset_list;
531 /* Allocate sufficient size of buffer to store all characters in
532 multibyte-form. But, it may be enlarged on demand if
533 Vglyph_table contains a string or a composite glyph is
534 encountered. */
535 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
536 memory_full (SIZE_MAX);
537 required = src_len;
538 required *= MAX_MULTIBYTE_LENGTH;
539 if (encode_terminal_src_size < required)
540 encode_terminal_src = xpalloc (encode_terminal_src,
541 &encode_terminal_src_size,
542 required - encode_terminal_src_size,
543 -1, sizeof *encode_terminal_src);
545 charset_list = coding_charset_list (coding);
547 buf = encode_terminal_src;
548 nchars = 0;
549 while (src < src_end)
551 if (src->type == COMPOSITE_GLYPH)
553 struct composition *cmp IF_LINT (= NULL);
554 Lisp_Object gstring IF_LINT (= Qnil);
555 int i;
557 nbytes = buf - encode_terminal_src;
558 if (src->u.cmp.automatic)
560 gstring = composition_gstring_from_id (src->u.cmp.id);
561 required = src->slice.cmp.to - src->slice.cmp.from + 1;
563 else
565 cmp = composition_table[src->u.cmp.id];
566 required = cmp->glyph_len;
567 required *= MAX_MULTIBYTE_LENGTH;
570 if (encode_terminal_src_size - nbytes < required)
572 encode_terminal_src =
573 xpalloc (encode_terminal_src, &encode_terminal_src_size,
574 required - (encode_terminal_src_size - nbytes),
575 -1, 1);
576 buf = encode_terminal_src + nbytes;
579 if (src->u.cmp.automatic)
580 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
582 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
583 int c = LGLYPH_CHAR (g);
585 if (! char_charset (c, charset_list, NULL))
586 c = '?';
587 buf += CHAR_STRING (c, buf);
588 nchars++;
590 else
591 for (i = 0; i < cmp->glyph_len; i++)
593 int c = COMPOSITION_GLYPH (cmp, i);
595 /* TAB in a composition means display glyphs with
596 padding space on the left or right. */
597 if (c == '\t')
598 continue;
599 if (char_charset (c, charset_list, NULL))
601 if (CHAR_WIDTH (c) == 0
602 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
603 /* Should be left-padded */
605 buf += CHAR_STRING (' ', buf);
606 nchars++;
609 else
610 c = '?';
611 buf += CHAR_STRING (c, buf);
612 nchars++;
615 /* We must skip glyphs to be padded for a wide character. */
616 else if (! CHAR_GLYPH_PADDING_P (*src))
618 GLYPH g;
619 int c IF_LINT (= 0);
620 Lisp_Object string;
622 string = Qnil;
623 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
625 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
627 /* This glyph doesn't have an entry in Vglyph_table. */
628 c = src->u.ch;
630 else
632 /* This glyph has an entry in Vglyph_table,
633 so process any alias before testing for simpleness. */
634 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
636 if (GLYPH_SIMPLE_P (tbase, tlen, g))
637 /* We set the multi-byte form of a character in G
638 (that should be an ASCII character) at WORKBUF. */
639 c = GLYPH_CHAR (g);
640 else
641 /* We have a string in Vglyph_table. */
642 string = tbase[GLYPH_CHAR (g)];
645 if (NILP (string))
647 nbytes = buf - encode_terminal_src;
648 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
650 encode_terminal_src =
651 xpalloc (encode_terminal_src, &encode_terminal_src_size,
652 MAX_MULTIBYTE_LENGTH, -1, 1);
653 buf = encode_terminal_src + nbytes;
655 if (CHAR_BYTE8_P (c)
656 || char_charset (c, charset_list, NULL))
658 /* Store the multibyte form of C at BUF. */
659 buf += CHAR_STRING (c, buf);
660 nchars++;
662 else
664 /* C is not encodable. */
665 *buf++ = '?';
666 nchars++;
667 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
669 *buf++ = '?';
670 nchars++;
671 src++;
675 else
677 if (! STRING_MULTIBYTE (string))
678 string = string_to_multibyte (string);
679 nbytes = buf - encode_terminal_src;
680 if (encode_terminal_src_size - nbytes < SBYTES (string))
682 encode_terminal_src =
683 xpalloc (encode_terminal_src, &encode_terminal_src_size,
684 (SBYTES (string)
685 - (encode_terminal_src_size - nbytes)),
686 -1, 1);
687 buf = encode_terminal_src + nbytes;
689 memcpy (buf, SDATA (string), SBYTES (string));
690 buf += SBYTES (string);
691 nchars += SCHARS (string);
694 src++;
697 if (nchars == 0)
699 coding->produced = 0;
700 return NULL;
703 nbytes = buf - encode_terminal_src;
704 coding->source = encode_terminal_src;
705 if (encode_terminal_dst_size == 0)
707 encode_terminal_dst = xrealloc (encode_terminal_dst,
708 encode_terminal_src_size);
709 encode_terminal_dst_size = encode_terminal_src_size;
711 coding->destination = encode_terminal_dst;
712 coding->dst_bytes = encode_terminal_dst_size;
713 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
714 /* coding->destination may have been reallocated. */
715 encode_terminal_dst = coding->destination;
716 encode_terminal_dst_size = coding->dst_bytes;
718 return (encode_terminal_dst);
723 /* An implementation of write_glyphs for termcap frames. */
725 static void
726 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
728 unsigned char *conversion_buffer;
729 struct coding_system *coding;
730 int n, stringlen;
732 struct tty_display_info *tty = FRAME_TTY (f);
734 tty_turn_off_insert (tty);
735 tty_hide_cursor (tty);
737 /* Don't dare write in last column of bottom line, if Auto-Wrap,
738 since that would scroll the whole frame on some terminals. */
740 if (AutoWrap (tty)
741 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
742 && (curX (tty) + len) == FRAME_COLS (f))
743 len --;
744 if (len <= 0)
745 return;
747 cmplus (tty, len);
749 /* If terminal_coding does any conversion, use it, otherwise use
750 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
751 because it always return 1 if the member src_multibyte is 1. */
752 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
753 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
754 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
755 the tail. */
756 coding->mode &= ~CODING_MODE_LAST_BLOCK;
758 for (stringlen = len; stringlen != 0; stringlen -= n)
760 /* Identify a run of glyphs with the same face. */
761 int face_id = string->face_id;
763 for (n = 1; n < stringlen; ++n)
764 if (string[n].face_id != face_id)
765 break;
767 /* Turn appearance modes of the face of the run on. */
768 tty_highlight_if_desired (tty);
769 turn_on_face (f, face_id);
771 if (n == stringlen)
772 /* This is the last run. */
773 coding->mode |= CODING_MODE_LAST_BLOCK;
774 conversion_buffer = encode_terminal_code (string, n, coding);
775 if (coding->produced > 0)
777 block_input ();
778 fwrite (conversion_buffer, 1, coding->produced, tty->output);
779 if (ferror (tty->output))
780 clearerr (tty->output);
781 if (tty->termscript)
782 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
783 unblock_input ();
785 string += n;
787 /* Turn appearance modes off. */
788 turn_off_face (f, face_id);
789 tty_turn_off_highlight (tty);
792 cmcheckmagic (tty);
795 #ifdef HAVE_GPM /* Only used by GPM code. */
797 static void
798 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
799 register int len, register int face_id)
801 unsigned char *conversion_buffer;
802 struct coding_system *coding;
804 struct tty_display_info *tty = FRAME_TTY (f);
806 tty_turn_off_insert (tty);
807 tty_hide_cursor (tty);
809 /* Don't dare write in last column of bottom line, if Auto-Wrap,
810 since that would scroll the whole frame on some terminals. */
812 if (AutoWrap (tty)
813 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
814 && (curX (tty) + len) == FRAME_COLS (f))
815 len --;
816 if (len <= 0)
817 return;
819 cmplus (tty, len);
821 /* If terminal_coding does any conversion, use it, otherwise use
822 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
823 because it always return 1 if the member src_multibyte is 1. */
824 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
825 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
826 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
827 the tail. */
828 coding->mode &= ~CODING_MODE_LAST_BLOCK;
830 /* Turn appearance modes of the face. */
831 tty_highlight_if_desired (tty);
832 turn_on_face (f, face_id);
834 coding->mode |= CODING_MODE_LAST_BLOCK;
835 conversion_buffer = encode_terminal_code (string, len, coding);
836 if (coding->produced > 0)
838 block_input ();
839 fwrite (conversion_buffer, 1, coding->produced, tty->output);
840 if (ferror (tty->output))
841 clearerr (tty->output);
842 if (tty->termscript)
843 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
844 unblock_input ();
847 /* Turn appearance modes off. */
848 turn_off_face (f, face_id);
849 tty_turn_off_highlight (tty);
851 cmcheckmagic (tty);
853 #endif
855 /* An implementation of insert_glyphs for termcap frames. */
857 static void
858 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
860 char *buf;
861 struct glyph *glyph = NULL;
862 unsigned char *conversion_buffer;
863 unsigned char space[1];
864 struct coding_system *coding;
866 struct tty_display_info *tty = FRAME_TTY (f);
868 if (tty->TS_ins_multi_chars)
870 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
871 OUTPUT1 (tty, buf);
872 xfree (buf);
873 if (start)
874 write_glyphs (f, start, len);
875 return;
878 tty_turn_on_insert (tty);
879 cmplus (tty, len);
881 if (! start)
882 space[0] = SPACEGLYPH;
884 /* If terminal_coding does any conversion, use it, otherwise use
885 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
886 because it always return 1 if the member src_multibyte is 1. */
887 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
888 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
889 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
890 the tail. */
891 coding->mode &= ~CODING_MODE_LAST_BLOCK;
893 while (len-- > 0)
895 OUTPUT1_IF (tty, tty->TS_ins_char);
896 if (!start)
898 conversion_buffer = space;
899 coding->produced = 1;
901 else
903 tty_highlight_if_desired (tty);
904 turn_on_face (f, start->face_id);
905 glyph = start;
906 ++start;
907 /* We must open sufficient space for a character which
908 occupies more than one column. */
909 while (len && CHAR_GLYPH_PADDING_P (*start))
911 OUTPUT1_IF (tty, tty->TS_ins_char);
912 start++, len--;
915 if (len <= 0)
916 /* This is the last glyph. */
917 coding->mode |= CODING_MODE_LAST_BLOCK;
919 conversion_buffer = encode_terminal_code (glyph, 1, coding);
922 if (coding->produced > 0)
924 block_input ();
925 fwrite (conversion_buffer, 1, coding->produced, tty->output);
926 if (ferror (tty->output))
927 clearerr (tty->output);
928 if (tty->termscript)
929 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
930 unblock_input ();
933 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
934 if (start)
936 turn_off_face (f, glyph->face_id);
937 tty_turn_off_highlight (tty);
941 cmcheckmagic (tty);
944 /* An implementation of delete_glyphs for termcap frames. */
946 static void
947 tty_delete_glyphs (struct frame *f, int n)
949 char *buf;
950 register int i;
952 struct tty_display_info *tty = FRAME_TTY (f);
954 if (tty->delete_in_insert_mode)
956 tty_turn_on_insert (tty);
958 else
960 tty_turn_off_insert (tty);
961 OUTPUT_IF (tty, tty->TS_delete_mode);
964 if (tty->TS_del_multi_chars)
966 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
967 OUTPUT1 (tty, buf);
968 xfree (buf);
970 else
971 for (i = 0; i < n; i++)
972 OUTPUT1 (tty, tty->TS_del_char);
973 if (!tty->delete_in_insert_mode)
974 OUTPUT_IF (tty, tty->TS_end_delete_mode);
977 /* An implementation of ins_del_lines for termcap frames. */
979 static void
980 tty_ins_del_lines (struct frame *f, int vpos, int n)
982 struct tty_display_info *tty = FRAME_TTY (f);
983 const char *multi =
984 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
985 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
986 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
988 int i = eabs (n);
989 char *buf;
991 /* If the lines below the insertion are being pushed
992 into the end of the window, this is the same as clearing;
993 and we know the lines are already clear, since the matching
994 deletion has already been done. So can ignore this. */
995 /* If the lines below the deletion are blank lines coming
996 out of the end of the window, don't bother,
997 as there will be a matching inslines later that will flush them. */
998 if (FRAME_SCROLL_REGION_OK (f)
999 && vpos + i >= tty->specified_window)
1000 return;
1001 if (!FRAME_MEMORY_BELOW_FRAME (f)
1002 && vpos + i >= FRAME_TOTAL_LINES (f))
1003 return;
1005 if (multi)
1007 raw_cursor_to (f, vpos, 0);
1008 tty_background_highlight (tty);
1009 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1010 OUTPUT (tty, buf);
1011 xfree (buf);
1013 else if (single)
1015 raw_cursor_to (f, vpos, 0);
1016 tty_background_highlight (tty);
1017 while (--i >= 0)
1018 OUTPUT (tty, single);
1019 if (tty->TF_teleray)
1020 curX (tty) = 0;
1022 else
1024 tty_set_scroll_region (f, vpos, tty->specified_window);
1025 if (n < 0)
1026 raw_cursor_to (f, tty->specified_window - 1, 0);
1027 else
1028 raw_cursor_to (f, vpos, 0);
1029 tty_background_highlight (tty);
1030 while (--i >= 0)
1031 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1032 tty_set_scroll_region (f, 0, tty->specified_window);
1035 if (!FRAME_SCROLL_REGION_OK (f)
1036 && FRAME_MEMORY_BELOW_FRAME (f)
1037 && n < 0)
1039 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1040 clear_to_end (f);
1044 /* Compute cost of sending "str", in characters,
1045 not counting any line-dependent padding. */
1048 string_cost (const char *str)
1050 cost = 0;
1051 if (str)
1052 tputs (str, 0, evalcost);
1053 return cost;
1056 /* Compute cost of sending "str", in characters,
1057 counting any line-dependent padding at one line. */
1059 static int
1060 string_cost_one_line (const char *str)
1062 cost = 0;
1063 if (str)
1064 tputs (str, 1, evalcost);
1065 return cost;
1068 /* Compute per line amount of line-dependent padding,
1069 in tenths of characters. */
1072 per_line_cost (const char *str)
1074 cost = 0;
1075 if (str)
1076 tputs (str, 0, evalcost);
1077 cost = - cost;
1078 if (str)
1079 tputs (str, 10, evalcost);
1080 return cost;
1083 /* char_ins_del_cost[n] is cost of inserting N characters.
1084 char_ins_del_cost[-n] is cost of deleting N characters.
1085 The length of this vector is based on max_frame_cols. */
1087 int *char_ins_del_vector;
1089 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1091 /* ARGSUSED */
1092 static void
1093 calculate_ins_del_char_costs (struct frame *f)
1095 struct tty_display_info *tty = FRAME_TTY (f);
1096 int ins_startup_cost, del_startup_cost;
1097 int ins_cost_per_char, del_cost_per_char;
1098 register int i;
1099 register int *p;
1101 if (tty->TS_ins_multi_chars)
1103 ins_cost_per_char = 0;
1104 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1106 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1107 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1109 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1110 + string_cost (tty->TS_end_insert_mode))) / 100;
1111 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1112 + string_cost_one_line (tty->TS_pad_inserted_char));
1114 else
1116 ins_startup_cost = 9999;
1117 ins_cost_per_char = 0;
1120 if (tty->TS_del_multi_chars)
1122 del_cost_per_char = 0;
1123 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1125 else if (tty->TS_del_char)
1127 del_startup_cost = (string_cost (tty->TS_delete_mode)
1128 + string_cost (tty->TS_end_delete_mode));
1129 if (tty->delete_in_insert_mode)
1130 del_startup_cost /= 2;
1131 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1133 else
1135 del_startup_cost = 9999;
1136 del_cost_per_char = 0;
1139 /* Delete costs are at negative offsets */
1140 p = &char_ins_del_cost (f)[0];
1141 for (i = FRAME_COLS (f); --i >= 0;)
1142 *--p = (del_startup_cost += del_cost_per_char);
1144 /* Doing nothing is free */
1145 p = &char_ins_del_cost (f)[0];
1146 *p++ = 0;
1148 /* Insert costs are at positive offsets */
1149 for (i = FRAME_COLS (f); --i >= 0;)
1150 *p++ = (ins_startup_cost += ins_cost_per_char);
1153 void
1154 calculate_costs (struct frame *frame)
1156 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1158 if (FRAME_TERMCAP_P (frame))
1160 struct tty_display_info *tty = FRAME_TTY (frame);
1161 register const char *f = (tty->TS_set_scroll_region
1162 ? tty->TS_set_scroll_region
1163 : tty->TS_set_scroll_region_1);
1165 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1167 tty->costs_set = 1;
1169 /* These variables are only used for terminal stuff. They are
1170 allocated once for the terminal frame of X-windows emacs, but not
1171 used afterwards.
1173 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1174 X turns off char_ins_del_ok. */
1176 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1177 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1178 < max_frame_cols)
1179 memory_full (SIZE_MAX);
1181 char_ins_del_vector =
1182 xrealloc (char_ins_del_vector,
1183 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1185 memset (char_ins_del_vector, 0,
1186 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1189 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1190 do_line_insertion_deletion_costs (frame,
1191 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1192 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1193 f, f, 1);
1194 else
1195 do_line_insertion_deletion_costs (frame,
1196 tty->TS_ins_line, tty->TS_ins_multi_lines,
1197 tty->TS_del_line, tty->TS_del_multi_lines,
1198 0, 0, 1);
1200 calculate_ins_del_char_costs (frame);
1202 /* Don't use TS_repeat if its padding is worse than sending the chars */
1203 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1204 tty->RPov = string_cost (tty->TS_repeat);
1205 else
1206 tty->RPov = FRAME_COLS (frame) * 2;
1208 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1212 struct fkey_table {
1213 const char *cap, *name;
1216 /* Termcap capability names that correspond directly to X keysyms.
1217 Some of these (marked "terminfo") aren't supplied by old-style
1218 (Berkeley) termcap entries. They're listed in X keysym order;
1219 except we put the keypad keys first, so that if they clash with
1220 other keys (as on the IBM PC keyboard) they get overridden.
1223 static const struct fkey_table keys[] =
1225 {"kh", "home"}, /* termcap */
1226 {"kl", "left"}, /* termcap */
1227 {"ku", "up"}, /* termcap */
1228 {"kr", "right"}, /* termcap */
1229 {"kd", "down"}, /* termcap */
1230 {"%8", "prior"}, /* terminfo */
1231 {"%5", "next"}, /* terminfo */
1232 {"@7", "end"}, /* terminfo */
1233 {"@1", "begin"}, /* terminfo */
1234 {"*6", "select"}, /* terminfo */
1235 {"%9", "print"}, /* terminfo */
1236 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1238 * "insert" --- see below
1240 {"&8", "undo"}, /* terminfo */
1241 {"%0", "redo"}, /* terminfo */
1242 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1243 {"@0", "find"}, /* terminfo */
1244 {"@2", "cancel"}, /* terminfo */
1245 {"%1", "help"}, /* terminfo */
1247 * "break" goes here, but can't be reliably intercepted with termcap
1249 {"&4", "reset"}, /* terminfo --- actually `restart' */
1251 * "system" and "user" --- no termcaps
1253 {"kE", "clearline"}, /* terminfo */
1254 {"kA", "insertline"}, /* terminfo */
1255 {"kL", "deleteline"}, /* terminfo */
1256 {"kI", "insertchar"}, /* terminfo */
1257 {"kD", "deletechar"}, /* terminfo */
1258 {"kB", "backtab"}, /* terminfo */
1260 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1262 {"@8", "kp-enter"}, /* terminfo */
1264 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1265 * "kp-multiply", "kp-add", "kp-separator",
1266 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1267 * --- no termcaps for any of these.
1269 {"K4", "kp-1"}, /* terminfo */
1271 * "kp-2" --- no termcap
1273 {"K5", "kp-3"}, /* terminfo */
1275 * "kp-4" --- no termcap
1277 {"K2", "kp-5"}, /* terminfo */
1279 * "kp-6" --- no termcap
1281 {"K1", "kp-7"}, /* terminfo */
1283 * "kp-8" --- no termcap
1285 {"K3", "kp-9"}, /* terminfo */
1287 * "kp-equal" --- no termcap
1289 {"k1", "f1"},
1290 {"k2", "f2"},
1291 {"k3", "f3"},
1292 {"k4", "f4"},
1293 {"k5", "f5"},
1294 {"k6", "f6"},
1295 {"k7", "f7"},
1296 {"k8", "f8"},
1297 {"k9", "f9"},
1299 {"&0", "S-cancel"}, /*shifted cancel key*/
1300 {"&9", "S-begin"}, /*shifted begin key*/
1301 {"*0", "S-find"}, /*shifted find key*/
1302 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1303 {"*4", "S-delete"}, /*shifted delete-character key*/
1304 {"*7", "S-end"}, /*shifted end key*/
1305 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1306 {"#1", "S-help"}, /*shifted help key*/
1307 {"#2", "S-home"}, /*shifted home key*/
1308 {"#3", "S-insert"}, /*shifted insert-character key*/
1309 {"#4", "S-left"}, /*shifted left-arrow key*/
1310 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1311 {"%c", "S-next"}, /*shifted next key*/
1312 {"%e", "S-prior"}, /*shifted previous key*/
1313 {"%f", "S-print"}, /*shifted print key*/
1314 {"%g", "S-redo"}, /*shifted redo key*/
1315 {"%i", "S-right"}, /*shifted right-arrow key*/
1316 {"!3", "S-undo"} /*shifted undo key*/
1319 #ifndef DOS_NT
1320 static char **term_get_fkeys_address;
1321 static KBOARD *term_get_fkeys_kboard;
1322 static Lisp_Object term_get_fkeys_1 (void);
1324 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1325 This function scans the termcap function key sequence entries, and
1326 adds entries to Vinput_decode_map for each function key it finds. */
1328 static void
1329 term_get_fkeys (char **address, KBOARD *kboard)
1331 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1332 errors during the call. The only errors should be from Fdefine_key
1333 when given a key sequence containing an invalid prefix key. If the
1334 termcap defines function keys which use a prefix that is already bound
1335 to a command by the default bindings, we should silently ignore that
1336 function key specification, rather than giving the user an error and
1337 refusing to run at all on such a terminal. */
1339 term_get_fkeys_address = address;
1340 term_get_fkeys_kboard = kboard;
1341 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1344 static Lisp_Object
1345 term_get_fkeys_1 (void)
1347 int i;
1349 char **address = term_get_fkeys_address;
1350 KBOARD *kboard = term_get_fkeys_kboard;
1352 /* This can happen if CANNOT_DUMP or with strange options. */
1353 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1354 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1356 for (i = 0; i < ARRAYELTS (keys); i++)
1358 char *sequence = tgetstr (keys[i].cap, address);
1359 if (sequence)
1360 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1361 Fmake_vector (make_number (1),
1362 intern (keys[i].name)));
1365 /* The uses of the "k0" capability are inconsistent; sometimes it
1366 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1367 We will attempt to politely accommodate both systems by testing for
1368 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1371 const char *k_semi = tgetstr ("k;", address);
1372 const char *k0 = tgetstr ("k0", address);
1373 const char *k0_name = "f10";
1375 if (k_semi)
1377 if (k0)
1378 /* Define f0 first, so that f10 takes precedence in case the
1379 key sequences happens to be the same. */
1380 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1381 Fmake_vector (make_number (1), intern ("f0")));
1382 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1383 Fmake_vector (make_number (1), intern ("f10")));
1385 else if (k0)
1386 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1387 Fmake_vector (make_number (1), intern (k0_name)));
1390 /* Set up cookies for numbered function keys above f10. */
1392 char fcap[3], fkey[4];
1394 fcap[0] = 'F'; fcap[2] = '\0';
1395 for (i = 11; i < 64; i++)
1397 if (i <= 19)
1398 fcap[1] = '1' + i - 11;
1399 else if (i <= 45)
1400 fcap[1] = 'A' + i - 20;
1401 else
1402 fcap[1] = 'a' + i - 46;
1405 char *sequence = tgetstr (fcap, address);
1406 if (sequence)
1408 sprintf (fkey, "f%d", i);
1409 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1410 Fmake_vector (make_number (1),
1411 intern (fkey)));
1418 * Various mappings to try and get a better fit.
1421 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1422 if (!tgetstr (cap1, address)) \
1424 char *sequence = tgetstr (cap2, address); \
1425 if (sequence) \
1426 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1427 Fmake_vector (make_number (1), \
1428 intern (sym))); \
1431 /* if there's no key_next keycap, map key_npage to `next' keysym */
1432 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1433 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1434 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1435 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1436 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1437 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1438 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1439 #undef CONDITIONAL_REASSIGN
1442 return Qnil;
1444 #endif /* not DOS_NT */
1447 /***********************************************************************
1448 Character Display Information
1449 ***********************************************************************/
1450 static void append_glyph (struct it *);
1451 static void append_composite_glyph (struct it *);
1452 static void produce_composite_glyph (struct it *);
1453 static void append_glyphless_glyph (struct it *, int, const char *);
1454 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1456 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1457 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1458 the character for which to produce glyphs; IT->face_id contains the
1459 character's face. Padding glyphs are appended if IT->c has a
1460 IT->pixel_width > 1. */
1462 static void
1463 append_glyph (struct it *it)
1465 struct glyph *glyph, *end;
1466 int i;
1468 eassert (it->glyph_row);
1469 glyph = (it->glyph_row->glyphs[it->area]
1470 + it->glyph_row->used[it->area]);
1471 end = it->glyph_row->glyphs[1 + it->area];
1473 /* If the glyph row is reversed, we need to prepend the glyph rather
1474 than append it. */
1475 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1477 struct glyph *g;
1478 int move_by = it->pixel_width;
1480 /* Make room for the new glyphs. */
1481 if (move_by > end - glyph) /* don't overstep end of this area */
1482 move_by = end - glyph;
1483 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1484 g[move_by] = *g;
1485 glyph = it->glyph_row->glyphs[it->area];
1486 end = glyph + move_by;
1489 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1490 right, even in the REVERSED_P case, since (a) all of its u.ch are
1491 identical, and (b) the PADDING_P flag needs to be set for the
1492 leftmost one, because we write to the terminal left-to-right. */
1493 for (i = 0;
1494 i < it->pixel_width && glyph < end;
1495 ++i)
1497 glyph->type = CHAR_GLYPH;
1498 glyph->pixel_width = 1;
1499 glyph->u.ch = it->char_to_display;
1500 glyph->face_id = it->face_id;
1501 glyph->padding_p = i > 0;
1502 glyph->charpos = CHARPOS (it->position);
1503 glyph->object = it->object;
1504 if (it->bidi_p)
1506 glyph->resolved_level = it->bidi_it.resolved_level;
1507 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1508 glyph->bidi_type = it->bidi_it.type;
1510 else
1512 glyph->resolved_level = 0;
1513 glyph->bidi_type = UNKNOWN_BT;
1516 ++it->glyph_row->used[it->area];
1517 ++glyph;
1521 /* For external use. */
1522 void
1523 tty_append_glyph (struct it *it)
1525 append_glyph (it);
1529 /* Produce glyphs for the display element described by IT. *IT
1530 specifies what we want to produce a glyph for (character, image, ...),
1531 and where in the glyph matrix we currently are (glyph row and hpos).
1532 produce_glyphs fills in output fields of *IT with information such as the
1533 pixel width and height of a character, and maybe output actual glyphs at
1534 the same time if IT->glyph_row is non-null. For an overview, see
1535 the explanation in dispextern.h, before the definition of the
1536 display_element_type enumeration.
1538 produce_glyphs also stores the result of glyph width, ascent
1539 etc. computations in *IT.
1541 IT->glyph_row may be null, in which case produce_glyphs does not
1542 actually fill in the glyphs. This is used in the move_* functions
1543 in xdisp.c for text width and height computations.
1545 Callers usually don't call produce_glyphs directly;
1546 instead they use the macro PRODUCE_GLYPHS. */
1548 void
1549 produce_glyphs (struct it *it)
1551 /* If a hook is installed, let it do the work. */
1553 /* Nothing but characters are supported on terminal frames. */
1554 eassert (it->what == IT_CHARACTER
1555 || it->what == IT_COMPOSITION
1556 || it->what == IT_STRETCH
1557 || it->what == IT_GLYPHLESS);
1559 if (it->what == IT_STRETCH)
1561 produce_stretch_glyph (it);
1562 goto done;
1565 if (it->what == IT_COMPOSITION)
1567 produce_composite_glyph (it);
1568 goto done;
1571 if (it->what == IT_GLYPHLESS)
1573 produce_glyphless_glyph (it, Qnil);
1574 goto done;
1577 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1579 it->pixel_width = it->nglyphs = 1;
1580 if (it->glyph_row)
1581 append_glyph (it);
1583 else if (it->char_to_display == '\n')
1584 it->pixel_width = it->nglyphs = 0;
1585 else if (it->char_to_display == '\t')
1587 int absolute_x = (it->current_x
1588 + it->continuation_lines_width);
1589 int next_tab_x
1590 = (((1 + absolute_x + it->tab_width - 1)
1591 / it->tab_width)
1592 * it->tab_width);
1593 int nspaces;
1595 /* If part of the TAB has been displayed on the previous line
1596 which is continued now, continuation_lines_width will have
1597 been incremented already by the part that fitted on the
1598 continued line. So, we will get the right number of spaces
1599 here. */
1600 nspaces = next_tab_x - absolute_x;
1602 if (it->glyph_row)
1604 int n = nspaces;
1606 it->char_to_display = ' ';
1607 it->pixel_width = it->len = 1;
1609 while (n--)
1610 append_glyph (it);
1613 it->pixel_width = nspaces;
1614 it->nglyphs = nspaces;
1616 else if (CHAR_BYTE8_P (it->char_to_display))
1618 /* Coming here means that we must send the raw 8-bit byte as is
1619 to the terminal. Although there's no way to know how many
1620 columns it occupies on a screen, it is a good assumption that
1621 a single byte code has 1-column width. */
1622 it->pixel_width = it->nglyphs = 1;
1623 if (it->glyph_row)
1624 append_glyph (it);
1626 else
1628 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1630 if (char_charset (it->char_to_display, charset_list, NULL))
1632 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1633 it->nglyphs = it->pixel_width;
1634 if (it->glyph_row)
1635 append_glyph (it);
1637 else
1639 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1641 eassert (it->what == IT_GLYPHLESS);
1642 produce_glyphless_glyph (it, acronym);
1646 done:
1647 /* Advance current_x by the pixel width as a convenience for
1648 the caller. */
1649 if (it->area == TEXT_AREA)
1650 it->current_x += it->pixel_width;
1651 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1652 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1655 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1656 Called from produce_composite_glyph for terminal frames if
1657 IT->glyph_row != NULL. IT->face_id contains the character's
1658 face. */
1660 static void
1661 append_composite_glyph (struct it *it)
1663 struct glyph *glyph;
1665 eassert (it->glyph_row);
1666 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1667 if (glyph < it->glyph_row->glyphs[1 + it->area])
1669 /* If the glyph row is reversed, we need to prepend the glyph
1670 rather than append it. */
1671 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1673 struct glyph *g;
1675 /* Make room for the new glyph. */
1676 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1677 g[1] = *g;
1678 glyph = it->glyph_row->glyphs[it->area];
1680 glyph->type = COMPOSITE_GLYPH;
1681 glyph->pixel_width = it->pixel_width;
1682 glyph->u.cmp.id = it->cmp_it.id;
1683 if (it->cmp_it.ch < 0)
1685 glyph->u.cmp.automatic = 0;
1686 glyph->u.cmp.id = it->cmp_it.id;
1688 else
1690 glyph->u.cmp.automatic = 1;
1691 glyph->u.cmp.id = it->cmp_it.id;
1692 glyph->slice.cmp.from = it->cmp_it.from;
1693 glyph->slice.cmp.to = it->cmp_it.to - 1;
1696 glyph->face_id = it->face_id;
1697 glyph->padding_p = 0;
1698 glyph->charpos = CHARPOS (it->position);
1699 glyph->object = it->object;
1700 if (it->bidi_p)
1702 glyph->resolved_level = it->bidi_it.resolved_level;
1703 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1704 glyph->bidi_type = it->bidi_it.type;
1706 else
1708 glyph->resolved_level = 0;
1709 glyph->bidi_type = UNKNOWN_BT;
1712 ++it->glyph_row->used[it->area];
1713 ++glyph;
1718 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1719 the composition. We simply produces components of the composition
1720 assuming that the terminal has a capability to layout/render it
1721 correctly. */
1723 static void
1724 produce_composite_glyph (struct it *it)
1726 if (it->cmp_it.ch < 0)
1728 struct composition *cmp = composition_table[it->cmp_it.id];
1730 it->pixel_width = cmp->width;
1732 else
1734 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1736 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1737 it->cmp_it.to, NULL);
1739 it->nglyphs = 1;
1740 if (it->glyph_row)
1741 append_composite_glyph (it);
1745 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1746 is a face ID to be used for the glyph. What is actually appended
1747 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1748 comes from it->nglyphs bytes). */
1750 static void
1751 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1753 struct glyph *glyph, *end;
1754 int i;
1756 eassert (it->glyph_row);
1757 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1758 end = it->glyph_row->glyphs[1 + it->area];
1760 /* If the glyph row is reversed, we need to prepend the glyph rather
1761 than append it. */
1762 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1764 struct glyph *g;
1765 int move_by = it->pixel_width;
1767 /* Make room for the new glyphs. */
1768 if (move_by > end - glyph) /* don't overstep end of this area */
1769 move_by = end - glyph;
1770 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1771 g[move_by] = *g;
1772 glyph = it->glyph_row->glyphs[it->area];
1773 end = glyph + move_by;
1776 if (glyph >= end)
1777 return;
1778 glyph->type = CHAR_GLYPH;
1779 glyph->pixel_width = 1;
1780 glyph->face_id = face_id;
1781 glyph->padding_p = 0;
1782 glyph->charpos = CHARPOS (it->position);
1783 glyph->object = it->object;
1784 if (it->bidi_p)
1786 glyph->resolved_level = it->bidi_it.resolved_level;
1787 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1788 glyph->bidi_type = it->bidi_it.type;
1790 else
1792 glyph->resolved_level = 0;
1793 glyph->bidi_type = UNKNOWN_BT;
1796 /* BIDI Note: we put the glyphs of characters left to right, even in
1797 the REVERSED_P case because we write to the terminal
1798 left-to-right. */
1799 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1801 if (i > 0)
1802 glyph[0] = glyph[-1];
1803 glyph->u.ch = str[i];
1804 ++it->glyph_row->used[it->area];
1805 ++glyph;
1809 /* Produce glyphs for a glyphless character for iterator IT.
1810 IT->glyphless_method specifies which method to use for displaying
1811 the character. See the description of enum
1812 glyphless_display_method in dispextern.h for the details.
1814 ACRONYM, if non-nil, is an acronym string for the character.
1816 The glyphs actually produced are of type CHAR_GLYPH. */
1818 static void
1819 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1821 int len, face_id = merge_glyphless_glyph_face (it);
1822 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1823 char const *str = " ";
1825 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1827 /* As there's no way to produce a thin space, we produce a space
1828 of canonical width. */
1829 len = 1;
1831 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1833 len = CHAR_WIDTH (it->c);
1834 if (len == 0)
1835 len = 1;
1836 else if (len > 4)
1837 len = 4;
1838 len = sprintf (buf, "[%.*s]", len, str);
1839 str = buf;
1841 else
1843 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1845 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1846 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1847 if (CONSP (acronym))
1848 acronym = XCDR (acronym);
1849 buf[0] = '[';
1850 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1851 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1852 buf[1 + len] = str[len];
1853 buf[1 + len] = ']';
1854 len += 2;
1856 else
1858 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1859 len = sprintf (buf,
1860 (it->c < 0x10000 ? "\\u%04X"
1861 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1862 : "\\x%06X"),
1863 it->c + 0u);
1865 str = buf;
1868 it->pixel_width = len;
1869 it->nglyphs = len;
1870 if (it->glyph_row)
1871 append_glyphless_glyph (it, face_id, str);
1875 /***********************************************************************
1876 Faces
1877 ***********************************************************************/
1879 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1880 one of the enumerators from enum no_color_bit, or a bit set built
1881 from them. Some display attributes may not be used together with
1882 color; the termcap capability `NC' specifies which ones. */
1884 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1885 (tty->TN_max_colors > 0 \
1886 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1887 : 1)
1889 /* Turn appearances of face FACE_ID on tty frame F on.
1890 FACE_ID is a realized face ID number, in the face cache. */
1892 static void
1893 turn_on_face (struct frame *f, int face_id)
1895 struct face *face = FACE_FROM_ID (f, face_id);
1896 unsigned long fg = face->foreground;
1897 unsigned long bg = face->background;
1898 struct tty_display_info *tty = FRAME_TTY (f);
1900 /* Use reverse video if the face specifies that.
1901 Do this first because TS_end_standout_mode may be the same
1902 as TS_exit_attribute_mode, which turns all appearances off. */
1903 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1904 && (inverse_video
1905 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1906 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1907 tty_toggle_highlight (tty);
1909 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1910 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1912 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1914 if (tty->TS_enter_italic_mode)
1915 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1916 else
1917 /* Italics mode is unavailable on many terminals. In that
1918 case, map slant to dimmed text; we want italic text to
1919 appear different and dimming is not otherwise used. */
1920 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1923 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1924 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1926 if (tty->TN_max_colors > 0)
1928 const char *ts;
1929 char *p;
1931 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1932 if (face_tty_specified_color (fg) && ts)
1934 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1935 OUTPUT (tty, p);
1936 xfree (p);
1939 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1940 if (face_tty_specified_color (bg) && ts)
1942 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1943 OUTPUT (tty, p);
1944 xfree (p);
1950 /* Turn off appearances of face FACE_ID on tty frame F. */
1952 static void
1953 turn_off_face (struct frame *f, int face_id)
1955 struct face *face = FACE_FROM_ID (f, face_id);
1956 struct tty_display_info *tty = FRAME_TTY (f);
1958 eassert (face != NULL);
1960 if (tty->TS_exit_attribute_mode)
1962 /* Capability "me" will turn off appearance modes double-bright,
1963 half-bright, reverse-video, standout, underline. It may or
1964 may not turn off alt-char-mode. */
1965 if (face->tty_bold_p
1966 || face->tty_italic_p
1967 || face->tty_reverse_p
1968 || face->tty_underline_p)
1970 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1971 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1972 tty->standout_mode = 0;
1975 else
1977 /* If we don't have "me" we can only have those appearances
1978 that have exit sequences defined. */
1979 if (face->tty_underline_p)
1980 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1983 /* Switch back to default colors. */
1984 if (tty->TN_max_colors > 0
1985 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1986 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1987 || (face->background != FACE_TTY_DEFAULT_COLOR
1988 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1989 OUTPUT1_IF (tty, tty->TS_orig_pair);
1993 /* Return true if the terminal on frame F supports all of the
1994 capabilities in CAPS simultaneously. */
1996 bool
1997 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
1999 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2000 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2001 return 0;
2003 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2004 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2005 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2006 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2009 /* We can do it! */
2010 return 1;
2013 /* Return non-zero if the terminal is capable to display colors. */
2015 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2016 0, 1, 0,
2017 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2019 TERMINAL can be a terminal object, a frame, or nil (meaning the
2020 selected frame's terminal). This function always returns nil if
2021 TERMINAL does not refer to a text terminal. */)
2022 (Lisp_Object terminal)
2024 struct terminal *t = decode_tty_terminal (terminal);
2026 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2029 /* Return the number of supported colors. */
2030 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2031 Stty_display_color_cells, 0, 1, 0,
2032 doc: /* Return the number of colors supported by the tty device TERMINAL.
2034 TERMINAL can be a terminal object, a frame, or nil (meaning the
2035 selected frame's terminal). This function always returns 0 if
2036 TERMINAL does not refer to a text terminal. */)
2037 (Lisp_Object terminal)
2039 struct terminal *t = decode_tty_terminal (terminal);
2041 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2044 #ifndef DOS_NT
2046 /* Declare here rather than in the function, as in the rest of Emacs,
2047 to work around an HPUX compiler bug (?). See
2048 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2049 static int default_max_colors;
2050 static int default_max_pairs;
2051 static int default_no_color_video;
2052 static char *default_orig_pair;
2053 static char *default_set_foreground;
2054 static char *default_set_background;
2056 /* Save or restore the default color-related capabilities of this
2057 terminal. */
2058 static void
2059 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2062 if (save)
2064 dupstring (&default_orig_pair, tty->TS_orig_pair);
2065 dupstring (&default_set_foreground, tty->TS_set_foreground);
2066 dupstring (&default_set_background, tty->TS_set_background);
2067 default_max_colors = tty->TN_max_colors;
2068 default_max_pairs = tty->TN_max_pairs;
2069 default_no_color_video = tty->TN_no_color_video;
2071 else
2073 tty->TS_orig_pair = default_orig_pair;
2074 tty->TS_set_foreground = default_set_foreground;
2075 tty->TS_set_background = default_set_background;
2076 tty->TN_max_colors = default_max_colors;
2077 tty->TN_max_pairs = default_max_pairs;
2078 tty->TN_no_color_video = default_no_color_video;
2082 /* Setup one of the standard tty color schemes according to MODE.
2083 MODE's value is generally the number of colors which we want to
2084 support; zero means set up for the default capabilities, the ones
2085 we saw at init_tty time; -1 means turn off color support. */
2086 static void
2087 tty_setup_colors (struct tty_display_info *tty, int mode)
2089 /* Canonicalize all negative values of MODE. */
2090 if (mode < -1)
2091 mode = -1;
2093 switch (mode)
2095 case -1: /* no colors at all */
2096 tty->TN_max_colors = 0;
2097 tty->TN_max_pairs = 0;
2098 tty->TN_no_color_video = 0;
2099 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2100 break;
2101 case 0: /* default colors, if any */
2102 default:
2103 tty_default_color_capabilities (tty, 0);
2104 break;
2105 case 8: /* 8 standard ANSI colors */
2106 tty->TS_orig_pair = "\033[0m";
2107 #ifdef TERMINFO
2108 tty->TS_set_foreground = "\033[3%p1%dm";
2109 tty->TS_set_background = "\033[4%p1%dm";
2110 #else
2111 tty->TS_set_foreground = "\033[3%dm";
2112 tty->TS_set_background = "\033[4%dm";
2113 #endif
2114 tty->TN_max_colors = 8;
2115 tty->TN_max_pairs = 64;
2116 tty->TN_no_color_video = 0;
2117 break;
2121 void
2122 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2124 Lisp_Object tem, val;
2125 Lisp_Object color_mode;
2126 int mode;
2127 Lisp_Object tty_color_mode_alist
2128 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2130 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2131 val = CONSP (tem) ? XCDR (tem) : Qnil;
2133 if (INTEGERP (val))
2134 color_mode = val;
2135 else if (SYMBOLP (tty_color_mode_alist))
2137 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2138 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2140 else
2141 color_mode = Qnil;
2143 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2145 if (mode != tty->previous_color_mode)
2147 tty->previous_color_mode = mode;
2148 tty_setup_colors (tty , mode);
2149 /* This recomputes all the faces given the new color definitions. */
2150 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2154 #endif /* !DOS_NT */
2156 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2157 doc: /* Return the type of the tty device that TERMINAL uses.
2158 Returns nil if TERMINAL is not on a tty device.
2160 TERMINAL can be a terminal object, a frame, or nil (meaning the
2161 selected frame's terminal). */)
2162 (Lisp_Object terminal)
2164 struct terminal *t = decode_tty_terminal (terminal);
2166 return (t && t->display_info.tty->type
2167 ? build_string (t->display_info.tty->type) : Qnil);
2170 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2171 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2173 TERMINAL can be a terminal object, a frame, or nil (meaning the
2174 selected frame's terminal). This function always returns nil if
2175 TERMINAL is not on a tty device. */)
2176 (Lisp_Object terminal)
2178 struct terminal *t = decode_tty_terminal (terminal);
2180 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2183 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2184 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2185 This is used to override the terminfo data, for certain terminals that
2186 do not really do underlining, but say that they do. This function has
2187 no effect if used on a non-tty terminal.
2189 TERMINAL can be a terminal object, a frame or nil (meaning the
2190 selected frame's terminal). This function always returns nil if
2191 TERMINAL does not refer to a text terminal. */)
2192 (Lisp_Object terminal)
2194 struct terminal *t = decode_live_terminal (terminal);
2196 if (t->type == output_termcap)
2197 t->display_info.tty->TS_enter_underline_mode = 0;
2198 return Qnil;
2201 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2202 doc: /* Return the topmost terminal frame on TERMINAL.
2203 TERMINAL can be a terminal object, a frame or nil (meaning the
2204 selected frame's terminal). This function returns nil if TERMINAL
2205 does not refer to a text terminal. Otherwise, it returns the
2206 top-most frame on the text terminal. */)
2207 (Lisp_Object terminal)
2209 struct terminal *t = decode_live_terminal (terminal);
2211 if (t->type == output_termcap)
2212 return t->display_info.tty->top_frame;
2213 return Qnil;
2218 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2219 doc: /* Suspend the terminal device TTY.
2221 The device is restored to its default state, and Emacs ceases all
2222 access to the tty device. Frames that use the device are not deleted,
2223 but input is not read from them and if they change, their display is
2224 not updated.
2226 TTY may be a terminal object, a frame, or nil for the terminal device
2227 of the currently selected frame.
2229 This function runs `suspend-tty-functions' after suspending the
2230 device. The functions are run with one arg, the id of the suspended
2231 terminal device.
2233 `suspend-tty' does nothing if it is called on a device that is already
2234 suspended.
2236 A suspended tty may be resumed by calling `resume-tty' on it. */)
2237 (Lisp_Object tty)
2239 struct terminal *t = decode_tty_terminal (tty);
2240 FILE *f;
2242 if (!t)
2243 error ("Attempt to suspend a non-text terminal device");
2245 f = t->display_info.tty->input;
2247 if (f)
2249 /* First run `suspend-tty-functions' and then clean up the tty
2250 state because `suspend-tty-functions' might need to change
2251 the tty state. */
2252 Lisp_Object term;
2253 XSETTERMINAL (term, t);
2254 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2256 reset_sys_modes (t->display_info.tty);
2257 delete_keyboard_wait_descriptor (fileno (f));
2259 #ifndef MSDOS
2260 fclose (f);
2261 if (f != t->display_info.tty->output)
2262 fclose (t->display_info.tty->output);
2263 #endif
2265 t->display_info.tty->input = 0;
2266 t->display_info.tty->output = 0;
2268 if (FRAMEP (t->display_info.tty->top_frame))
2269 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2273 /* Clear display hooks to prevent further output. */
2274 clear_tty_hooks (t);
2276 return Qnil;
2279 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2280 doc: /* Resume the previously suspended terminal device TTY.
2281 The terminal is opened and reinitialized. Frames that are on the
2282 suspended terminal are revived.
2284 It is an error to resume a terminal while another terminal is active
2285 on the same device.
2287 This function runs `resume-tty-functions' after resuming the terminal.
2288 The functions are run with one arg, the id of the resumed terminal
2289 device.
2291 `resume-tty' does nothing if it is called on a device that is not
2292 suspended.
2294 TTY may be a terminal object, a frame, or nil (meaning the selected
2295 frame's terminal). */)
2296 (Lisp_Object tty)
2298 struct terminal *t = decode_tty_terminal (tty);
2299 int fd;
2301 if (!t)
2302 error ("Attempt to resume a non-text terminal device");
2304 if (!t->display_info.tty->input)
2306 if (get_named_terminal (t->display_info.tty->name))
2307 error ("Cannot resume display while another display is active on the same device");
2309 #ifdef MSDOS
2310 t->display_info.tty->output = stdout;
2311 t->display_info.tty->input = stdin;
2312 #else /* !MSDOS */
2313 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2314 t->display_info.tty->input = t->display_info.tty->output
2315 = fd < 0 ? 0 : fdopen (fd, "w+");
2317 if (! t->display_info.tty->input)
2319 int open_errno = errno;
2320 emacs_close (fd);
2321 report_file_errno ("Cannot reopen tty device",
2322 build_string (t->display_info.tty->name),
2323 open_errno);
2326 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2327 dissociate_if_controlling_tty (fd);
2328 #endif
2330 add_keyboard_wait_descriptor (fd);
2332 if (FRAMEP (t->display_info.tty->top_frame))
2334 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2335 int width, height;
2336 int old_height = FRAME_COLS (f);
2337 int old_width = FRAME_TOTAL_LINES (f);
2339 /* Check if terminal/window size has changed while the frame
2340 was suspended. */
2341 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2342 if (width != old_width || height != old_height)
2343 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2344 0, 0, 0, 0);
2345 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2348 set_tty_hooks (t);
2349 init_sys_modes (t->display_info.tty);
2351 /* Run `resume-tty-functions'. */
2352 Lisp_Object term;
2353 XSETTERMINAL (term, t);
2354 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2357 set_tty_hooks (t);
2359 return Qnil;
2363 /***********************************************************************
2364 Mouse
2365 ***********************************************************************/
2367 #ifdef HAVE_GPM
2369 #ifndef HAVE_WINDOW_SYSTEM
2370 void
2371 term_mouse_moveto (int x, int y)
2373 /* TODO: how to set mouse position?
2374 const char *name;
2375 int fd;
2376 name = (const char *) ttyname (0);
2377 fd = emacs_open (name, O_WRONLY, 0);
2378 SOME_FUNCTION (x, y, fd);
2379 emacs_close (fd);
2380 last_mouse_x = x;
2381 last_mouse_y = y; */
2383 #endif /* HAVE_WINDOW_SYSTEM */
2385 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2386 void
2387 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2388 int start_hpos, int end_hpos,
2389 enum draw_glyphs_face draw)
2391 int nglyphs = end_hpos - start_hpos;
2392 struct frame *f = XFRAME (WINDOW_FRAME (w));
2393 struct tty_display_info *tty = FRAME_TTY (f);
2394 int face_id = tty->mouse_highlight.mouse_face_face_id;
2395 int save_x, save_y, pos_x, pos_y;
2397 if (end_hpos >= row->used[TEXT_AREA])
2398 nglyphs = row->used[TEXT_AREA] - start_hpos;
2400 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2401 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2403 /* Save current cursor co-ordinates. */
2404 save_y = curY (tty);
2405 save_x = curX (tty);
2406 cursor_to (f, pos_y, pos_x);
2408 if (draw == DRAW_MOUSE_FACE)
2409 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2410 nglyphs, face_id);
2411 else if (draw == DRAW_NORMAL_TEXT)
2412 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2414 cursor_to (f, save_y, save_x);
2417 static bool
2418 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2420 /* Has the mouse moved off the glyph it was on at the last sighting? */
2421 if (event->x != last_mouse_x || event->y != last_mouse_y)
2423 frame->mouse_moved = 1;
2424 note_mouse_highlight (frame, event->x, event->y);
2425 /* Remember which glyph we're now on. */
2426 last_mouse_x = event->x;
2427 last_mouse_y = event->y;
2428 return 1;
2430 return 0;
2433 /* Return the Time that corresponds to T. Wrap around on overflow. */
2434 static Time
2435 timeval_to_Time (struct timeval const *t)
2437 Time s_1000, ms;
2439 s_1000 = t->tv_sec;
2440 s_1000 *= 1000;
2441 ms = t->tv_usec / 1000;
2442 return s_1000 + ms;
2445 /* Return the current position of the mouse.
2447 Set *f to the frame the mouse is in, or zero if the mouse is in no
2448 Emacs frame. If it is set to zero, all the other arguments are
2449 garbage.
2451 Set *bar_window to Qnil, and *x and *y to the column and
2452 row of the character cell the mouse is over.
2454 Set *timeptr to the time the mouse was at the returned position.
2456 This clears mouse_moved until the next motion
2457 event arrives. */
2458 static void
2459 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2460 enum scroll_bar_part *part, Lisp_Object *x,
2461 Lisp_Object *y, Time *timeptr)
2463 struct timeval now;
2465 *fp = SELECTED_FRAME ();
2466 (*fp)->mouse_moved = 0;
2468 *bar_window = Qnil;
2469 *part = scroll_bar_above_handle;
2471 XSETINT (*x, last_mouse_x);
2472 XSETINT (*y, last_mouse_y);
2473 gettimeofday(&now, 0);
2474 *timeptr = timeval_to_Time (&now);
2477 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2479 If the event is a button press, then note that we have grabbed
2480 the mouse. */
2482 static Lisp_Object
2483 term_mouse_click (struct input_event *result, Gpm_Event *event,
2484 struct frame *f)
2486 struct timeval now;
2487 int i, j;
2489 result->kind = GPM_CLICK_EVENT;
2490 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2492 if (event->buttons & j) {
2493 result->code = i; /* button number */
2494 break;
2497 gettimeofday(&now, 0);
2498 result->timestamp = timeval_to_Time (&now);
2500 if (event->type & GPM_UP)
2501 result->modifiers = up_modifier;
2502 else if (event->type & GPM_DOWN)
2503 result->modifiers = down_modifier;
2504 else
2505 result->modifiers = 0;
2507 if (event->type & GPM_SINGLE)
2508 result->modifiers |= click_modifier;
2510 if (event->type & GPM_DOUBLE)
2511 result->modifiers |= double_modifier;
2513 if (event->type & GPM_TRIPLE)
2514 result->modifiers |= triple_modifier;
2516 if (event->type & GPM_DRAG)
2517 result->modifiers |= drag_modifier;
2519 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2521 /* 1 << KG_SHIFT */
2522 if (event->modifiers & (1 << 0))
2523 result->modifiers |= shift_modifier;
2525 /* 1 << KG_CTRL */
2526 if (event->modifiers & (1 << 2))
2527 result->modifiers |= ctrl_modifier;
2529 /* 1 << KG_ALT || KG_ALTGR */
2530 if (event->modifiers & (1 << 3)
2531 || event->modifiers & (1 << 1))
2532 result->modifiers |= meta_modifier;
2535 XSETINT (result->x, event->x);
2536 XSETINT (result->y, event->y);
2537 XSETFRAME (result->frame_or_window, f);
2538 result->arg = Qnil;
2539 return Qnil;
2543 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2545 struct frame *f = XFRAME (tty->top_frame);
2546 struct input_event ie;
2547 bool do_help = 0;
2548 int count = 0;
2550 EVENT_INIT (ie);
2551 ie.kind = NO_EVENT;
2552 ie.arg = Qnil;
2554 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2555 previous_help_echo_string = help_echo_string;
2556 help_echo_string = Qnil;
2558 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2560 if (!term_mouse_movement (f, event))
2561 help_echo_string = previous_help_echo_string;
2563 /* If the contents of the global variable help_echo_string
2564 has changed, generate a HELP_EVENT. */
2565 if (!NILP (help_echo_string)
2566 || !NILP (previous_help_echo_string))
2567 do_help = 1;
2569 goto done;
2571 else {
2572 f->mouse_moved = 0;
2573 term_mouse_click (&ie, event, f);
2576 done:
2577 if (ie.kind != NO_EVENT)
2579 kbd_buffer_store_event_hold (&ie, hold_quit);
2580 count++;
2583 if (do_help
2584 && !(hold_quit && hold_quit->kind != NO_EVENT))
2586 Lisp_Object frame;
2588 if (f)
2589 XSETFRAME (frame, f);
2590 else
2591 frame = Qnil;
2593 gen_help_event (help_echo_string, frame, help_echo_window,
2594 help_echo_object, help_echo_pos);
2595 count++;
2598 return count;
2601 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2602 0, 0, 0,
2603 doc: /* Open a connection to Gpm.
2604 Gpm-mouse can only be activated for one tty at a time. */)
2605 (void)
2607 struct frame *f = SELECTED_FRAME ();
2608 struct tty_display_info *tty
2609 = ((f)->output_method == output_termcap
2610 ? (f)->terminal->display_info.tty : NULL);
2611 Gpm_Connect connection;
2613 if (!tty)
2614 error ("Gpm-mouse only works in the GNU/Linux console");
2615 if (gpm_tty == tty)
2616 return Qnil; /* Already activated, nothing to do. */
2617 if (gpm_tty)
2618 error ("Gpm-mouse can only be activated for one tty at a time");
2620 connection.eventMask = ~0;
2621 connection.defaultMask = ~GPM_HARD;
2622 connection.maxMod = ~0;
2623 connection.minMod = 0;
2624 gpm_zerobased = 1;
2626 if (Gpm_Open (&connection, 0) < 0)
2627 error ("Gpm-mouse failed to connect to the gpm daemon");
2628 else
2630 gpm_tty = tty;
2631 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2632 to generate SIGIOs. Apparently we need to call reset_sys_modes
2633 before calling init_sys_modes. */
2634 reset_sys_modes (tty);
2635 init_sys_modes (tty);
2636 add_gpm_wait_descriptor (gpm_fd);
2637 return Qnil;
2641 void
2642 close_gpm (int fd)
2644 if (fd >= 0)
2645 delete_gpm_wait_descriptor (fd);
2646 while (Gpm_Close()); /* close all the stack */
2647 gpm_tty = NULL;
2650 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2651 0, 0, 0,
2652 doc: /* Close a connection to Gpm. */)
2653 (void)
2655 struct frame *f = SELECTED_FRAME ();
2656 struct tty_display_info *tty
2657 = ((f)->output_method == output_termcap
2658 ? (f)->terminal->display_info.tty : NULL);
2660 if (!tty || gpm_tty != tty)
2661 return Qnil; /* Not activated on this terminal, nothing to do. */
2663 close_gpm (gpm_fd);
2664 return Qnil;
2666 #endif /* HAVE_GPM */
2669 /***********************************************************************
2670 Menus
2671 ***********************************************************************/
2673 #if !defined (MSDOS)
2675 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2677 However, unlike on MSDOS, where the menu text is drawn directly to
2678 the display video memory, on a TTY we use display_string (see
2679 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2680 the menu items into the frame's 'desired_matrix' glyph matrix, and
2681 then call update_frame_with_menu to deliver the results to the
2682 glass. The previous contents of the screen, in the form of the
2683 current_matrix, is stashed away, and used to restore screen
2684 contents when the menu selection changes or when the final
2685 selection is made and the menu should be popped down.
2687 The idea of this implementation was suggested by Gerd Moellmann. */
2689 #define TTYM_FAILURE -1
2690 #define TTYM_SUCCESS 1
2691 #define TTYM_NO_SELECT 2
2692 #define TTYM_IA_SELECT 3
2693 #define TTYM_NEXT 4
2694 #define TTYM_PREV 5
2696 /* These hold text of the current and the previous menu help messages. */
2697 static const char *menu_help_message, *prev_menu_help_message;
2698 /* Pane number and item number of the menu item which generated the
2699 last menu help message. */
2700 static int menu_help_paneno, menu_help_itemno;
2702 typedef struct tty_menu_struct
2704 int count;
2705 char **text;
2706 struct tty_menu_struct **submenu;
2707 int *panenumber; /* Also used as enabled flag. */
2708 ptrdiff_t allocated;
2709 int panecount;
2710 int width;
2711 const char **help_text;
2712 } tty_menu;
2714 /* Create a brand new menu structure. */
2716 static tty_menu *
2717 tty_menu_create (void)
2719 return xzalloc (sizeof *tty_menu_create ());
2722 /* Allocate some (more) memory for MENU ensuring that there is room for one
2723 more item. */
2725 static void
2726 tty_menu_make_room (tty_menu *menu)
2728 if (menu->allocated == menu->count)
2730 ptrdiff_t allocated = menu->allocated;
2731 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2732 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2733 menu->submenu = xrealloc (menu->submenu,
2734 allocated * sizeof *menu->submenu);
2735 menu->panenumber = xrealloc (menu->panenumber,
2736 allocated * sizeof *menu->panenumber);
2737 menu->help_text = xrealloc (menu->help_text,
2738 allocated * sizeof *menu->help_text);
2739 menu->allocated = allocated;
2743 /* Search the given menu structure for a given pane number. */
2745 static tty_menu *
2746 tty_menu_search_pane (tty_menu *menu, int pane)
2748 int i;
2749 tty_menu *try;
2751 for (i = 0; i < menu->count; i++)
2752 if (menu->submenu[i])
2754 if (pane == menu->panenumber[i])
2755 return menu->submenu[i];
2756 try = tty_menu_search_pane (menu->submenu[i], pane);
2757 if (try)
2758 return try;
2760 return (tty_menu *) 0;
2763 /* Determine how much screen space a given menu needs. */
2765 static void
2766 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2768 int i, h2, w2, maxsubwidth, maxheight;
2770 maxsubwidth = menu->width;
2771 maxheight = menu->count;
2772 for (i = 0; i < menu->count; i++)
2774 if (menu->submenu[i])
2776 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2777 if (w2 > maxsubwidth) maxsubwidth = w2;
2778 if (i + h2 > maxheight) maxheight = i + h2;
2781 *width = maxsubwidth;
2782 *height = maxheight;
2785 static void
2786 mouse_get_xy (int *x, int *y)
2788 struct frame *sf = SELECTED_FRAME ();
2789 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2790 enum scroll_bar_part part_dummy;
2791 Time time_dummy;
2793 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2794 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2795 &lisp_dummy, &part_dummy,
2796 &lmx, &lmy,
2797 &time_dummy);
2798 if (!NILP (lmx))
2800 *x = XINT (lmx);
2801 *y = XINT (lmy);
2805 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2806 (zero-based). */
2808 static void
2809 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2810 int mx, int my, int first_item, bool disp_help)
2812 int i, face, width, enabled, mousehere, row, col;
2813 struct frame *sf = SELECTED_FRAME ();
2814 struct tty_display_info *tty = FRAME_TTY (sf);
2815 /* Don't try to display more menu items than the console can display
2816 using the available screen lines. Exclude the echo area line, as
2817 it will be overwritten by the help-echo anyway. */
2818 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2820 menu_help_message = NULL;
2822 width = menu->width;
2823 col = cursorX (tty);
2824 row = cursorY (tty);
2825 for (i = 0; i < max_items; i++)
2827 int max_width = width + 2; /* +2 for padding blanks on each side */
2828 int j = i + first_item;
2830 if (menu->submenu[j])
2831 max_width += 2; /* for displaying " >" after the item */
2832 enabled
2833 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2834 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2835 face = faces[enabled + mousehere * 2];
2836 /* Display the menu help string for the i-th menu item even if
2837 the menu item is currently disabled. That's what the GUI
2838 code does. */
2839 if (disp_help && enabled + mousehere * 2 >= 2)
2841 menu_help_message = menu->help_text[j];
2842 menu_help_paneno = pn - 1;
2843 menu_help_itemno = j;
2845 /* Take note of the coordinates of the active menu item, to
2846 display the cursor there. */
2847 if (mousehere)
2849 row = y + i;
2850 col = x;
2852 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2853 menu->submenu[j] != NULL);
2855 update_frame_with_menu (sf, row, col);
2858 /* --------------------------- X Menu emulation ---------------------- */
2860 /* Create a new pane and place it on the outer-most level. */
2862 static int
2863 tty_menu_add_pane (tty_menu *menu, const char *txt)
2865 int len;
2867 tty_menu_make_room (menu);
2868 menu->submenu[menu->count] = tty_menu_create ();
2869 menu->text[menu->count] = (char *)txt;
2870 menu->panenumber[menu->count] = ++menu->panecount;
2871 menu->help_text[menu->count] = NULL;
2872 menu->count++;
2874 /* Update the menu width, if necessary. */
2875 len = menu_item_width ((const unsigned char *) txt);
2876 if (len > menu->width)
2877 menu->width = len;
2879 return menu->panecount;
2882 /* Create a new item in a menu pane. */
2884 static bool
2885 tty_menu_add_selection (tty_menu *menu, int pane,
2886 char *txt, bool enable, char const *help_text)
2888 int len;
2890 if (pane)
2892 menu = tty_menu_search_pane (menu, pane);
2893 if (! menu)
2894 return 0;
2896 tty_menu_make_room (menu);
2897 menu->submenu[menu->count] = (tty_menu *) 0;
2898 menu->text[menu->count] = txt;
2899 menu->panenumber[menu->count] = enable;
2900 menu->help_text[menu->count] = help_text;
2901 menu->count++;
2903 /* Update the menu width, if necessary. */
2904 len = menu_item_width ((const unsigned char *) txt);
2905 if (len > menu->width)
2906 menu->width = len;
2908 return 1;
2911 /* Decide where the menu would be placed if requested at (X,Y). */
2913 static void
2914 tty_menu_locate (tty_menu *menu, int x, int y,
2915 int *ulx, int *uly, int *width, int *height)
2917 tty_menu_calc_size (menu, width, height);
2918 *ulx = x + 1;
2919 *uly = y;
2920 *width += 2;
2923 struct tty_menu_state
2925 struct glyph_matrix *screen_behind;
2926 tty_menu *menu;
2927 int pane;
2928 int x, y;
2931 /* Save away the contents of frame F's current frame matrix, and
2932 enable all its rows. Value is a glyph matrix holding the contents
2933 of F's current frame matrix with all its glyph rows enabled. */
2935 static struct glyph_matrix *
2936 save_and_enable_current_matrix (struct frame *f)
2938 int i;
2939 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2940 saved->nrows = f->current_matrix->nrows;
2941 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2943 for (i = 0; i < saved->nrows; ++i)
2945 struct glyph_row *from = f->current_matrix->rows + i;
2946 struct glyph_row *to = saved->rows + i;
2947 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2949 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2950 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2951 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2952 /* Make sure every row is enabled, or else update_frame will not
2953 redraw them. (Rows that are identical to what is already on
2954 screen will not be redrawn anyway.) */
2955 to->enabled_p = true;
2956 to->hash = from->hash;
2959 return saved;
2962 /* Restore the contents of frame F's desired frame matrix from SAVED,
2963 and free memory associated with SAVED. */
2965 static void
2966 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2968 int i;
2970 for (i = 0; i < saved->nrows; ++i)
2972 struct glyph_row *from = saved->rows + i;
2973 struct glyph_row *to = f->desired_matrix->rows + i;
2974 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2976 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2977 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2978 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2979 to->enabled_p = from->enabled_p;
2980 to->hash = from->hash;
2984 static void
2985 free_saved_screen (struct glyph_matrix *saved)
2987 int i;
2989 if (!saved)
2990 return; /* Already freed! */
2992 for (i = 0; i < saved->nrows; ++i)
2994 struct glyph_row *from = saved->rows + i;
2996 xfree (from->glyphs[TEXT_AREA]);
2999 xfree (saved->rows);
3000 xfree (saved);
3003 /* Update the display of frame F from its saved contents. */
3004 static void
3005 screen_update (struct frame *f, struct glyph_matrix *mtx)
3007 restore_desired_matrix (f, mtx);
3008 update_frame_with_menu (f, -1, -1);
3011 typedef enum {
3012 MI_QUIT_MENU = -1,
3013 MI_CONTINUE = 0,
3014 MI_ITEM_SELECTED = 1,
3015 MI_NEXT_ITEM = 2,
3016 MI_PREV_ITEM = 3,
3017 MI_SCROLL_FORWARD = 4,
3018 MI_SCROLL_BACK = 5
3019 } mi_result;
3021 /* Read user input and return X and Y coordinates where that input
3022 puts us. We only consider mouse movement and click events, and
3023 keyboard movement commands; the rest are ignored. */
3024 static mi_result
3025 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3026 bool *first_time)
3028 if (*first_time)
3030 *first_time = false;
3031 sf->mouse_moved = 1;
3033 else
3035 Lisp_Object cmd;
3036 bool usable_input = 1;
3037 mi_result st = MI_CONTINUE;
3038 struct tty_display_info *tty = FRAME_TTY (sf);
3039 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3041 /* Signal the keyboard reading routines we are displaying a menu
3042 on this terminal. */
3043 tty->showing_menu = 1;
3044 /* We want mouse movements be reported by read_menu_command. */
3045 do_mouse_tracking = Qt;
3046 do {
3047 cmd = read_menu_command ();
3048 } while (NILP (cmd));
3049 tty->showing_menu = 0;
3050 do_mouse_tracking = saved_mouse_tracking;
3052 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3053 /* If some input switched frames under our feet, exit the
3054 menu, since the menu faces are no longer valid, and the
3055 menu is no longer relevant anyway. */
3056 || sf != SELECTED_FRAME ())
3057 return MI_QUIT_MENU;
3058 if (EQ (cmd, Qtty_menu_mouse_movement))
3059 mouse_get_xy (x, y);
3060 else if (EQ (cmd, Qtty_menu_next_menu))
3062 usable_input = 0;
3063 st = MI_NEXT_ITEM;
3065 else if (EQ (cmd, Qtty_menu_prev_menu))
3067 usable_input = 0;
3068 st = MI_PREV_ITEM;
3070 else if (EQ (cmd, Qtty_menu_next_item))
3072 if (*y < max_y)
3073 *y += 1;
3074 else
3075 st = MI_SCROLL_FORWARD;
3077 else if (EQ (cmd, Qtty_menu_prev_item))
3079 if (*y > min_y)
3080 *y -= 1;
3081 else
3082 st = MI_SCROLL_BACK;
3084 else if (EQ (cmd, Qtty_menu_select))
3085 st = MI_ITEM_SELECTED;
3086 else if (!EQ (cmd, Qtty_menu_ignore))
3087 usable_input = 0;
3088 if (usable_input)
3089 sf->mouse_moved = 1;
3090 return st;
3092 return MI_CONTINUE;
3095 /* Display menu, wait for user's response, and return that response. */
3096 static int
3097 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3098 int x0, int y0, char **txt,
3099 void (*help_callback)(char const *, int, int),
3100 bool kbd_navigation)
3102 struct tty_menu_state *state;
3103 int statecount, x, y, i;
3104 bool leave, onepane;
3105 int result IF_LINT (= 0);
3106 int title_faces[4]; /* Face to display the menu title. */
3107 int faces[4], buffers_num_deleted = 0;
3108 struct frame *sf = SELECTED_FRAME ();
3109 struct tty_display_info *tty = FRAME_TTY (sf);
3110 bool first_time;
3111 Lisp_Object selectface;
3112 int first_item = 0;
3113 int col, row;
3114 Lisp_Object prev_inhibit_redisplay = Vinhibit_redisplay;
3115 USE_SAFE_ALLOCA;
3117 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3118 around the display. */
3119 if (x0 <= 0)
3120 x0 = 1;
3121 if (y0 <= 0)
3122 y0 = 1;
3124 SAFE_NALLOCA (state, 1, menu->panecount);
3125 memset (state, 0, sizeof (*state));
3126 faces[0]
3127 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3128 DEFAULT_FACE_ID, 1);
3129 faces[1]
3130 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3131 DEFAULT_FACE_ID, 1);
3132 selectface = intern ("tty-menu-selected-face");
3133 faces[2] = lookup_derived_face (sf, selectface,
3134 faces[0], 1);
3135 faces[3] = lookup_derived_face (sf, selectface,
3136 faces[1], 1);
3138 /* Make sure the menu title is always displayed with
3139 `tty-menu-selected-face', no matter where the mouse pointer is. */
3140 for (i = 0; i < 4; i++)
3141 title_faces[i] = faces[3];
3143 statecount = 1;
3145 /* Don't let the title for the "Buffers" popup menu include a
3146 digit (which is ugly).
3148 This is a terrible kludge, but I think the "Buffers" case is
3149 the only one where the title includes a number, so it doesn't
3150 seem to be necessary to make this more general. */
3151 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3153 menu->text[0][7] = '\0';
3154 buffers_num_deleted = 1;
3157 /* Inhibit redisplay for as long as the menu is active, to avoid
3158 messing the screen if some timer calls sit-for or a similar
3159 function. */
3160 Vinhibit_redisplay = Qt;
3162 /* Force update of the current frame, so that the desired and the
3163 current matrices are identical. */
3164 update_frame_with_menu (sf, -1, -1);
3165 state[0].menu = menu;
3166 state[0].screen_behind = save_and_enable_current_matrix (sf);
3168 /* Display the menu title. We subtract 1 from x0 and y0 because we
3169 want to interpret them as zero-based column and row coordinates,
3170 and also because we want the first item of the menu, not its
3171 title, to appear at x0,y0. */
3172 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3174 /* Turn off the cursor. Otherwise it shows through the menu
3175 panes, which is ugly. */
3176 col = cursorX (tty);
3177 row = cursorY (tty);
3178 tty_hide_cursor (tty);
3180 if (buffers_num_deleted)
3181 menu->text[0][7] = ' ';
3182 onepane = menu->count == 1 && menu->submenu[0];
3183 if (onepane)
3185 menu->width = menu->submenu[0]->width;
3186 state[0].menu = menu->submenu[0];
3188 else
3190 state[0].menu = menu;
3192 state[0].x = x0 - 1;
3193 state[0].y = y0;
3194 state[0].pane = onepane;
3196 x = state[0].x;
3197 y = state[0].y;
3198 first_time = true;
3200 leave = 0;
3201 while (!leave)
3203 mi_result input_status;
3204 int min_y = state[0].y;
3205 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3207 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3208 if (input_status)
3210 leave = 1;
3211 switch (input_status)
3213 case MI_QUIT_MENU:
3214 /* Remove the last help-echo, so that it doesn't
3215 re-appear after "Quit". */
3216 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3217 result = TTYM_NO_SELECT;
3218 break;
3219 case MI_NEXT_ITEM:
3220 if (kbd_navigation)
3221 result = TTYM_NEXT;
3222 else
3223 leave = 0;
3224 break;
3225 case MI_PREV_ITEM:
3226 if (kbd_navigation)
3227 result = TTYM_PREV;
3228 else
3229 leave = 0;
3230 break;
3231 case MI_SCROLL_FORWARD:
3232 if (y - min_y == state[0].menu->count - 1 - first_item)
3234 y = min_y;
3235 first_item = 0;
3237 else
3238 first_item++;
3239 leave = 0;
3240 break;
3241 case MI_SCROLL_BACK:
3242 if (first_item == 0)
3244 y = max_y;
3245 first_item = state[0].menu->count - 1 - (y - min_y);
3247 else
3248 first_item--;
3249 leave = 0;
3250 break;
3251 default:
3252 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3253 break;
3256 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3258 sf->mouse_moved = 0;
3259 result = TTYM_IA_SELECT;
3260 for (i = 0; i < statecount; i++)
3261 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3263 int dy = y - state[i].y + first_item;
3264 if (0 <= dy && dy < state[i].menu->count)
3266 if (!state[i].menu->submenu[dy])
3268 if (state[i].menu->panenumber[dy])
3269 result = TTYM_SUCCESS;
3270 else
3271 result = TTYM_IA_SELECT;
3273 *pane = state[i].pane - 1;
3274 *selidx = dy;
3275 /* We hit some part of a menu, so drop extra menus that
3276 have been opened. That does not include an open and
3277 active submenu. */
3278 if (i != statecount - 2
3279 || state[i].menu->submenu[dy] != state[i + 1].menu)
3280 while (i != statecount - 1)
3282 statecount--;
3283 screen_update (sf, state[statecount].screen_behind);
3284 state[statecount].screen_behind = NULL;
3286 if (i == statecount - 1 && state[i].menu->submenu[dy])
3288 tty_menu_display (state[i].menu,
3289 state[i].x,
3290 state[i].y,
3291 state[i].pane,
3292 faces, x, y, first_item, 1);
3293 state[statecount].menu = state[i].menu->submenu[dy];
3294 state[statecount].pane = state[i].menu->panenumber[dy];
3295 state[statecount].screen_behind
3296 = save_and_enable_current_matrix (sf);
3297 state[statecount].x
3298 = state[i].x + state[i].menu->width + 2;
3299 state[statecount].y = y;
3300 statecount++;
3304 tty_menu_display (state[statecount - 1].menu,
3305 state[statecount - 1].x,
3306 state[statecount - 1].y,
3307 state[statecount - 1].pane,
3308 faces, x, y, first_item, 1);
3309 /* The call to display help-echo below will move the cursor,
3310 so remember its current position as computed by
3311 tty_menu_display. */
3312 col = cursorX (tty);
3313 row = cursorY (tty);
3316 /* Display the help-echo message for the currently-selected menu
3317 item. */
3318 if ((menu_help_message || prev_menu_help_message)
3319 && menu_help_message != prev_menu_help_message)
3321 help_callback (menu_help_message,
3322 menu_help_paneno, menu_help_itemno);
3323 /* Move the cursor to the beginning of the current menu
3324 item, so that screen readers and other accessibility aids
3325 know where the active region is. */
3326 cursor_to (sf, row, col);
3327 prev_menu_help_message = menu_help_message;
3329 /* Both tty_menu_display and help_callback invoke update_end,
3330 which calls tty_show_cursor. Re-hide it, so it doesn't show
3331 through the menus. */
3332 tty_hide_cursor (tty);
3333 fflush (tty->output);
3336 sf->mouse_moved = 0;
3337 screen_update (sf, state[0].screen_behind);
3338 while (statecount--)
3339 free_saved_screen (state[statecount].screen_behind);
3340 tty_show_cursor (tty); /* Turn cursor back on. */
3341 fflush (tty->output);
3343 /* Clean up any mouse events that are waiting inside Emacs event queue.
3344 These events are likely to be generated before the menu was even
3345 displayed, probably because the user pressed and released the button
3346 (which invoked the menu) too quickly. If we don't remove these events,
3347 Emacs will process them after we return and surprise the user. */
3348 discard_mouse_events ();
3349 if (!kbd_buffer_events_waiting ())
3350 clear_input_pending ();
3351 SAFE_FREE ();
3352 Vinhibit_redisplay = prev_inhibit_redisplay;
3353 return result;
3356 /* Dispose of a menu. */
3358 static void
3359 tty_menu_destroy (tty_menu *menu)
3361 int i;
3362 if (menu->allocated)
3364 for (i = 0; i < menu->count; i++)
3365 if (menu->submenu[i])
3366 tty_menu_destroy (menu->submenu[i]);
3367 xfree (menu->text);
3368 xfree (menu->submenu);
3369 xfree (menu->panenumber);
3370 xfree (menu->help_text);
3372 xfree (menu);
3373 menu_help_message = prev_menu_help_message = NULL;
3376 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3378 PANE is the pane number, and ITEM is the menu item number in
3379 the menu (currently not used). */
3381 static void
3382 tty_menu_help_callback (char const *help_string, int pane, int item)
3384 Lisp_Object *first_item;
3385 Lisp_Object pane_name;
3386 Lisp_Object menu_object;
3388 first_item = XVECTOR (menu_items)->contents;
3389 if (EQ (first_item[0], Qt))
3390 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3391 else if (EQ (first_item[0], Qquote))
3392 /* This shouldn't happen, see xmenu_show. */
3393 pane_name = empty_unibyte_string;
3394 else
3395 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3397 /* (menu-item MENU-NAME PANE-NUMBER) */
3398 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3399 show_help_echo (help_string ? build_string (help_string) : Qnil,
3400 Qnil, menu_object, make_number (item));
3403 static void
3404 tty_pop_down_menu (Lisp_Object arg)
3406 tty_menu *menu = XSAVE_POINTER (arg, 0);
3408 block_input ();
3409 tty_menu_destroy (menu);
3410 unblock_input ();
3413 /* Return the zero-based index of the last menu-bar item on frame F. */
3414 static int
3415 tty_menu_last_menubar_item (struct frame *f)
3417 int i = 0;
3419 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3420 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3422 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3424 while (i < ASIZE (items))
3426 Lisp_Object str;
3428 str = AREF (items, i + 1);
3429 if (NILP (str))
3430 break;
3431 i += 4;
3433 i -= 4; /* Went one too far! */
3435 return i;
3438 /* Find in frame F's menu bar the menu item that is next or previous
3439 to the item at X/Y, and return that item's position in X/Y. WHICH
3440 says which one--next or previous--item to look for. X and Y are
3441 measured in character cells. This should only be called on TTY
3442 frames. */
3443 static void
3444 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3446 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3447 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3449 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3450 int last_i = tty_menu_last_menubar_item (f);
3451 int i, prev_x;
3453 /* This loop assumes a single menu-bar line, and will fail to
3454 find an item if it is not in the first line. Note that
3455 make_lispy_event in keyboard.c makes the same assumption. */
3456 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3458 Lisp_Object pos, str;
3459 int ix;
3461 str = AREF (items, i + 1);
3462 pos = AREF (items, i + 3);
3463 if (NILP (str))
3464 return;
3465 ix = XINT (pos);
3466 if (ix <= *x
3467 /* We use <= so the blank between 2 items on a TTY is
3468 considered part of the previous item. */
3469 && *x <= ix + menu_item_width (SDATA (str)))
3471 /* Found current item. Now compute the X coordinate of
3472 the previous or next item. */
3473 if (which == TTYM_NEXT)
3475 if (i < last_i)
3476 *x = XINT (AREF (items, i + 4 + 3));
3477 else
3478 *x = 0; /* Wrap around to the first item. */
3480 else if (prev_x < 0)
3482 /* Wrap around to the last item. */
3483 *x = XINT (AREF (items, last_i + 3));
3485 else
3486 *x = prev_x;
3487 return;
3489 prev_x = ix;
3494 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3495 Lisp_Object
3496 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3497 Lisp_Object title, const char **error_name)
3499 tty_menu *menu;
3500 int pane, selidx, lpane, status;
3501 Lisp_Object entry, pane_prefix;
3502 char *datap;
3503 int ulx, uly, width, height;
3504 int item_x, item_y;
3505 int dispwidth, dispheight;
3506 int i, j, lines, maxlines;
3507 int maxwidth;
3508 ptrdiff_t specpdl_count;
3510 eassert (FRAME_TERMCAP_P (f));
3512 *error_name = 0;
3513 if (menu_items_n_panes == 0)
3514 return Qnil;
3516 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3518 *error_name = "Empty menu";
3519 return Qnil;
3522 /* Make the menu on that window. */
3523 menu = tty_menu_create ();
3525 /* Don't GC while we prepare and show the menu, because we give the
3526 menu functions pointers to the contents of strings. */
3527 specpdl_count = inhibit_garbage_collection ();
3529 /* Avoid crashes if, e.g., another client will connect while we
3530 are in a menu. */
3531 temporarily_switch_to_single_kboard (f);
3533 /* Adjust coordinates to be root-window-relative. */
3534 item_x = x += f->left_pos;
3535 item_y = y += f->top_pos;
3537 /* Create all the necessary panes and their items. */
3538 USE_SAFE_ALLOCA;
3539 maxwidth = maxlines = lines = i = 0;
3540 lpane = TTYM_FAILURE;
3541 while (i < menu_items_used)
3543 if (EQ (AREF (menu_items, i), Qt))
3545 /* Create a new pane. */
3546 Lisp_Object pane_name, prefix;
3547 const char *pane_string;
3549 maxlines = max (maxlines, lines);
3550 lines = 0;
3551 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3552 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3553 pane_string = (NILP (pane_name)
3554 ? "" : SSDATA (pane_name));
3555 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3556 pane_string++;
3558 lpane = tty_menu_add_pane (menu, pane_string);
3559 if (lpane == TTYM_FAILURE)
3561 tty_menu_destroy (menu);
3562 *error_name = "Can't create pane";
3563 entry = Qnil;
3564 goto tty_menu_end;
3566 i += MENU_ITEMS_PANE_LENGTH;
3568 /* Find the width of the widest item in this pane. */
3569 j = i;
3570 while (j < menu_items_used)
3572 Lisp_Object item;
3573 item = AREF (menu_items, j);
3574 if (EQ (item, Qt))
3575 break;
3576 if (NILP (item))
3578 j++;
3579 continue;
3581 width = SBYTES (item);
3582 if (width > maxwidth)
3583 maxwidth = width;
3585 j += MENU_ITEMS_ITEM_LENGTH;
3588 /* Ignore a nil in the item list.
3589 It's meaningful only for dialog boxes. */
3590 else if (EQ (AREF (menu_items, i), Qquote))
3591 i += 1;
3592 else
3594 /* Create a new item within current pane. */
3595 Lisp_Object item_name, enable, descrip, help;
3596 char *item_data;
3597 char const *help_string;
3599 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3600 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3601 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3602 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3603 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3605 if (!NILP (descrip))
3607 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3608 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3609 for (j = SCHARS (item_name); j < maxwidth; j++)
3610 item_data[j] = ' ';
3611 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3612 item_data[j + SBYTES (descrip)] = 0;
3614 else
3615 item_data = SSDATA (item_name);
3617 if (lpane == TTYM_FAILURE
3618 || (! tty_menu_add_selection (menu, lpane, item_data,
3619 !NILP (enable), help_string)))
3621 tty_menu_destroy (menu);
3622 *error_name = "Can't add selection to menu";
3623 entry = Qnil;
3624 goto tty_menu_end;
3626 i += MENU_ITEMS_ITEM_LENGTH;
3627 lines++;
3631 maxlines = max (maxlines, lines);
3633 /* All set and ready to fly. */
3634 dispwidth = f->text_cols;
3635 dispheight = f->text_lines;
3636 x = min (x, dispwidth);
3637 y = min (y, dispheight);
3638 x = max (x, 1);
3639 y = max (y, 1);
3640 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3641 if (ulx + width > dispwidth)
3643 x -= (ulx + width) - dispwidth;
3644 ulx = dispwidth - width;
3646 if (uly + height > dispheight)
3648 y -= (uly + height) - dispheight;
3649 uly = dispheight - height;
3652 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3654 /* Move the menu away of the echo area, to avoid overwriting the
3655 menu with help echo messages or vice versa. */
3656 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3658 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3659 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3661 else
3663 y -= 2;
3664 uly -= 2;
3668 if (ulx < 0) x -= ulx;
3669 if (uly < 0) y -= uly;
3671 #if 0
3672 /* This code doesn't make sense on a TTY, since it can easily annul
3673 the adjustments above that carefully avoid truncation of the menu
3674 items. I think it was written to fix some problem that only
3675 happens on X11. */
3676 if (! for_click)
3678 /* If position was not given by a mouse click, adjust so upper left
3679 corner of the menu as a whole ends up at given coordinates. This
3680 is what x-popup-menu says in its documentation. */
3681 x += width / 2;
3682 y += 1.5 * height / (maxlines + 2);
3684 #endif
3686 pane = selidx = 0;
3688 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3690 specbind (Qoverriding_terminal_local_map,
3691 Fsymbol_value (Qtty_menu_navigation_map));
3692 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3693 tty_menu_help_callback,
3694 menuflags & MENU_KBD_NAVIGATION);
3695 entry = pane_prefix = Qnil;
3697 switch (status)
3699 case TTYM_SUCCESS:
3700 /* Find the item number SELIDX in pane number PANE. */
3701 i = 0;
3702 while (i < menu_items_used)
3704 if (EQ (AREF (menu_items, i), Qt))
3706 if (pane == 0)
3707 pane_prefix
3708 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3709 pane--;
3710 i += MENU_ITEMS_PANE_LENGTH;
3712 else
3714 if (pane == -1)
3716 if (selidx == 0)
3718 entry
3719 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3720 if (menuflags & MENU_KEYMAPS)
3722 entry = Fcons (entry, Qnil);
3723 if (!NILP (pane_prefix))
3724 entry = Fcons (pane_prefix, entry);
3726 break;
3728 selidx--;
3730 i += MENU_ITEMS_ITEM_LENGTH;
3733 break;
3735 case TTYM_NEXT:
3736 case TTYM_PREV:
3737 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3738 entry = Fcons (make_number (item_x), make_number (item_y));
3739 break;
3741 case TTYM_FAILURE:
3742 *error_name = "Can't activate menu";
3743 case TTYM_IA_SELECT:
3744 break;
3745 case TTYM_NO_SELECT:
3746 /* If the selected frame was changed while we displayed a menu,
3747 throw to top level in order to undo any temporary settings
3748 made by TTY menu code. */
3749 if (f != SELECTED_FRAME ())
3750 Ftop_level ();
3751 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3752 the menu was invoked with a mouse event as POSITION). */
3753 if (!(menuflags & MENU_FOR_CLICK))
3754 Fsignal (Qquit, Qnil);
3755 break;
3758 tty_menu_end:
3760 SAFE_FREE ();
3761 unbind_to (specpdl_count, Qnil);
3762 return entry;
3765 #endif /* !MSDOS */
3768 #ifndef MSDOS
3769 /***********************************************************************
3770 Initialization
3771 ***********************************************************************/
3773 /* Initialize the tty-dependent part of frame F. The frame must
3774 already have its device initialized. */
3776 void
3777 create_tty_output (struct frame *f)
3779 struct tty_output *t = xzalloc (sizeof *t);
3781 eassert (FRAME_TERMCAP_P (f));
3783 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3785 f->output_data.tty = t;
3788 /* Delete frame F's face cache, and its tty-dependent part. */
3790 static void
3791 tty_free_frame_resources (struct frame *f)
3793 eassert (FRAME_TERMCAP_P (f));
3794 free_frame_faces (f);
3795 xfree (f->output_data.tty);
3798 #else /* MSDOS */
3800 /* Delete frame F's face cache. */
3802 static void
3803 tty_free_frame_resources (struct frame *f)
3805 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3806 free_frame_faces (f);
3808 #endif /* MSDOS */
3810 /* Reset the hooks in TERMINAL. */
3812 static void
3813 clear_tty_hooks (struct terminal *terminal)
3815 terminal->rif = 0;
3816 terminal->cursor_to_hook = 0;
3817 terminal->raw_cursor_to_hook = 0;
3818 terminal->clear_to_end_hook = 0;
3819 terminal->clear_frame_hook = 0;
3820 terminal->clear_end_of_line_hook = 0;
3821 terminal->ins_del_lines_hook = 0;
3822 terminal->insert_glyphs_hook = 0;
3823 terminal->write_glyphs_hook = 0;
3824 terminal->delete_glyphs_hook = 0;
3825 terminal->ring_bell_hook = 0;
3826 terminal->reset_terminal_modes_hook = 0;
3827 terminal->set_terminal_modes_hook = 0;
3828 terminal->update_begin_hook = 0;
3829 terminal->update_end_hook = 0;
3830 terminal->set_terminal_window_hook = 0;
3831 terminal->mouse_position_hook = 0;
3832 terminal->frame_rehighlight_hook = 0;
3833 terminal->frame_raise_lower_hook = 0;
3834 terminal->fullscreen_hook = 0;
3835 terminal->menu_show_hook = 0;
3836 terminal->set_vertical_scroll_bar_hook = 0;
3837 terminal->set_horizontal_scroll_bar_hook = 0;
3838 terminal->condemn_scroll_bars_hook = 0;
3839 terminal->redeem_scroll_bar_hook = 0;
3840 terminal->judge_scroll_bars_hook = 0;
3841 terminal->read_socket_hook = 0;
3842 terminal->frame_up_to_date_hook = 0;
3844 /* Leave these two set, or suspended frames are not deleted
3845 correctly. */
3846 terminal->delete_frame_hook = &tty_free_frame_resources;
3847 terminal->delete_terminal_hook = &delete_tty;
3850 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3852 static void
3853 set_tty_hooks (struct terminal *terminal)
3855 terminal->cursor_to_hook = &tty_cursor_to;
3856 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3857 terminal->clear_to_end_hook = &tty_clear_to_end;
3858 terminal->clear_frame_hook = &tty_clear_frame;
3859 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3860 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3861 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3862 terminal->write_glyphs_hook = &tty_write_glyphs;
3863 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3864 terminal->ring_bell_hook = &tty_ring_bell;
3865 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3866 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3867 terminal->update_end_hook = &tty_update_end;
3868 #ifdef MSDOS
3869 terminal->menu_show_hook = &x_menu_show;
3870 #else
3871 terminal->menu_show_hook = &tty_menu_show;
3872 #endif
3873 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3874 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3875 terminal->delete_frame_hook = &tty_free_frame_resources;
3876 terminal->delete_terminal_hook = &delete_tty;
3877 /* Other hooks are NULL by default. */
3880 /* If FD is the controlling terminal, drop it. */
3881 static void
3882 dissociate_if_controlling_tty (int fd)
3884 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3885 so dissociate it by invoking setsid. */
3886 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3888 #ifdef TIOCNOTTY
3889 /* setsid failed, presumably because Emacs is already a process
3890 group leader. Fall back on the obsolescent way to dissociate
3891 a controlling tty. */
3892 sigset_t oldset;
3893 block_tty_out_signal (&oldset);
3894 ioctl (fd, TIOCNOTTY, 0);
3895 unblock_tty_out_signal (&oldset);
3896 #endif
3900 /* Create a termcap display on the tty device with the given name and
3901 type.
3903 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3904 Otherwise NAME should be a path to the tty device file,
3905 e.g. "/dev/pts/7".
3907 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3909 If MUST_SUCCEED is true, then all errors are fatal. */
3911 struct terminal *
3912 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3914 char *area;
3915 char **address = &area;
3916 int status;
3917 struct tty_display_info *tty = NULL;
3918 struct terminal *terminal = NULL;
3919 sigset_t oldset;
3920 bool ctty = false; /* True if asked to open controlling tty. */
3922 if (!terminal_type)
3923 maybe_fatal (must_succeed, 0,
3924 "Unknown terminal type",
3925 "Unknown terminal type");
3927 if (name == NULL)
3928 name = DEV_TTY;
3929 if (!strcmp (name, DEV_TTY))
3930 ctty = 1;
3932 /* If we already have a terminal on the given device, use that. If
3933 all such terminals are suspended, create a new one instead. */
3934 /* XXX Perhaps this should be made explicit by having init_tty
3935 always create a new terminal and separating terminal and frame
3936 creation on Lisp level. */
3937 terminal = get_named_terminal (name);
3938 if (terminal)
3939 return terminal;
3941 terminal = create_terminal (output_termcap, NULL);
3942 #ifdef MSDOS
3943 if (been_here > 0)
3944 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3945 name, "");
3946 been_here = 1;
3947 tty = &the_only_display_info;
3948 #else
3949 tty = xzalloc (sizeof *tty);
3950 #endif
3951 tty->top_frame = Qnil;
3952 tty->next = tty_list;
3953 tty_list = tty;
3955 terminal->display_info.tty = tty;
3956 tty->terminal = terminal;
3958 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3959 Wcm_clear (tty);
3961 encode_terminal_src_size = 0;
3962 encode_terminal_dst_size = 0;
3965 #ifndef DOS_NT
3966 set_tty_hooks (terminal);
3969 /* Open the terminal device. */
3971 /* If !ctty, don't recognize it as our controlling terminal, and
3972 don't make it the controlling tty if we don't have one now.
3974 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3975 defined on Hurd. On other systems, we need to explicitly
3976 dissociate ourselves from the controlling tty when we want to
3977 open a frame on the same terminal. */
3978 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3979 int fd = emacs_open (name, flags, 0);
3980 tty->input = tty->output
3981 = ((fd < 0 || ! isatty (fd))
3982 ? NULL
3983 : fdopen (fd, "w+"));
3985 if (! tty->input)
3987 char const *diagnostic
3988 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3989 emacs_close (fd);
3990 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
3993 tty->name = xstrdup (name);
3994 terminal->name = xstrdup (name);
3996 if (!O_IGNORE_CTTY && !ctty)
3997 dissociate_if_controlling_tty (fd);
4000 tty->type = xstrdup (terminal_type);
4002 add_keyboard_wait_descriptor (fileno (tty->input));
4004 Wcm_clear (tty);
4006 /* On some systems, tgetent tries to access the controlling
4007 terminal. */
4008 block_tty_out_signal (&oldset);
4009 status = tgetent (tty->termcap_term_buffer, terminal_type);
4010 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4011 emacs_abort ();
4012 unblock_tty_out_signal (&oldset);
4014 if (status < 0)
4016 #ifdef TERMINFO
4017 maybe_fatal (must_succeed, terminal,
4018 "Cannot open terminfo database file",
4019 "Cannot open terminfo database file");
4020 #else
4021 maybe_fatal (must_succeed, terminal,
4022 "Cannot open termcap database file",
4023 "Cannot open termcap database file");
4024 #endif
4026 if (status == 0)
4028 maybe_fatal (must_succeed, terminal,
4029 "Terminal type %s is not defined",
4030 "Terminal type %s is not defined.\n\
4031 If that is not the actual type of terminal you have,\n\
4032 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4033 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4034 #ifdef TERMINFO
4035 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4036 #else
4037 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4038 #endif
4039 terminal_type);
4042 area = tty->termcap_strings_buffer;
4043 tty->TS_ins_line = tgetstr ("al", address);
4044 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4045 tty->TS_bell = tgetstr ("bl", address);
4046 BackTab (tty) = tgetstr ("bt", address);
4047 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4048 tty->TS_clr_line = tgetstr ("ce", address);
4049 tty->TS_clr_frame = tgetstr ("cl", address);
4050 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4051 AbsPosition (tty) = tgetstr ("cm", address);
4052 CR (tty) = tgetstr ("cr", address);
4053 tty->TS_set_scroll_region = tgetstr ("cs", address);
4054 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4055 RowPosition (tty) = tgetstr ("cv", address);
4056 tty->TS_del_char = tgetstr ("dc", address);
4057 tty->TS_del_multi_chars = tgetstr ("DC", address);
4058 tty->TS_del_line = tgetstr ("dl", address);
4059 tty->TS_del_multi_lines = tgetstr ("DL", address);
4060 tty->TS_delete_mode = tgetstr ("dm", address);
4061 tty->TS_end_delete_mode = tgetstr ("ed", address);
4062 tty->TS_end_insert_mode = tgetstr ("ei", address);
4063 Home (tty) = tgetstr ("ho", address);
4064 tty->TS_ins_char = tgetstr ("ic", address);
4065 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4066 tty->TS_insert_mode = tgetstr ("im", address);
4067 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4068 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4069 tty->TS_keypad_mode = tgetstr ("ks", address);
4070 LastLine (tty) = tgetstr ("ll", address);
4071 Right (tty) = tgetstr ("nd", address);
4072 Down (tty) = tgetstr ("do", address);
4073 if (!Down (tty))
4074 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4075 if (tgetflag ("bs"))
4076 Left (tty) = "\b"; /* Can't possibly be longer! */
4077 else /* (Actually, "bs" is obsolete...) */
4078 Left (tty) = tgetstr ("le", address);
4079 if (!Left (tty))
4080 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4081 tty->TS_pad_char = tgetstr ("pc", address);
4082 tty->TS_repeat = tgetstr ("rp", address);
4083 tty->TS_end_standout_mode = tgetstr ("se", address);
4084 tty->TS_fwd_scroll = tgetstr ("sf", address);
4085 tty->TS_standout_mode = tgetstr ("so", address);
4086 tty->TS_rev_scroll = tgetstr ("sr", address);
4087 tty->Wcm->cm_tab = tgetstr ("ta", address);
4088 tty->TS_end_termcap_modes = tgetstr ("te", address);
4089 tty->TS_termcap_modes = tgetstr ("ti", address);
4090 Up (tty) = tgetstr ("up", address);
4091 tty->TS_visible_bell = tgetstr ("vb", address);
4092 tty->TS_cursor_normal = tgetstr ("ve", address);
4093 tty->TS_cursor_visible = tgetstr ("vs", address);
4094 tty->TS_cursor_invisible = tgetstr ("vi", address);
4095 tty->TS_set_window = tgetstr ("wi", address);
4097 tty->TS_enter_underline_mode = tgetstr ("us", address);
4098 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4099 tty->TS_enter_bold_mode = tgetstr ("md", address);
4100 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4101 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4102 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4103 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4104 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4105 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4107 MultiUp (tty) = tgetstr ("UP", address);
4108 MultiDown (tty) = tgetstr ("DO", address);
4109 MultiLeft (tty) = tgetstr ("LE", address);
4110 MultiRight (tty) = tgetstr ("RI", address);
4112 /* SVr4/ANSI color support. If "op" isn't available, don't support
4113 color because we can't switch back to the default foreground and
4114 background. */
4115 tty->TS_orig_pair = tgetstr ("op", address);
4116 if (tty->TS_orig_pair)
4118 tty->TS_set_foreground = tgetstr ("AF", address);
4119 tty->TS_set_background = tgetstr ("AB", address);
4120 if (!tty->TS_set_foreground)
4122 /* SVr4. */
4123 tty->TS_set_foreground = tgetstr ("Sf", address);
4124 tty->TS_set_background = tgetstr ("Sb", address);
4127 tty->TN_max_colors = tgetnum ("Co");
4128 tty->TN_max_pairs = tgetnum ("pa");
4130 tty->TN_no_color_video = tgetnum ("NC");
4131 if (tty->TN_no_color_video == -1)
4132 tty->TN_no_color_video = 0;
4135 tty_default_color_capabilities (tty, 1);
4137 MagicWrap (tty) = tgetflag ("xn");
4138 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4139 the former flag imply the latter. */
4140 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4141 tty->memory_below_frame = tgetflag ("db");
4142 tty->TF_hazeltine = tgetflag ("hz");
4143 tty->must_write_spaces = tgetflag ("in");
4144 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4145 tty->TF_insmode_motion = tgetflag ("mi");
4146 tty->TF_standout_motion = tgetflag ("ms");
4147 tty->TF_underscore = tgetflag ("ul");
4148 tty->TF_teleray = tgetflag ("xt");
4150 #else /* DOS_NT */
4151 #ifdef WINDOWSNT
4153 struct frame *f = XFRAME (selected_frame);
4154 int height, width;
4156 initialize_w32_display (terminal, &width, &height);
4158 FrameRows (tty) = height;
4159 FrameCols (tty) = width;
4160 tty->specified_window = height;
4162 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4163 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4164 tty->char_ins_del_ok = 1;
4165 baud_rate = 19200;
4167 #else /* MSDOS */
4169 int height, width;
4170 if (strcmp (terminal_type, "internal") == 0)
4171 terminal->type = output_msdos_raw;
4172 initialize_msdos_display (terminal);
4174 get_tty_size (fileno (tty->input), &width, &height);
4175 FrameCols (tty) = width;
4176 FrameRows (tty) = height;
4177 tty->char_ins_del_ok = 0;
4178 init_baud_rate (fileno (tty->input));
4180 #endif /* MSDOS */
4181 tty->output = stdout;
4182 tty->input = stdin;
4183 /* The following two are inaccessible from w32console.c. */
4184 terminal->delete_frame_hook = &tty_free_frame_resources;
4185 terminal->delete_terminal_hook = &delete_tty;
4187 tty->name = xstrdup (name);
4188 terminal->name = xstrdup (name);
4189 tty->type = xstrdup (terminal_type);
4191 add_keyboard_wait_descriptor (0);
4193 tty->delete_in_insert_mode = 1;
4195 UseTabs (tty) = 0;
4196 tty->scroll_region_ok = 0;
4198 /* Seems to insert lines when it's not supposed to, messing up the
4199 display. In doing a trace, it didn't seem to be called much, so I
4200 don't think we're losing anything by turning it off. */
4201 tty->line_ins_del_ok = 0;
4203 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4204 #endif /* DOS_NT */
4206 #ifdef HAVE_GPM
4207 terminal->mouse_position_hook = term_mouse_position;
4208 tty->mouse_highlight.mouse_face_window = Qnil;
4209 #endif
4211 terminal->kboard = allocate_kboard (Qnil);
4212 terminal->kboard->reference_count++;
4213 /* Don't let the initial kboard remain current longer than necessary.
4214 That would cause problems if a file loaded on startup tries to
4215 prompt in the mini-buffer. */
4216 if (current_kboard == initial_kboard)
4217 current_kboard = terminal->kboard;
4218 #ifndef DOS_NT
4219 term_get_fkeys (address, terminal->kboard);
4221 /* Get frame size from system, or else from termcap. */
4223 int height, width;
4224 get_tty_size (fileno (tty->input), &width, &height);
4225 FrameCols (tty) = width;
4226 FrameRows (tty) = height;
4229 if (FrameCols (tty) <= 0)
4230 FrameCols (tty) = tgetnum ("co");
4231 if (FrameRows (tty) <= 0)
4232 FrameRows (tty) = tgetnum ("li");
4234 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4235 maybe_fatal (must_succeed, terminal,
4236 "Screen size %dx%d is too small",
4237 "Screen size %dx%d is too small",
4238 FrameCols (tty), FrameRows (tty));
4240 TabWidth (tty) = tgetnum ("tw");
4242 if (!tty->TS_bell)
4243 tty->TS_bell = "\07";
4245 if (!tty->TS_fwd_scroll)
4246 tty->TS_fwd_scroll = Down (tty);
4248 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4250 if (TabWidth (tty) < 0)
4251 TabWidth (tty) = 8;
4253 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4254 and newer termcap doc does not seem to say there is a default.
4255 if (!tty->Wcm->cm_tab)
4256 tty->Wcm->cm_tab = "\t";
4259 /* We don't support standout modes that use `magic cookies', so
4260 turn off any that do. */
4261 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4263 tty->TS_standout_mode = 0;
4264 tty->TS_end_standout_mode = 0;
4266 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4268 tty->TS_enter_underline_mode = 0;
4269 tty->TS_exit_underline_mode = 0;
4272 /* If there's no standout mode, try to use underlining instead. */
4273 if (tty->TS_standout_mode == 0)
4275 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4276 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4279 /* If no `se' string, try using a `me' string instead.
4280 If that fails, we can't use standout mode at all. */
4281 if (tty->TS_end_standout_mode == 0)
4283 char *s = tgetstr ("me", address);
4284 if (s != 0)
4285 tty->TS_end_standout_mode = s;
4286 else
4287 tty->TS_standout_mode = 0;
4290 if (tty->TF_teleray)
4292 tty->Wcm->cm_tab = 0;
4293 /* We can't support standout mode, because it uses magic cookies. */
4294 tty->TS_standout_mode = 0;
4295 /* But that means we cannot rely on ^M to go to column zero! */
4296 CR (tty) = 0;
4297 /* LF can't be trusted either -- can alter hpos. */
4298 /* If move at column 0 thru a line with TS_standout_mode. */
4299 Down (tty) = 0;
4302 tty->specified_window = FrameRows (tty);
4304 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4306 maybe_fatal (must_succeed, terminal,
4307 "Terminal type \"%s\" is not powerful enough to run Emacs",
4308 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4309 It lacks the ability to position the cursor.\n\
4310 If that is not the actual type of terminal you have,\n\
4311 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4312 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4313 # ifdef TERMINFO
4314 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4315 # else /* TERMCAP */
4316 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4317 # endif /* TERMINFO */
4318 terminal_type);
4321 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4322 maybe_fatal (must_succeed, terminal,
4323 "Could not determine the frame size",
4324 "Could not determine the frame size");
4326 tty->delete_in_insert_mode
4327 = tty->TS_delete_mode && tty->TS_insert_mode
4328 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4330 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4332 tty->scroll_region_ok
4333 = (tty->Wcm->cm_abs
4334 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4336 tty->line_ins_del_ok
4337 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4338 && (tty->TS_del_line || tty->TS_del_multi_lines))
4339 || (tty->scroll_region_ok
4340 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4342 tty->char_ins_del_ok
4343 = ((tty->TS_ins_char || tty->TS_insert_mode
4344 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4345 && (tty->TS_del_char || tty->TS_del_multi_chars));
4347 init_baud_rate (fileno (tty->input));
4349 #endif /* not DOS_NT */
4351 /* Init system terminal modes (RAW or CBREAK, etc.). */
4352 init_sys_modes (tty);
4354 return terminal;
4358 static void
4359 vfatal (const char *str, va_list ap)
4361 fprintf (stderr, "emacs: ");
4362 vfprintf (stderr, str, ap);
4363 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4364 fprintf (stderr, "\n");
4365 fflush (stderr);
4366 exit (1);
4370 /* Auxiliary error-handling function for init_tty.
4371 Delete TERMINAL, then call error or fatal with str1 or str2,
4372 respectively, according to whether MUST_SUCCEED is true. */
4374 static void
4375 maybe_fatal (bool must_succeed, struct terminal *terminal,
4376 const char *str1, const char *str2, ...)
4378 va_list ap;
4379 va_start (ap, str2);
4380 if (terminal)
4381 delete_tty (terminal);
4383 if (must_succeed)
4384 vfatal (str2, ap);
4385 else
4386 verror (str1, ap);
4389 void
4390 fatal (const char *str, ...)
4392 va_list ap;
4393 va_start (ap, str);
4394 vfatal (str, ap);
4399 /* Delete the given tty terminal, closing all frames on it. */
4401 static void
4402 delete_tty (struct terminal *terminal)
4404 struct tty_display_info *tty;
4406 /* Protect against recursive calls. delete_frame in
4407 delete_terminal calls us back when it deletes our last frame. */
4408 if (!terminal->name)
4409 return;
4411 eassert (terminal->type == output_termcap);
4413 tty = terminal->display_info.tty;
4415 if (tty == tty_list)
4416 tty_list = tty->next;
4417 else
4419 struct tty_display_info *p;
4420 for (p = tty_list; p && p->next != tty; p = p->next)
4423 if (! p)
4424 /* This should not happen. */
4425 emacs_abort ();
4427 p->next = tty->next;
4428 tty->next = 0;
4431 /* reset_sys_modes needs a valid device, so this call needs to be
4432 before delete_terminal. */
4433 reset_sys_modes (tty);
4435 delete_terminal (terminal);
4437 xfree (tty->name);
4438 xfree (tty->type);
4440 if (tty->input)
4442 delete_keyboard_wait_descriptor (fileno (tty->input));
4443 if (tty->input != stdin)
4444 fclose (tty->input);
4446 if (tty->output && tty->output != stdout && tty->output != tty->input)
4447 fclose (tty->output);
4448 if (tty->termscript)
4449 fclose (tty->termscript);
4451 xfree (tty->old_tty);
4452 xfree (tty->Wcm);
4453 xfree (tty);
4456 void
4457 syms_of_term (void)
4459 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4460 doc: /* Non-nil means the system uses terminfo rather than termcap.
4461 This variable can be used by terminal emulator packages. */);
4462 #ifdef TERMINFO
4463 system_uses_terminfo = 1;
4464 #else
4465 system_uses_terminfo = 0;
4466 #endif
4468 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4469 doc: /* Functions run after suspending a tty.
4470 The functions are run with one argument, the terminal object to be suspended.
4471 See `suspend-tty'. */);
4472 Vsuspend_tty_functions = Qnil;
4475 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4476 doc: /* Functions run after resuming a tty.
4477 The functions are run with one argument, the terminal object that was revived.
4478 See `resume-tty'. */);
4479 Vresume_tty_functions = Qnil;
4481 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4482 doc: /* Non-nil means to make the cursor very visible.
4483 This only has an effect when running in a text terminal.
4484 What means \"very visible\" is up to your terminal. It may make the cursor
4485 bigger, or it may make it blink, or it may do nothing at all. */);
4486 visible_cursor = 1;
4488 defsubr (&Stty_display_color_p);
4489 defsubr (&Stty_display_color_cells);
4490 defsubr (&Stty_no_underline);
4491 defsubr (&Stty_type);
4492 defsubr (&Scontrolling_tty_p);
4493 defsubr (&Stty_top_frame);
4494 defsubr (&Ssuspend_tty);
4495 defsubr (&Sresume_tty);
4496 #ifdef HAVE_GPM
4497 defsubr (&Sgpm_mouse_start);
4498 defsubr (&Sgpm_mouse_stop);
4499 #endif /* HAVE_GPM */
4501 #ifndef DOS_NT
4502 default_orig_pair = NULL;
4503 default_set_foreground = NULL;
4504 default_set_background = NULL;
4505 #endif /* !DOS_NT */
4507 encode_terminal_src = NULL;
4508 encode_terminal_dst = NULL;
4510 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4511 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4513 #ifndef MSDOS
4514 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4515 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4516 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4517 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4518 DEFSYM (Qtty_menu_select, "tty-menu-select");
4519 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4520 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4521 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4522 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4523 #endif