src/w32heap.c (init_heap): Fix typos in comments (again).
[emacs.git] / src / term.c
blob379c94e54a1dd4665e6d239f1702c34be7b5b9a3
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2014 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 #include "systty.h"
48 #include "intervals.h"
49 #ifdef MSDOS
50 #include "msdos.h"
51 static int been_here = -1;
52 #endif
54 #ifdef USE_X_TOOLKIT
55 #include "../lwlib/lwlib.h"
56 #endif
58 #include "cm.h"
59 #ifdef HAVE_X_WINDOWS
60 #include "xterm.h"
61 #endif
63 #include "menu.h"
65 /* The name of the default console device. */
66 #ifdef WINDOWSNT
67 #define DEV_TTY "CONOUT$"
68 #include "w32term.h"
69 #else
70 #define DEV_TTY "/dev/tty"
71 #endif
73 static void tty_set_scroll_region (struct frame *f, int start, int stop);
74 static void turn_on_face (struct frame *, int face_id);
75 static void turn_off_face (struct frame *, int face_id);
76 static void tty_turn_off_highlight (struct tty_display_info *);
77 static void tty_show_cursor (struct tty_display_info *);
78 static void tty_hide_cursor (struct tty_display_info *);
79 static void tty_background_highlight (struct tty_display_info *tty);
80 static struct terminal *get_tty_terminal (Lisp_Object, bool);
81 static void clear_tty_hooks (struct terminal *terminal);
82 static void set_tty_hooks (struct terminal *terminal);
83 static void dissociate_if_controlling_tty (int fd);
84 static void delete_tty (struct terminal *);
85 static _Noreturn void maybe_fatal (bool, struct terminal *,
86 const char *, const char *, ...)
87 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
88 static _Noreturn void vfatal (const char *str, va_list ap)
89 ATTRIBUTE_FORMAT_PRINTF (1, 0);
92 #define OUTPUT(tty, a) \
93 emacs_tputs ((tty), a, \
94 FRAME_LINES (XFRAME (selected_frame)) - curY (tty), \
95 cmputc)
97 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
98 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
100 #define OUTPUT_IF(tty, a) \
101 do { \
102 if (a) \
103 OUTPUT (tty, a); \
104 } while (0)
106 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
108 /* Display space properties */
110 /* Chain of all tty device parameters. */
111 struct tty_display_info *tty_list;
113 /* Meaning of bits in no_color_video. Each bit set means that the
114 corresponding attribute cannot be combined with colors. */
116 enum no_color_bit
118 NC_STANDOUT = 1 << 0,
119 NC_UNDERLINE = 1 << 1,
120 NC_REVERSE = 1 << 2,
121 NC_ITALIC = 1 << 3,
122 NC_DIM = 1 << 4,
123 NC_BOLD = 1 << 5,
124 NC_INVIS = 1 << 6,
125 NC_PROTECT = 1 << 7
128 /* internal state */
130 /* The largest frame width in any call to calculate_costs. */
132 static int max_frame_cols;
134 static Lisp_Object Qtty_mode_set_strings;
135 static Lisp_Object Qtty_mode_reset_strings;
139 #ifdef HAVE_GPM
140 #include <sys/fcntl.h>
142 /* The device for which we have enabled gpm support (or NULL). */
143 struct tty_display_info *gpm_tty = NULL;
145 /* Last recorded mouse coordinates. */
146 static int last_mouse_x, last_mouse_y;
147 #endif /* HAVE_GPM */
149 /* Ring the bell on a tty. */
151 static void
152 tty_ring_bell (struct frame *f)
154 struct tty_display_info *tty = FRAME_TTY (f);
156 if (tty->output)
158 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
159 ? tty->TS_visible_bell
160 : tty->TS_bell));
161 fflush (tty->output);
165 /* Set up termcap modes for Emacs. */
167 static void
168 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
170 Lisp_Object lisp_terminal;
171 Lisp_Object extra_codes;
172 struct tty_display_info *tty = terminal->display_info.tty;
174 XSETTERMINAL (lisp_terminal, terminal);
175 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
176 CONSP (extra_codes);
177 extra_codes = XCDR (extra_codes))
179 Lisp_Object string = XCAR (extra_codes);
180 if (STRINGP (string))
182 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
183 if (tty->termscript)
184 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
189 static void
190 tty_set_terminal_modes (struct terminal *terminal)
192 struct tty_display_info *tty = terminal->display_info.tty;
194 if (tty->output)
196 if (tty->TS_termcap_modes)
197 OUTPUT (tty, tty->TS_termcap_modes);
198 else
200 /* Output enough newlines to scroll all the old screen contents
201 off the screen, so it won't be overwritten and lost. */
202 int i;
203 current_tty = tty;
204 for (i = 0; i < FRAME_LINES (XFRAME (selected_frame)); i++)
205 cmputc ('\n');
208 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
209 OUTPUT_IF (tty, tty->TS_keypad_mode);
210 losecursor (tty);
211 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
212 fflush (tty->output);
216 /* Reset termcap modes before exiting Emacs. */
218 static void
219 tty_reset_terminal_modes (struct terminal *terminal)
221 struct tty_display_info *tty = terminal->display_info.tty;
223 if (tty->output)
225 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
226 tty_turn_off_highlight (tty);
227 tty_turn_off_insert (tty);
228 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
229 OUTPUT_IF (tty, tty->TS_cursor_normal);
230 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
231 OUTPUT_IF (tty, tty->TS_orig_pair);
232 /* Output raw CR so kernel can track the cursor hpos. */
233 current_tty = tty;
234 cmputc ('\r');
235 fflush (tty->output);
239 /* Flag the end of a display update on a termcap terminal. */
241 static void
242 tty_update_end (struct frame *f)
244 struct tty_display_info *tty = FRAME_TTY (f);
246 if (!XWINDOW (selected_window)->cursor_off_p)
247 tty_show_cursor (tty);
248 tty_turn_off_insert (tty);
249 tty_background_highlight (tty);
250 fflush (tty->output);
253 /* The implementation of set_terminal_window for termcap frames. */
255 static void
256 tty_set_terminal_window (struct frame *f, int size)
258 struct tty_display_info *tty = FRAME_TTY (f);
260 tty->specified_window = size ? size : FRAME_LINES (f);
261 if (FRAME_SCROLL_REGION_OK (f))
262 tty_set_scroll_region (f, 0, tty->specified_window);
265 static void
266 tty_set_scroll_region (struct frame *f, int start, int stop)
268 char *buf;
269 struct tty_display_info *tty = FRAME_TTY (f);
271 if (tty->TS_set_scroll_region)
272 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
273 else if (tty->TS_set_scroll_region_1)
274 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
275 FRAME_LINES (f), start,
276 FRAME_LINES (f) - stop,
277 FRAME_LINES (f));
278 else
279 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
281 OUTPUT (tty, buf);
282 xfree (buf);
283 losecursor (tty);
287 static void
288 tty_turn_on_insert (struct tty_display_info *tty)
290 if (!tty->insert_mode)
291 OUTPUT (tty, tty->TS_insert_mode);
292 tty->insert_mode = 1;
295 void
296 tty_turn_off_insert (struct tty_display_info *tty)
298 if (tty->insert_mode)
299 OUTPUT (tty, tty->TS_end_insert_mode);
300 tty->insert_mode = 0;
303 /* Handle highlighting. */
305 static void
306 tty_turn_off_highlight (struct tty_display_info *tty)
308 if (tty->standout_mode)
309 OUTPUT_IF (tty, tty->TS_end_standout_mode);
310 tty->standout_mode = 0;
313 static void
314 tty_turn_on_highlight (struct tty_display_info *tty)
316 if (!tty->standout_mode)
317 OUTPUT_IF (tty, tty->TS_standout_mode);
318 tty->standout_mode = 1;
321 static void
322 tty_toggle_highlight (struct tty_display_info *tty)
324 if (tty->standout_mode)
325 tty_turn_off_highlight (tty);
326 else
327 tty_turn_on_highlight (tty);
331 /* Make cursor invisible. */
333 static void
334 tty_hide_cursor (struct tty_display_info *tty)
336 if (tty->cursor_hidden == 0)
338 tty->cursor_hidden = 1;
339 #ifdef WINDOWSNT
340 w32con_hide_cursor ();
341 #else
342 OUTPUT_IF (tty, tty->TS_cursor_invisible);
343 #endif
348 /* Ensure that cursor is visible. */
350 static void
351 tty_show_cursor (struct tty_display_info *tty)
353 if (tty->cursor_hidden)
355 tty->cursor_hidden = 0;
356 #ifdef WINDOWSNT
357 w32con_show_cursor ();
358 #else
359 OUTPUT_IF (tty, tty->TS_cursor_normal);
360 if (visible_cursor)
361 OUTPUT_IF (tty, tty->TS_cursor_visible);
362 #endif
367 /* Set standout mode to the state it should be in for
368 empty space inside windows. What this is,
369 depends on the user option inverse-video. */
371 static void
372 tty_background_highlight (struct tty_display_info *tty)
374 if (inverse_video)
375 tty_turn_on_highlight (tty);
376 else
377 tty_turn_off_highlight (tty);
380 /* Set standout mode to the mode specified for the text to be output. */
382 static void
383 tty_highlight_if_desired (struct tty_display_info *tty)
385 if (inverse_video)
386 tty_turn_on_highlight (tty);
387 else
388 tty_turn_off_highlight (tty);
392 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
393 frame-relative coordinates. */
395 static void
396 tty_cursor_to (struct frame *f, int vpos, int hpos)
398 struct tty_display_info *tty = FRAME_TTY (f);
400 /* Detect the case where we are called from reset_sys_modes
401 and the costs have never been calculated. Do nothing. */
402 if (! tty->costs_set)
403 return;
405 if (curY (tty) == vpos
406 && curX (tty) == hpos)
407 return;
408 if (!tty->TF_standout_motion)
409 tty_background_highlight (tty);
410 if (!tty->TF_insmode_motion)
411 tty_turn_off_insert (tty);
412 cmgoto (tty, vpos, hpos);
415 /* Similar but don't take any account of the wasted characters. */
417 static void
418 tty_raw_cursor_to (struct frame *f, int row, int col)
420 struct tty_display_info *tty = FRAME_TTY (f);
422 if (curY (tty) == row
423 && curX (tty) == col)
424 return;
425 if (!tty->TF_standout_motion)
426 tty_background_highlight (tty);
427 if (!tty->TF_insmode_motion)
428 tty_turn_off_insert (tty);
429 cmgoto (tty, row, col);
432 /* Erase operations */
434 /* Clear from cursor to end of frame on a termcap device. */
436 static void
437 tty_clear_to_end (struct frame *f)
439 register int i;
440 struct tty_display_info *tty = FRAME_TTY (f);
442 if (tty->TS_clr_to_bottom)
444 tty_background_highlight (tty);
445 OUTPUT (tty, tty->TS_clr_to_bottom);
447 else
449 for (i = curY (tty); i < FRAME_LINES (f); i++)
451 cursor_to (f, i, 0);
452 clear_end_of_line (f, FRAME_COLS (f));
457 /* Clear an entire termcap frame. */
459 static void
460 tty_clear_frame (struct frame *f)
462 struct tty_display_info *tty = FRAME_TTY (f);
464 if (tty->TS_clr_frame)
466 tty_background_highlight (tty);
467 OUTPUT (tty, tty->TS_clr_frame);
468 cmat (tty, 0, 0);
470 else
472 cursor_to (f, 0, 0);
473 clear_to_end (f);
477 /* An implementation of clear_end_of_line for termcap frames.
479 Note that the cursor may be moved, on terminals lacking a `ce' string. */
481 static void
482 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
484 register int i;
485 struct tty_display_info *tty = FRAME_TTY (f);
487 /* Detect the case where we are called from reset_sys_modes
488 and the costs have never been calculated. Do nothing. */
489 if (! tty->costs_set)
490 return;
492 if (curX (tty) >= first_unused_hpos)
493 return;
494 tty_background_highlight (tty);
495 if (tty->TS_clr_line)
497 OUTPUT1 (tty, tty->TS_clr_line);
499 else
500 { /* have to do it the hard way */
501 tty_turn_off_insert (tty);
503 /* Do not write in last row last col with Auto-wrap on. */
504 if (AutoWrap (tty)
505 && curY (tty) == FrameRows (tty) - 1
506 && first_unused_hpos == FrameCols (tty))
507 first_unused_hpos--;
509 for (i = curX (tty); i < first_unused_hpos; i++)
511 if (tty->termscript)
512 fputc (' ', tty->termscript);
513 fputc (' ', tty->output);
515 cmplus (tty, first_unused_hpos - curX (tty));
519 /* Buffers to store the source and result of code conversion for terminal. */
520 static unsigned char *encode_terminal_src;
521 static unsigned char *encode_terminal_dst;
522 /* Allocated sizes of the above buffers. */
523 static ptrdiff_t encode_terminal_src_size;
524 static ptrdiff_t encode_terminal_dst_size;
526 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
527 Set CODING->produced to the byte-length of the resulting byte
528 sequence, and return a pointer to that byte sequence. */
530 #ifndef DOS_NT
531 static
532 #endif
533 unsigned char *
534 encode_terminal_code (struct glyph *src, int src_len,
535 struct coding_system *coding)
537 struct glyph *src_end = src + src_len;
538 unsigned char *buf;
539 ptrdiff_t nchars, nbytes, required;
540 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
541 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
542 Lisp_Object charset_list;
544 /* Allocate sufficient size of buffer to store all characters in
545 multibyte-form. But, it may be enlarged on demand if
546 Vglyph_table contains a string or a composite glyph is
547 encountered. */
548 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
549 memory_full (SIZE_MAX);
550 required = src_len;
551 required *= MAX_MULTIBYTE_LENGTH;
552 if (encode_terminal_src_size < required)
554 encode_terminal_src = xrealloc (encode_terminal_src, required);
555 encode_terminal_src_size = required;
558 charset_list = coding_charset_list (coding);
560 buf = encode_terminal_src;
561 nchars = 0;
562 while (src < src_end)
564 if (src->type == COMPOSITE_GLYPH)
566 struct composition *cmp IF_LINT (= NULL);
567 Lisp_Object gstring IF_LINT (= Qnil);
568 int i;
570 nbytes = buf - encode_terminal_src;
571 if (src->u.cmp.automatic)
573 gstring = composition_gstring_from_id (src->u.cmp.id);
574 required = src->slice.cmp.to - src->slice.cmp.from + 1;
576 else
578 cmp = composition_table[src->u.cmp.id];
579 required = cmp->glyph_len;
580 required *= MAX_MULTIBYTE_LENGTH;
583 if (encode_terminal_src_size - nbytes < required)
585 encode_terminal_src =
586 xpalloc (encode_terminal_src, &encode_terminal_src_size,
587 required - (encode_terminal_src_size - nbytes),
588 -1, 1);
589 buf = encode_terminal_src + nbytes;
592 if (src->u.cmp.automatic)
593 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
595 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
596 int c = LGLYPH_CHAR (g);
598 if (! char_charset (c, charset_list, NULL))
599 c = '?';
600 buf += CHAR_STRING (c, buf);
601 nchars++;
603 else
604 for (i = 0; i < cmp->glyph_len; i++)
606 int c = COMPOSITION_GLYPH (cmp, i);
608 /* TAB in a composition means display glyphs with
609 padding space on the left or right. */
610 if (c == '\t')
611 continue;
612 if (char_charset (c, charset_list, NULL))
614 if (CHAR_WIDTH (c) == 0
615 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
616 /* Should be left-padded */
618 buf += CHAR_STRING (' ', buf);
619 nchars++;
622 else
623 c = '?';
624 buf += CHAR_STRING (c, buf);
625 nchars++;
628 /* We must skip glyphs to be padded for a wide character. */
629 else if (! CHAR_GLYPH_PADDING_P (*src))
631 GLYPH g;
632 int c IF_LINT (= 0);
633 Lisp_Object string;
635 string = Qnil;
636 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
638 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
640 /* This glyph doesn't have an entry in Vglyph_table. */
641 c = src->u.ch;
643 else
645 /* This glyph has an entry in Vglyph_table,
646 so process any alias before testing for simpleness. */
647 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
649 if (GLYPH_SIMPLE_P (tbase, tlen, g))
650 /* We set the multi-byte form of a character in G
651 (that should be an ASCII character) at WORKBUF. */
652 c = GLYPH_CHAR (g);
653 else
654 /* We have a string in Vglyph_table. */
655 string = tbase[GLYPH_CHAR (g)];
658 if (NILP (string))
660 nbytes = buf - encode_terminal_src;
661 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
663 encode_terminal_src =
664 xpalloc (encode_terminal_src, &encode_terminal_src_size,
665 MAX_MULTIBYTE_LENGTH, -1, 1);
666 buf = encode_terminal_src + nbytes;
668 if (CHAR_BYTE8_P (c)
669 || char_charset (c, charset_list, NULL))
671 /* Store the multibyte form of C at BUF. */
672 buf += CHAR_STRING (c, buf);
673 nchars++;
675 else
677 /* C is not encodable. */
678 *buf++ = '?';
679 nchars++;
680 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
682 *buf++ = '?';
683 nchars++;
684 src++;
688 else
690 if (! STRING_MULTIBYTE (string))
691 string = string_to_multibyte (string);
692 nbytes = buf - encode_terminal_src;
693 if (encode_terminal_src_size - nbytes < SBYTES (string))
695 encode_terminal_src =
696 xpalloc (encode_terminal_src, &encode_terminal_src_size,
697 (SBYTES (string)
698 - (encode_terminal_src_size - nbytes)),
699 -1, 1);
700 buf = encode_terminal_src + nbytes;
702 memcpy (buf, SDATA (string), SBYTES (string));
703 buf += SBYTES (string);
704 nchars += SCHARS (string);
707 src++;
710 if (nchars == 0)
712 coding->produced = 0;
713 return NULL;
716 nbytes = buf - encode_terminal_src;
717 coding->source = encode_terminal_src;
718 if (encode_terminal_dst_size == 0)
720 encode_terminal_dst = xrealloc (encode_terminal_dst,
721 encode_terminal_src_size);
722 encode_terminal_dst_size = encode_terminal_src_size;
724 coding->destination = encode_terminal_dst;
725 coding->dst_bytes = encode_terminal_dst_size;
726 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
727 /* coding->destination may have been reallocated. */
728 encode_terminal_dst = coding->destination;
729 encode_terminal_dst_size = coding->dst_bytes;
731 return (encode_terminal_dst);
736 /* An implementation of write_glyphs for termcap frames. */
738 static void
739 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
741 unsigned char *conversion_buffer;
742 struct coding_system *coding;
743 int n, stringlen;
745 struct tty_display_info *tty = FRAME_TTY (f);
747 tty_turn_off_insert (tty);
748 tty_hide_cursor (tty);
750 /* Don't dare write in last column of bottom line, if Auto-Wrap,
751 since that would scroll the whole frame on some terminals. */
753 if (AutoWrap (tty)
754 && curY (tty) + 1 == FRAME_LINES (f)
755 && (curX (tty) + len) == FRAME_COLS (f))
756 len --;
757 if (len <= 0)
758 return;
760 cmplus (tty, len);
762 /* If terminal_coding does any conversion, use it, otherwise use
763 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
764 because it always return 1 if the member src_multibyte is 1. */
765 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
766 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
767 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
768 the tail. */
769 coding->mode &= ~CODING_MODE_LAST_BLOCK;
771 for (stringlen = len; stringlen != 0; stringlen -= n)
773 /* Identify a run of glyphs with the same face. */
774 int face_id = string->face_id;
776 for (n = 1; n < stringlen; ++n)
777 if (string[n].face_id != face_id)
778 break;
780 /* Turn appearance modes of the face of the run on. */
781 tty_highlight_if_desired (tty);
782 turn_on_face (f, face_id);
784 if (n == stringlen)
785 /* This is the last run. */
786 coding->mode |= CODING_MODE_LAST_BLOCK;
787 conversion_buffer = encode_terminal_code (string, n, coding);
788 if (coding->produced > 0)
790 block_input ();
791 fwrite (conversion_buffer, 1, coding->produced, tty->output);
792 if (ferror (tty->output))
793 clearerr (tty->output);
794 if (tty->termscript)
795 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
796 unblock_input ();
798 string += n;
800 /* Turn appearance modes off. */
801 turn_off_face (f, face_id);
802 tty_turn_off_highlight (tty);
805 cmcheckmagic (tty);
808 #ifdef HAVE_GPM /* Only used by GPM code. */
810 static void
811 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
812 register int len, register int face_id)
814 unsigned char *conversion_buffer;
815 struct coding_system *coding;
817 struct tty_display_info *tty = FRAME_TTY (f);
819 tty_turn_off_insert (tty);
820 tty_hide_cursor (tty);
822 /* Don't dare write in last column of bottom line, if Auto-Wrap,
823 since that would scroll the whole frame on some terminals. */
825 if (AutoWrap (tty)
826 && curY (tty) + 1 == FRAME_LINES (f)
827 && (curX (tty) + len) == FRAME_COLS (f))
828 len --;
829 if (len <= 0)
830 return;
832 cmplus (tty, len);
834 /* If terminal_coding does any conversion, use it, otherwise use
835 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
836 because it always return 1 if the member src_multibyte is 1. */
837 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
838 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
839 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
840 the tail. */
841 coding->mode &= ~CODING_MODE_LAST_BLOCK;
843 /* Turn appearance modes of the face. */
844 tty_highlight_if_desired (tty);
845 turn_on_face (f, face_id);
847 coding->mode |= CODING_MODE_LAST_BLOCK;
848 conversion_buffer = encode_terminal_code (string, len, coding);
849 if (coding->produced > 0)
851 block_input ();
852 fwrite (conversion_buffer, 1, coding->produced, tty->output);
853 if (ferror (tty->output))
854 clearerr (tty->output);
855 if (tty->termscript)
856 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
857 unblock_input ();
860 /* Turn appearance modes off. */
861 turn_off_face (f, face_id);
862 tty_turn_off_highlight (tty);
864 cmcheckmagic (tty);
866 #endif
868 /* An implementation of insert_glyphs for termcap frames. */
870 static void
871 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
873 char *buf;
874 struct glyph *glyph = NULL;
875 unsigned char *conversion_buffer;
876 unsigned char space[1];
877 struct coding_system *coding;
879 struct tty_display_info *tty = FRAME_TTY (f);
881 if (tty->TS_ins_multi_chars)
883 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
884 OUTPUT1 (tty, buf);
885 xfree (buf);
886 if (start)
887 write_glyphs (f, start, len);
888 return;
891 tty_turn_on_insert (tty);
892 cmplus (tty, len);
894 if (! start)
895 space[0] = SPACEGLYPH;
897 /* If terminal_coding does any conversion, use it, otherwise use
898 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
899 because it always return 1 if the member src_multibyte is 1. */
900 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
901 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
902 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
903 the tail. */
904 coding->mode &= ~CODING_MODE_LAST_BLOCK;
906 while (len-- > 0)
908 OUTPUT1_IF (tty, tty->TS_ins_char);
909 if (!start)
911 conversion_buffer = space;
912 coding->produced = 1;
914 else
916 tty_highlight_if_desired (tty);
917 turn_on_face (f, start->face_id);
918 glyph = start;
919 ++start;
920 /* We must open sufficient space for a character which
921 occupies more than one column. */
922 while (len && CHAR_GLYPH_PADDING_P (*start))
924 OUTPUT1_IF (tty, tty->TS_ins_char);
925 start++, len--;
928 if (len <= 0)
929 /* This is the last glyph. */
930 coding->mode |= CODING_MODE_LAST_BLOCK;
932 conversion_buffer = encode_terminal_code (glyph, 1, coding);
935 if (coding->produced > 0)
937 block_input ();
938 fwrite (conversion_buffer, 1, coding->produced, tty->output);
939 if (ferror (tty->output))
940 clearerr (tty->output);
941 if (tty->termscript)
942 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
943 unblock_input ();
946 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
947 if (start)
949 turn_off_face (f, glyph->face_id);
950 tty_turn_off_highlight (tty);
954 cmcheckmagic (tty);
957 /* An implementation of delete_glyphs for termcap frames. */
959 static void
960 tty_delete_glyphs (struct frame *f, int n)
962 char *buf;
963 register int i;
965 struct tty_display_info *tty = FRAME_TTY (f);
967 if (tty->delete_in_insert_mode)
969 tty_turn_on_insert (tty);
971 else
973 tty_turn_off_insert (tty);
974 OUTPUT_IF (tty, tty->TS_delete_mode);
977 if (tty->TS_del_multi_chars)
979 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
980 OUTPUT1 (tty, buf);
981 xfree (buf);
983 else
984 for (i = 0; i < n; i++)
985 OUTPUT1 (tty, tty->TS_del_char);
986 if (!tty->delete_in_insert_mode)
987 OUTPUT_IF (tty, tty->TS_end_delete_mode);
990 /* An implementation of ins_del_lines for termcap frames. */
992 static void
993 tty_ins_del_lines (struct frame *f, int vpos, int n)
995 struct tty_display_info *tty = FRAME_TTY (f);
996 const char *multi =
997 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
998 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
999 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
1001 int i = eabs (n);
1002 char *buf;
1004 /* If the lines below the insertion are being pushed
1005 into the end of the window, this is the same as clearing;
1006 and we know the lines are already clear, since the matching
1007 deletion has already been done. So can ignore this. */
1008 /* If the lines below the deletion are blank lines coming
1009 out of the end of the window, don't bother,
1010 as there will be a matching inslines later that will flush them. */
1011 if (FRAME_SCROLL_REGION_OK (f)
1012 && vpos + i >= tty->specified_window)
1013 return;
1014 if (!FRAME_MEMORY_BELOW_FRAME (f)
1015 && vpos + i >= FRAME_LINES (f))
1016 return;
1018 if (multi)
1020 raw_cursor_to (f, vpos, 0);
1021 tty_background_highlight (tty);
1022 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1023 OUTPUT (tty, buf);
1024 xfree (buf);
1026 else if (single)
1028 raw_cursor_to (f, vpos, 0);
1029 tty_background_highlight (tty);
1030 while (--i >= 0)
1031 OUTPUT (tty, single);
1032 if (tty->TF_teleray)
1033 curX (tty) = 0;
1035 else
1037 tty_set_scroll_region (f, vpos, tty->specified_window);
1038 if (n < 0)
1039 raw_cursor_to (f, tty->specified_window - 1, 0);
1040 else
1041 raw_cursor_to (f, vpos, 0);
1042 tty_background_highlight (tty);
1043 while (--i >= 0)
1044 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1045 tty_set_scroll_region (f, 0, tty->specified_window);
1048 if (!FRAME_SCROLL_REGION_OK (f)
1049 && FRAME_MEMORY_BELOW_FRAME (f)
1050 && n < 0)
1052 cursor_to (f, FRAME_LINES (f) + n, 0);
1053 clear_to_end (f);
1057 /* Compute cost of sending "str", in characters,
1058 not counting any line-dependent padding. */
1061 string_cost (const char *str)
1063 cost = 0;
1064 if (str)
1065 tputs (str, 0, evalcost);
1066 return cost;
1069 /* Compute cost of sending "str", in characters,
1070 counting any line-dependent padding at one line. */
1072 static int
1073 string_cost_one_line (const char *str)
1075 cost = 0;
1076 if (str)
1077 tputs (str, 1, evalcost);
1078 return cost;
1081 /* Compute per line amount of line-dependent padding,
1082 in tenths of characters. */
1085 per_line_cost (const char *str)
1087 cost = 0;
1088 if (str)
1089 tputs (str, 0, evalcost);
1090 cost = - cost;
1091 if (str)
1092 tputs (str, 10, evalcost);
1093 return cost;
1096 /* char_ins_del_cost[n] is cost of inserting N characters.
1097 char_ins_del_cost[-n] is cost of deleting N characters.
1098 The length of this vector is based on max_frame_cols. */
1100 int *char_ins_del_vector;
1102 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1104 /* ARGSUSED */
1105 static void
1106 calculate_ins_del_char_costs (struct frame *f)
1108 struct tty_display_info *tty = FRAME_TTY (f);
1109 int ins_startup_cost, del_startup_cost;
1110 int ins_cost_per_char, del_cost_per_char;
1111 register int i;
1112 register int *p;
1114 if (tty->TS_ins_multi_chars)
1116 ins_cost_per_char = 0;
1117 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1119 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1120 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1122 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1123 + string_cost (tty->TS_end_insert_mode))) / 100;
1124 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1125 + string_cost_one_line (tty->TS_pad_inserted_char));
1127 else
1129 ins_startup_cost = 9999;
1130 ins_cost_per_char = 0;
1133 if (tty->TS_del_multi_chars)
1135 del_cost_per_char = 0;
1136 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1138 else if (tty->TS_del_char)
1140 del_startup_cost = (string_cost (tty->TS_delete_mode)
1141 + string_cost (tty->TS_end_delete_mode));
1142 if (tty->delete_in_insert_mode)
1143 del_startup_cost /= 2;
1144 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1146 else
1148 del_startup_cost = 9999;
1149 del_cost_per_char = 0;
1152 /* Delete costs are at negative offsets */
1153 p = &char_ins_del_cost (f)[0];
1154 for (i = FRAME_COLS (f); --i >= 0;)
1155 *--p = (del_startup_cost += del_cost_per_char);
1157 /* Doing nothing is free */
1158 p = &char_ins_del_cost (f)[0];
1159 *p++ = 0;
1161 /* Insert costs are at positive offsets */
1162 for (i = FRAME_COLS (f); --i >= 0;)
1163 *p++ = (ins_startup_cost += ins_cost_per_char);
1166 void
1167 calculate_costs (struct frame *frame)
1169 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1171 if (FRAME_TERMCAP_P (frame))
1173 struct tty_display_info *tty = FRAME_TTY (frame);
1174 register const char *f = (tty->TS_set_scroll_region
1175 ? tty->TS_set_scroll_region
1176 : tty->TS_set_scroll_region_1);
1178 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1180 tty->costs_set = 1;
1182 /* These variables are only used for terminal stuff. They are
1183 allocated once for the terminal frame of X-windows emacs, but not
1184 used afterwards.
1186 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1187 X turns off char_ins_del_ok. */
1189 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1190 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1191 < max_frame_cols)
1192 memory_full (SIZE_MAX);
1194 char_ins_del_vector =
1195 xrealloc (char_ins_del_vector,
1196 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1198 memset (char_ins_del_vector, 0,
1199 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1202 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1203 do_line_insertion_deletion_costs (frame,
1204 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1205 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1206 f, f, 1);
1207 else
1208 do_line_insertion_deletion_costs (frame,
1209 tty->TS_ins_line, tty->TS_ins_multi_lines,
1210 tty->TS_del_line, tty->TS_del_multi_lines,
1211 0, 0, 1);
1213 calculate_ins_del_char_costs (frame);
1215 /* Don't use TS_repeat if its padding is worse than sending the chars */
1216 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1217 tty->RPov = string_cost (tty->TS_repeat);
1218 else
1219 tty->RPov = FRAME_COLS (frame) * 2;
1221 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1225 struct fkey_table {
1226 const char *cap, *name;
1229 /* Termcap capability names that correspond directly to X keysyms.
1230 Some of these (marked "terminfo") aren't supplied by old-style
1231 (Berkeley) termcap entries. They're listed in X keysym order;
1232 except we put the keypad keys first, so that if they clash with
1233 other keys (as on the IBM PC keyboard) they get overridden.
1236 static const struct fkey_table keys[] =
1238 {"kh", "home"}, /* termcap */
1239 {"kl", "left"}, /* termcap */
1240 {"ku", "up"}, /* termcap */
1241 {"kr", "right"}, /* termcap */
1242 {"kd", "down"}, /* termcap */
1243 {"%8", "prior"}, /* terminfo */
1244 {"%5", "next"}, /* terminfo */
1245 {"@7", "end"}, /* terminfo */
1246 {"@1", "begin"}, /* terminfo */
1247 {"*6", "select"}, /* terminfo */
1248 {"%9", "print"}, /* terminfo */
1249 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1251 * "insert" --- see below
1253 {"&8", "undo"}, /* terminfo */
1254 {"%0", "redo"}, /* terminfo */
1255 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1256 {"@0", "find"}, /* terminfo */
1257 {"@2", "cancel"}, /* terminfo */
1258 {"%1", "help"}, /* terminfo */
1260 * "break" goes here, but can't be reliably intercepted with termcap
1262 {"&4", "reset"}, /* terminfo --- actually `restart' */
1264 * "system" and "user" --- no termcaps
1266 {"kE", "clearline"}, /* terminfo */
1267 {"kA", "insertline"}, /* terminfo */
1268 {"kL", "deleteline"}, /* terminfo */
1269 {"kI", "insertchar"}, /* terminfo */
1270 {"kD", "deletechar"}, /* terminfo */
1271 {"kB", "backtab"}, /* terminfo */
1273 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1275 {"@8", "kp-enter"}, /* terminfo */
1277 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1278 * "kp-multiply", "kp-add", "kp-separator",
1279 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1280 * --- no termcaps for any of these.
1282 {"K4", "kp-1"}, /* terminfo */
1284 * "kp-2" --- no termcap
1286 {"K5", "kp-3"}, /* terminfo */
1288 * "kp-4" --- no termcap
1290 {"K2", "kp-5"}, /* terminfo */
1292 * "kp-6" --- no termcap
1294 {"K1", "kp-7"}, /* terminfo */
1296 * "kp-8" --- no termcap
1298 {"K3", "kp-9"}, /* terminfo */
1300 * "kp-equal" --- no termcap
1302 {"k1", "f1"},
1303 {"k2", "f2"},
1304 {"k3", "f3"},
1305 {"k4", "f4"},
1306 {"k5", "f5"},
1307 {"k6", "f6"},
1308 {"k7", "f7"},
1309 {"k8", "f8"},
1310 {"k9", "f9"},
1312 {"&0", "S-cancel"}, /*shifted cancel key*/
1313 {"&9", "S-begin"}, /*shifted begin key*/
1314 {"*0", "S-find"}, /*shifted find key*/
1315 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1316 {"*4", "S-delete"}, /*shifted delete-character key*/
1317 {"*7", "S-end"}, /*shifted end key*/
1318 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1319 {"#1", "S-help"}, /*shifted help key*/
1320 {"#2", "S-home"}, /*shifted home key*/
1321 {"#3", "S-insert"}, /*shifted insert-character key*/
1322 {"#4", "S-left"}, /*shifted left-arrow key*/
1323 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1324 {"%c", "S-next"}, /*shifted next key*/
1325 {"%e", "S-prior"}, /*shifted previous key*/
1326 {"%f", "S-print"}, /*shifted print key*/
1327 {"%g", "S-redo"}, /*shifted redo key*/
1328 {"%i", "S-right"}, /*shifted right-arrow key*/
1329 {"!3", "S-undo"} /*shifted undo key*/
1332 #ifndef DOS_NT
1333 static char **term_get_fkeys_address;
1334 static KBOARD *term_get_fkeys_kboard;
1335 static Lisp_Object term_get_fkeys_1 (void);
1337 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1338 This function scans the termcap function key sequence entries, and
1339 adds entries to Vinput_decode_map for each function key it finds. */
1341 static void
1342 term_get_fkeys (char **address, KBOARD *kboard)
1344 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1345 errors during the call. The only errors should be from Fdefine_key
1346 when given a key sequence containing an invalid prefix key. If the
1347 termcap defines function keys which use a prefix that is already bound
1348 to a command by the default bindings, we should silently ignore that
1349 function key specification, rather than giving the user an error and
1350 refusing to run at all on such a terminal. */
1352 term_get_fkeys_address = address;
1353 term_get_fkeys_kboard = kboard;
1354 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1357 static Lisp_Object
1358 term_get_fkeys_1 (void)
1360 int i;
1362 char **address = term_get_fkeys_address;
1363 KBOARD *kboard = term_get_fkeys_kboard;
1365 /* This can happen if CANNOT_DUMP or with strange options. */
1366 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1367 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1369 for (i = 0; i < ARRAYELTS (keys); i++)
1371 char *sequence = tgetstr (keys[i].cap, address);
1372 if (sequence)
1373 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1374 Fmake_vector (make_number (1),
1375 intern (keys[i].name)));
1378 /* The uses of the "k0" capability are inconsistent; sometimes it
1379 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1380 We will attempt to politely accommodate both systems by testing for
1381 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1384 const char *k_semi = tgetstr ("k;", address);
1385 const char *k0 = tgetstr ("k0", address);
1386 const char *k0_name = "f10";
1388 if (k_semi)
1390 if (k0)
1391 /* Define f0 first, so that f10 takes precedence in case the
1392 key sequences happens to be the same. */
1393 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1394 Fmake_vector (make_number (1), intern ("f0")));
1395 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1396 Fmake_vector (make_number (1), intern ("f10")));
1398 else if (k0)
1399 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1400 Fmake_vector (make_number (1), intern (k0_name)));
1403 /* Set up cookies for numbered function keys above f10. */
1405 char fcap[3], fkey[4];
1407 fcap[0] = 'F'; fcap[2] = '\0';
1408 for (i = 11; i < 64; i++)
1410 if (i <= 19)
1411 fcap[1] = '1' + i - 11;
1412 else if (i <= 45)
1413 fcap[1] = 'A' + i - 20;
1414 else
1415 fcap[1] = 'a' + i - 46;
1418 char *sequence = tgetstr (fcap, address);
1419 if (sequence)
1421 sprintf (fkey, "f%d", i);
1422 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1423 Fmake_vector (make_number (1),
1424 intern (fkey)));
1431 * Various mappings to try and get a better fit.
1434 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1435 if (!tgetstr (cap1, address)) \
1437 char *sequence = tgetstr (cap2, address); \
1438 if (sequence) \
1439 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1440 Fmake_vector (make_number (1), \
1441 intern (sym))); \
1444 /* if there's no key_next keycap, map key_npage to `next' keysym */
1445 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1446 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1447 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1448 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1449 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1450 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1451 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1452 #undef CONDITIONAL_REASSIGN
1455 return Qnil;
1457 #endif /* not DOS_NT */
1460 /***********************************************************************
1461 Character Display Information
1462 ***********************************************************************/
1463 static void append_glyph (struct it *);
1464 static void append_composite_glyph (struct it *);
1465 static void produce_composite_glyph (struct it *);
1466 static void append_glyphless_glyph (struct it *, int, const char *);
1467 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1469 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1470 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1471 the character for which to produce glyphs; IT->face_id contains the
1472 character's face. Padding glyphs are appended if IT->c has a
1473 IT->pixel_width > 1. */
1475 static void
1476 append_glyph (struct it *it)
1478 struct glyph *glyph, *end;
1479 int i;
1481 eassert (it->glyph_row);
1482 glyph = (it->glyph_row->glyphs[it->area]
1483 + it->glyph_row->used[it->area]);
1484 end = it->glyph_row->glyphs[1 + it->area];
1486 /* If the glyph row is reversed, we need to prepend the glyph rather
1487 than append it. */
1488 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1490 struct glyph *g;
1491 int move_by = it->pixel_width;
1493 /* Make room for the new glyphs. */
1494 if (move_by > end - glyph) /* don't overstep end of this area */
1495 move_by = end - glyph;
1496 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1497 g[move_by] = *g;
1498 glyph = it->glyph_row->glyphs[it->area];
1499 end = glyph + move_by;
1502 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1503 right, even in the REVERSED_P case, since (a) all of its u.ch are
1504 identical, and (b) the PADDING_P flag needs to be set for the
1505 leftmost one, because we write to the terminal left-to-right. */
1506 for (i = 0;
1507 i < it->pixel_width && glyph < end;
1508 ++i)
1510 glyph->type = CHAR_GLYPH;
1511 glyph->pixel_width = 1;
1512 glyph->u.ch = it->char_to_display;
1513 glyph->face_id = it->face_id;
1514 glyph->padding_p = i > 0;
1515 glyph->charpos = CHARPOS (it->position);
1516 glyph->object = it->object;
1517 if (it->bidi_p)
1519 glyph->resolved_level = it->bidi_it.resolved_level;
1520 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1521 emacs_abort ();
1522 glyph->bidi_type = it->bidi_it.type;
1524 else
1526 glyph->resolved_level = 0;
1527 glyph->bidi_type = UNKNOWN_BT;
1530 ++it->glyph_row->used[it->area];
1531 ++glyph;
1535 /* For external use. */
1536 void
1537 tty_append_glyph (struct it *it)
1539 append_glyph (it);
1543 /* Produce glyphs for the display element described by IT. *IT
1544 specifies what we want to produce a glyph for (character, image, ...),
1545 and where in the glyph matrix we currently are (glyph row and hpos).
1546 produce_glyphs fills in output fields of *IT with information such as the
1547 pixel width and height of a character, and maybe output actual glyphs at
1548 the same time if IT->glyph_row is non-null. For an overview, see
1549 the explanation in dispextern.h, before the definition of the
1550 display_element_type enumeration.
1552 produce_glyphs also stores the result of glyph width, ascent
1553 etc. computations in *IT.
1555 IT->glyph_row may be null, in which case produce_glyphs does not
1556 actually fill in the glyphs. This is used in the move_* functions
1557 in xdisp.c for text width and height computations.
1559 Callers usually don't call produce_glyphs directly;
1560 instead they use the macro PRODUCE_GLYPHS. */
1562 void
1563 produce_glyphs (struct it *it)
1565 /* If a hook is installed, let it do the work. */
1567 /* Nothing but characters are supported on terminal frames. */
1568 eassert (it->what == IT_CHARACTER
1569 || it->what == IT_COMPOSITION
1570 || it->what == IT_STRETCH
1571 || it->what == IT_GLYPHLESS);
1573 if (it->what == IT_STRETCH)
1575 produce_stretch_glyph (it);
1576 goto done;
1579 if (it->what == IT_COMPOSITION)
1581 produce_composite_glyph (it);
1582 goto done;
1585 if (it->what == IT_GLYPHLESS)
1587 produce_glyphless_glyph (it, Qnil);
1588 goto done;
1591 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1593 it->pixel_width = it->nglyphs = 1;
1594 if (it->glyph_row)
1595 append_glyph (it);
1597 else if (it->char_to_display == '\n')
1598 it->pixel_width = it->nglyphs = 0;
1599 else if (it->char_to_display == '\t')
1601 int absolute_x = (it->current_x
1602 + it->continuation_lines_width);
1603 int next_tab_x
1604 = (((1 + absolute_x + it->tab_width - 1)
1605 / it->tab_width)
1606 * it->tab_width);
1607 int nspaces;
1609 /* If part of the TAB has been displayed on the previous line
1610 which is continued now, continuation_lines_width will have
1611 been incremented already by the part that fitted on the
1612 continued line. So, we will get the right number of spaces
1613 here. */
1614 nspaces = next_tab_x - absolute_x;
1616 if (it->glyph_row)
1618 int n = nspaces;
1620 it->char_to_display = ' ';
1621 it->pixel_width = it->len = 1;
1623 while (n--)
1624 append_glyph (it);
1627 it->pixel_width = nspaces;
1628 it->nglyphs = nspaces;
1630 else if (CHAR_BYTE8_P (it->char_to_display))
1632 /* Coming here means that we must send the raw 8-bit byte as is
1633 to the terminal. Although there's no way to know how many
1634 columns it occupies on a screen, it is a good assumption that
1635 a single byte code has 1-column width. */
1636 it->pixel_width = it->nglyphs = 1;
1637 if (it->glyph_row)
1638 append_glyph (it);
1640 else
1642 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1644 if (char_charset (it->char_to_display, charset_list, NULL))
1646 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1647 it->nglyphs = it->pixel_width;
1648 if (it->glyph_row)
1649 append_glyph (it);
1651 else
1653 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1655 eassert (it->what == IT_GLYPHLESS);
1656 produce_glyphless_glyph (it, acronym);
1660 done:
1661 /* Advance current_x by the pixel width as a convenience for
1662 the caller. */
1663 if (it->area == TEXT_AREA)
1664 it->current_x += it->pixel_width;
1665 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1666 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1669 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1670 Called from produce_composite_glyph for terminal frames if
1671 IT->glyph_row != NULL. IT->face_id contains the character's
1672 face. */
1674 static void
1675 append_composite_glyph (struct it *it)
1677 struct glyph *glyph;
1679 eassert (it->glyph_row);
1680 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1681 if (glyph < it->glyph_row->glyphs[1 + it->area])
1683 /* If the glyph row is reversed, we need to prepend the glyph
1684 rather than append it. */
1685 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1687 struct glyph *g;
1689 /* Make room for the new glyph. */
1690 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1691 g[1] = *g;
1692 glyph = it->glyph_row->glyphs[it->area];
1694 glyph->type = COMPOSITE_GLYPH;
1695 glyph->pixel_width = it->pixel_width;
1696 glyph->u.cmp.id = it->cmp_it.id;
1697 if (it->cmp_it.ch < 0)
1699 glyph->u.cmp.automatic = 0;
1700 glyph->u.cmp.id = it->cmp_it.id;
1702 else
1704 glyph->u.cmp.automatic = 1;
1705 glyph->u.cmp.id = it->cmp_it.id;
1706 glyph->slice.cmp.from = it->cmp_it.from;
1707 glyph->slice.cmp.to = it->cmp_it.to - 1;
1710 glyph->face_id = it->face_id;
1711 glyph->padding_p = 0;
1712 glyph->charpos = CHARPOS (it->position);
1713 glyph->object = it->object;
1714 if (it->bidi_p)
1716 glyph->resolved_level = it->bidi_it.resolved_level;
1717 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1718 emacs_abort ();
1719 glyph->bidi_type = it->bidi_it.type;
1721 else
1723 glyph->resolved_level = 0;
1724 glyph->bidi_type = UNKNOWN_BT;
1727 ++it->glyph_row->used[it->area];
1728 ++glyph;
1733 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1734 the composition. We simply produces components of the composition
1735 assuming that the terminal has a capability to layout/render it
1736 correctly. */
1738 static void
1739 produce_composite_glyph (struct it *it)
1741 if (it->cmp_it.ch < 0)
1743 struct composition *cmp = composition_table[it->cmp_it.id];
1745 it->pixel_width = cmp->width;
1747 else
1749 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1751 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1752 it->cmp_it.to, NULL);
1754 it->nglyphs = 1;
1755 if (it->glyph_row)
1756 append_composite_glyph (it);
1760 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1761 is a face ID to be used for the glyph. What is actually appended
1762 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1763 comes from it->nglyphs bytes). */
1765 static void
1766 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1768 struct glyph *glyph, *end;
1769 int i;
1771 eassert (it->glyph_row);
1772 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1773 end = it->glyph_row->glyphs[1 + it->area];
1775 /* If the glyph row is reversed, we need to prepend the glyph rather
1776 than append it. */
1777 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1779 struct glyph *g;
1780 int move_by = it->pixel_width;
1782 /* Make room for the new glyphs. */
1783 if (move_by > end - glyph) /* don't overstep end of this area */
1784 move_by = end - glyph;
1785 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1786 g[move_by] = *g;
1787 glyph = it->glyph_row->glyphs[it->area];
1788 end = glyph + move_by;
1791 if (glyph >= end)
1792 return;
1793 glyph->type = CHAR_GLYPH;
1794 glyph->pixel_width = 1;
1795 glyph->face_id = face_id;
1796 glyph->padding_p = 0;
1797 glyph->charpos = CHARPOS (it->position);
1798 glyph->object = it->object;
1799 if (it->bidi_p)
1801 glyph->resolved_level = it->bidi_it.resolved_level;
1802 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1803 emacs_abort ();
1804 glyph->bidi_type = it->bidi_it.type;
1806 else
1808 glyph->resolved_level = 0;
1809 glyph->bidi_type = UNKNOWN_BT;
1812 /* BIDI Note: we put the glyphs of characters left to right, even in
1813 the REVERSED_P case because we write to the terminal
1814 left-to-right. */
1815 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1817 if (i > 0)
1818 glyph[0] = glyph[-1];
1819 glyph->u.ch = str[i];
1820 ++it->glyph_row->used[it->area];
1821 ++glyph;
1825 /* Produce glyphs for a glyphless character for iterator IT.
1826 IT->glyphless_method specifies which method to use for displaying
1827 the character. See the description of enum
1828 glyphless_display_method in dispextern.h for the details.
1830 ACRONYM, if non-nil, is an acronym string for the character.
1832 The glyphs actually produced are of type CHAR_GLYPH. */
1834 static void
1835 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1837 int len, face_id = merge_glyphless_glyph_face (it);
1838 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1839 char const *str = " ";
1841 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1843 /* As there's no way to produce a thin space, we produce a space
1844 of canonical width. */
1845 len = 1;
1847 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1849 len = CHAR_WIDTH (it->c);
1850 if (len == 0)
1851 len = 1;
1852 else if (len > 4)
1853 len = 4;
1854 len = sprintf (buf, "[%.*s]", len, str);
1855 str = buf;
1857 else
1859 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1861 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1862 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1863 if (CONSP (acronym))
1864 acronym = XCDR (acronym);
1865 buf[0] = '[';
1866 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1867 for (len = 0; len < 6 && str[len] && ASCII_BYTE_P (str[len]); len++)
1868 buf[1 + len] = str[len];
1869 buf[1 + len] = ']';
1870 len += 2;
1872 else
1874 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1875 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1876 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1877 : sprintf (buf, "\\x%06X", it->c));
1879 str = buf;
1882 it->pixel_width = len;
1883 it->nglyphs = len;
1884 if (it->glyph_row)
1885 append_glyphless_glyph (it, face_id, str);
1889 /***********************************************************************
1890 Faces
1891 ***********************************************************************/
1893 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1894 one of the enumerators from enum no_color_bit, or a bit set built
1895 from them. Some display attributes may not be used together with
1896 color; the termcap capability `NC' specifies which ones. */
1898 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1899 (tty->TN_max_colors > 0 \
1900 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1901 : 1)
1903 /* Turn appearances of face FACE_ID on tty frame F on.
1904 FACE_ID is a realized face ID number, in the face cache. */
1906 static void
1907 turn_on_face (struct frame *f, int face_id)
1909 struct face *face = FACE_FROM_ID (f, face_id);
1910 unsigned long fg = face->foreground;
1911 unsigned long bg = face->background;
1912 struct tty_display_info *tty = FRAME_TTY (f);
1914 /* Use reverse video if the face specifies that.
1915 Do this first because TS_end_standout_mode may be the same
1916 as TS_exit_attribute_mode, which turns all appearances off. */
1917 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1918 && (inverse_video
1919 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1920 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1921 tty_toggle_highlight (tty);
1923 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1924 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1926 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1928 if (tty->TS_enter_italic_mode)
1929 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1930 else
1931 /* Italics mode is unavailable on many terminals. In that
1932 case, map slant to dimmed text; we want italic text to
1933 appear different and dimming is not otherwise used. */
1934 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1937 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1938 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1940 if (tty->TN_max_colors > 0)
1942 const char *ts;
1943 char *p;
1945 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1946 if (face_tty_specified_color (fg) && ts)
1948 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1949 OUTPUT (tty, p);
1950 xfree (p);
1953 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1954 if (face_tty_specified_color (bg) && ts)
1956 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1957 OUTPUT (tty, p);
1958 xfree (p);
1964 /* Turn off appearances of face FACE_ID on tty frame F. */
1966 static void
1967 turn_off_face (struct frame *f, int face_id)
1969 struct face *face = FACE_FROM_ID (f, face_id);
1970 struct tty_display_info *tty = FRAME_TTY (f);
1972 eassert (face != NULL);
1974 if (tty->TS_exit_attribute_mode)
1976 /* Capability "me" will turn off appearance modes double-bright,
1977 half-bright, reverse-video, standout, underline. It may or
1978 may not turn off alt-char-mode. */
1979 if (face->tty_bold_p
1980 || face->tty_italic_p
1981 || face->tty_reverse_p
1982 || face->tty_underline_p)
1984 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1985 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1986 tty->standout_mode = 0;
1989 else
1991 /* If we don't have "me" we can only have those appearances
1992 that have exit sequences defined. */
1993 if (face->tty_underline_p)
1994 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1997 /* Switch back to default colors. */
1998 if (tty->TN_max_colors > 0
1999 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
2000 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
2001 || (face->background != FACE_TTY_DEFAULT_COLOR
2002 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
2003 OUTPUT1_IF (tty, tty->TS_orig_pair);
2007 /* Return true if the terminal on frame F supports all of the
2008 capabilities in CAPS simultaneously. */
2010 bool
2011 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2013 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2014 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2015 return 0;
2017 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2018 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2019 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2020 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2021 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2023 /* We can do it! */
2024 return 1;
2027 /* Return non-zero if the terminal is capable to display colors. */
2029 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2030 0, 1, 0,
2031 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2033 TERMINAL can be a terminal object, a frame, or nil (meaning the
2034 selected frame's terminal). This function always returns nil if
2035 TERMINAL does not refer to a text terminal. */)
2036 (Lisp_Object terminal)
2038 struct terminal *t = get_tty_terminal (terminal, 0);
2039 if (!t)
2040 return Qnil;
2041 else
2042 return t->display_info.tty->TN_max_colors > 0 ? Qt : Qnil;
2045 /* Return the number of supported colors. */
2046 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2047 Stty_display_color_cells, 0, 1, 0,
2048 doc: /* Return the number of colors supported by the tty device TERMINAL.
2050 TERMINAL can be a terminal object, a frame, or nil (meaning the
2051 selected frame's terminal). This function always returns 0 if
2052 TERMINAL does not refer to a text terminal. */)
2053 (Lisp_Object terminal)
2055 struct terminal *t = get_tty_terminal (terminal, 0);
2056 if (!t)
2057 return make_number (0);
2058 else
2059 return make_number (t->display_info.tty->TN_max_colors);
2062 #ifndef DOS_NT
2064 /* Declare here rather than in the function, as in the rest of Emacs,
2065 to work around an HPUX compiler bug (?). See
2066 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2067 static int default_max_colors;
2068 static int default_max_pairs;
2069 static int default_no_color_video;
2070 static char *default_orig_pair;
2071 static char *default_set_foreground;
2072 static char *default_set_background;
2074 /* Save or restore the default color-related capabilities of this
2075 terminal. */
2076 static void
2077 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2080 if (save)
2082 dupstring (&default_orig_pair, tty->TS_orig_pair);
2083 dupstring (&default_set_foreground, tty->TS_set_foreground);
2084 dupstring (&default_set_background, tty->TS_set_background);
2085 default_max_colors = tty->TN_max_colors;
2086 default_max_pairs = tty->TN_max_pairs;
2087 default_no_color_video = tty->TN_no_color_video;
2089 else
2091 tty->TS_orig_pair = default_orig_pair;
2092 tty->TS_set_foreground = default_set_foreground;
2093 tty->TS_set_background = default_set_background;
2094 tty->TN_max_colors = default_max_colors;
2095 tty->TN_max_pairs = default_max_pairs;
2096 tty->TN_no_color_video = default_no_color_video;
2100 /* Setup one of the standard tty color schemes according to MODE.
2101 MODE's value is generally the number of colors which we want to
2102 support; zero means set up for the default capabilities, the ones
2103 we saw at init_tty time; -1 means turn off color support. */
2104 static void
2105 tty_setup_colors (struct tty_display_info *tty, int mode)
2107 /* Canonicalize all negative values of MODE. */
2108 if (mode < -1)
2109 mode = -1;
2111 switch (mode)
2113 case -1: /* no colors at all */
2114 tty->TN_max_colors = 0;
2115 tty->TN_max_pairs = 0;
2116 tty->TN_no_color_video = 0;
2117 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2118 break;
2119 case 0: /* default colors, if any */
2120 default:
2121 tty_default_color_capabilities (tty, 0);
2122 break;
2123 case 8: /* 8 standard ANSI colors */
2124 tty->TS_orig_pair = "\033[0m";
2125 #ifdef TERMINFO
2126 tty->TS_set_foreground = "\033[3%p1%dm";
2127 tty->TS_set_background = "\033[4%p1%dm";
2128 #else
2129 tty->TS_set_foreground = "\033[3%dm";
2130 tty->TS_set_background = "\033[4%dm";
2131 #endif
2132 tty->TN_max_colors = 8;
2133 tty->TN_max_pairs = 64;
2134 tty->TN_no_color_video = 0;
2135 break;
2139 void
2140 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2142 Lisp_Object tem, val;
2143 Lisp_Object color_mode;
2144 int mode;
2145 Lisp_Object tty_color_mode_alist
2146 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2148 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2149 val = CONSP (tem) ? XCDR (tem) : Qnil;
2151 if (INTEGERP (val))
2152 color_mode = val;
2153 else if (SYMBOLP (tty_color_mode_alist))
2155 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2156 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2158 else
2159 color_mode = Qnil;
2161 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2163 if (mode != tty->previous_color_mode)
2165 tty->previous_color_mode = mode;
2166 tty_setup_colors (tty , mode);
2167 /* This recomputes all the faces given the new color definitions. */
2168 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2172 #endif /* !DOS_NT */
2176 /* Return the tty display object specified by TERMINAL. */
2178 static struct terminal *
2179 get_tty_terminal (Lisp_Object terminal, bool throw)
2181 struct terminal *t = get_terminal (terminal, throw);
2183 if (t && t->type != output_termcap && t->type != output_msdos_raw)
2185 if (throw)
2186 error ("Device %d is not a termcap terminal device", t->id);
2187 else
2188 return NULL;
2191 return t;
2194 /* Return an active termcap device that uses the tty device with the
2195 given name.
2197 This function ignores suspended devices.
2199 Returns NULL if the named terminal device is not opened. */
2201 struct terminal *
2202 get_named_tty (const char *name)
2204 struct terminal *t;
2206 eassert (name);
2208 for (t = terminal_list; t; t = t->next_terminal)
2210 if ((t->type == output_termcap || t->type == output_msdos_raw)
2211 && !strcmp (t->display_info.tty->name, name)
2212 && TERMINAL_ACTIVE_P (t))
2213 return t;
2216 return 0;
2220 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2221 doc: /* Return the type of the tty device that TERMINAL uses.
2222 Returns nil if TERMINAL is not on a tty device.
2224 TERMINAL can be a terminal object, a frame, or nil (meaning the
2225 selected frame's terminal). */)
2226 (Lisp_Object terminal)
2228 struct terminal *t = get_terminal (terminal, 1);
2230 if (t->type != output_termcap && t->type != output_msdos_raw)
2231 return Qnil;
2233 if (t->display_info.tty->type)
2234 return build_string (t->display_info.tty->type);
2235 else
2236 return Qnil;
2239 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2240 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2242 TERMINAL can be a terminal object, a frame, or nil (meaning the
2243 selected frame's terminal). This function always returns nil if
2244 TERMINAL is not on a tty device. */)
2245 (Lisp_Object terminal)
2247 struct terminal *t = get_terminal (terminal, 1);
2249 if ((t->type != output_termcap && t->type != output_msdos_raw)
2250 || strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2251 return Qnil;
2252 else
2253 return Qt;
2256 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2257 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2258 This is used to override the terminfo data, for certain terminals that
2259 do not really do underlining, but say that they do. This function has
2260 no effect if used on a non-tty terminal.
2262 TERMINAL can be a terminal object, a frame or nil (meaning the
2263 selected frame's terminal). This function always returns nil if
2264 TERMINAL does not refer to a text terminal. */)
2265 (Lisp_Object terminal)
2267 struct terminal *t = get_terminal (terminal, 1);
2269 if (t->type == output_termcap)
2270 t->display_info.tty->TS_enter_underline_mode = 0;
2271 return Qnil;
2274 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2275 doc: /* Return the topmost terminal frame on TERMINAL.
2276 TERMINAL can be a terminal object, a frame or nil (meaning the
2277 selected frame's terminal). This function returns nil if TERMINAL
2278 does not refer to a text terminal. Otherwise, it returns the
2279 top-most frame on the text terminal. */)
2280 (Lisp_Object terminal)
2282 struct terminal *t = get_terminal (terminal, 1);
2284 if (t->type == output_termcap)
2285 return t->display_info.tty->top_frame;
2286 return Qnil;
2291 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2292 doc: /* Suspend the terminal device TTY.
2294 The device is restored to its default state, and Emacs ceases all
2295 access to the tty device. Frames that use the device are not deleted,
2296 but input is not read from them and if they change, their display is
2297 not updated.
2299 TTY may be a terminal object, a frame, or nil for the terminal device
2300 of the currently selected frame.
2302 This function runs `suspend-tty-functions' after suspending the
2303 device. The functions are run with one arg, the id of the suspended
2304 terminal device.
2306 `suspend-tty' does nothing if it is called on a device that is already
2307 suspended.
2309 A suspended tty may be resumed by calling `resume-tty' on it. */)
2310 (Lisp_Object tty)
2312 struct terminal *t = get_tty_terminal (tty, 1);
2313 FILE *f;
2315 if (!t)
2316 error ("Unknown tty device");
2318 f = t->display_info.tty->input;
2320 if (f)
2322 /* First run `suspend-tty-functions' and then clean up the tty
2323 state because `suspend-tty-functions' might need to change
2324 the tty state. */
2325 Lisp_Object args[2];
2326 args[0] = intern ("suspend-tty-functions");
2327 XSETTERMINAL (args[1], t);
2328 Frun_hook_with_args (2, args);
2330 reset_sys_modes (t->display_info.tty);
2331 delete_keyboard_wait_descriptor (fileno (f));
2333 #ifndef MSDOS
2334 fclose (f);
2335 if (f != t->display_info.tty->output)
2336 fclose (t->display_info.tty->output);
2337 #endif
2339 t->display_info.tty->input = 0;
2340 t->display_info.tty->output = 0;
2342 if (FRAMEP (t->display_info.tty->top_frame))
2343 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2347 /* Clear display hooks to prevent further output. */
2348 clear_tty_hooks (t);
2350 return Qnil;
2353 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2354 doc: /* Resume the previously suspended terminal device TTY.
2355 The terminal is opened and reinitialized. Frames that are on the
2356 suspended terminal are revived.
2358 It is an error to resume a terminal while another terminal is active
2359 on the same device.
2361 This function runs `resume-tty-functions' after resuming the terminal.
2362 The functions are run with one arg, the id of the resumed terminal
2363 device.
2365 `resume-tty' does nothing if it is called on a device that is not
2366 suspended.
2368 TTY may be a terminal object, a frame, or nil (meaning the selected
2369 frame's terminal). */)
2370 (Lisp_Object tty)
2372 struct terminal *t = get_tty_terminal (tty, 1);
2373 int fd;
2375 if (!t)
2376 error ("Unknown tty device");
2378 if (!t->display_info.tty->input)
2380 if (get_named_tty (t->display_info.tty->name))
2381 error ("Cannot resume display while another display is active on the same device");
2383 #ifdef MSDOS
2384 t->display_info.tty->output = stdout;
2385 t->display_info.tty->input = stdin;
2386 #else /* !MSDOS */
2387 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2388 t->display_info.tty->input = t->display_info.tty->output
2389 = fd < 0 ? 0 : fdopen (fd, "w+");
2391 if (! t->display_info.tty->input)
2393 int open_errno = errno;
2394 emacs_close (fd);
2395 report_file_errno ("Cannot reopen tty device",
2396 build_string (t->display_info.tty->name),
2397 open_errno);
2400 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2401 dissociate_if_controlling_tty (fd);
2402 #endif
2404 add_keyboard_wait_descriptor (fd);
2406 if (FRAMEP (t->display_info.tty->top_frame))
2408 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2409 int width, height;
2410 int old_height = FRAME_COLS (f);
2411 int old_width = FRAME_LINES (f);
2413 /* Check if terminal/window size has changed while the frame
2414 was suspended. */
2415 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2416 if (width != old_width || height != old_height)
2417 change_frame_size (f, width, height, 0, 0, 0, 0);
2418 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2421 set_tty_hooks (t);
2422 init_sys_modes (t->display_info.tty);
2425 /* Run `resume-tty-functions'. */
2426 Lisp_Object args[2];
2427 args[0] = intern ("resume-tty-functions");
2428 XSETTERMINAL (args[1], t);
2429 Frun_hook_with_args (2, args);
2433 set_tty_hooks (t);
2435 return Qnil;
2439 /***********************************************************************
2440 Mouse
2441 ***********************************************************************/
2443 #ifdef HAVE_GPM
2445 #ifndef HAVE_WINDOW_SYSTEM
2446 void
2447 term_mouse_moveto (int x, int y)
2449 /* TODO: how to set mouse position?
2450 const char *name;
2451 int fd;
2452 name = (const char *) ttyname (0);
2453 fd = emacs_open (name, O_WRONLY, 0);
2454 SOME_FUNCTION (x, y, fd);
2455 emacs_close (fd);
2456 last_mouse_x = x;
2457 last_mouse_y = y; */
2459 #endif /* HAVE_WINDOW_SYSTEM */
2461 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2462 void
2463 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2464 int start_hpos, int end_hpos,
2465 enum draw_glyphs_face draw)
2467 int nglyphs = end_hpos - start_hpos;
2468 struct frame *f = XFRAME (WINDOW_FRAME (w));
2469 struct tty_display_info *tty = FRAME_TTY (f);
2470 int face_id = tty->mouse_highlight.mouse_face_face_id;
2471 int save_x, save_y, pos_x, pos_y;
2473 if (end_hpos >= row->used[TEXT_AREA])
2474 nglyphs = row->used[TEXT_AREA] - start_hpos;
2476 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2477 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2479 /* Save current cursor co-ordinates. */
2480 save_y = curY (tty);
2481 save_x = curX (tty);
2482 cursor_to (f, pos_y, pos_x);
2484 if (draw == DRAW_MOUSE_FACE)
2485 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2486 nglyphs, face_id);
2487 else if (draw == DRAW_NORMAL_TEXT)
2488 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2490 cursor_to (f, save_y, save_x);
2493 static bool
2494 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2496 /* Has the mouse moved off the glyph it was on at the last sighting? */
2497 if (event->x != last_mouse_x || event->y != last_mouse_y)
2499 frame->mouse_moved = 1;
2500 note_mouse_highlight (frame, event->x, event->y);
2501 /* Remember which glyph we're now on. */
2502 last_mouse_x = event->x;
2503 last_mouse_y = event->y;
2504 return 1;
2506 return 0;
2509 /* Return the Time that corresponds to T. Wrap around on overflow. */
2510 static Time
2511 timeval_to_Time (struct timeval const *t)
2513 Time s_1000, ms;
2515 s_1000 = t->tv_sec;
2516 s_1000 *= 1000;
2517 ms = t->tv_usec / 1000;
2518 return s_1000 + ms;
2521 /* Return the current position of the mouse.
2523 Set *f to the frame the mouse is in, or zero if the mouse is in no
2524 Emacs frame. If it is set to zero, all the other arguments are
2525 garbage.
2527 Set *bar_window to Qnil, and *x and *y to the column and
2528 row of the character cell the mouse is over.
2530 Set *timeptr to the time the mouse was at the returned position.
2532 This clears mouse_moved until the next motion
2533 event arrives. */
2534 static void
2535 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2536 enum scroll_bar_part *part, Lisp_Object *x,
2537 Lisp_Object *y, Time *timeptr)
2539 struct timeval now;
2541 *fp = SELECTED_FRAME ();
2542 (*fp)->mouse_moved = 0;
2544 *bar_window = Qnil;
2545 *part = 0;
2547 XSETINT (*x, last_mouse_x);
2548 XSETINT (*y, last_mouse_y);
2549 gettimeofday(&now, 0);
2550 *timeptr = timeval_to_Time (&now);
2553 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2555 If the event is a button press, then note that we have grabbed
2556 the mouse. */
2558 static Lisp_Object
2559 term_mouse_click (struct input_event *result, Gpm_Event *event,
2560 struct frame *f)
2562 struct timeval now;
2563 int i, j;
2565 result->kind = GPM_CLICK_EVENT;
2566 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2568 if (event->buttons & j) {
2569 result->code = i; /* button number */
2570 break;
2573 gettimeofday(&now, 0);
2574 result->timestamp = timeval_to_Time (&now);
2576 if (event->type & GPM_UP)
2577 result->modifiers = up_modifier;
2578 else if (event->type & GPM_DOWN)
2579 result->modifiers = down_modifier;
2580 else
2581 result->modifiers = 0;
2583 if (event->type & GPM_SINGLE)
2584 result->modifiers |= click_modifier;
2586 if (event->type & GPM_DOUBLE)
2587 result->modifiers |= double_modifier;
2589 if (event->type & GPM_TRIPLE)
2590 result->modifiers |= triple_modifier;
2592 if (event->type & GPM_DRAG)
2593 result->modifiers |= drag_modifier;
2595 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2597 /* 1 << KG_SHIFT */
2598 if (event->modifiers & (1 << 0))
2599 result->modifiers |= shift_modifier;
2601 /* 1 << KG_CTRL */
2602 if (event->modifiers & (1 << 2))
2603 result->modifiers |= ctrl_modifier;
2605 /* 1 << KG_ALT || KG_ALTGR */
2606 if (event->modifiers & (1 << 3)
2607 || event->modifiers & (1 << 1))
2608 result->modifiers |= meta_modifier;
2611 XSETINT (result->x, event->x);
2612 XSETINT (result->y, event->y);
2613 XSETFRAME (result->frame_or_window, f);
2614 result->arg = Qnil;
2615 return Qnil;
2619 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2621 struct frame *f = XFRAME (tty->top_frame);
2622 struct input_event ie;
2623 bool do_help = 0;
2624 int count = 0;
2626 EVENT_INIT (ie);
2627 ie.kind = NO_EVENT;
2628 ie.arg = Qnil;
2630 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2631 previous_help_echo_string = help_echo_string;
2632 help_echo_string = Qnil;
2634 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2636 if (!term_mouse_movement (f, event))
2637 help_echo_string = previous_help_echo_string;
2639 /* If the contents of the global variable help_echo_string
2640 has changed, generate a HELP_EVENT. */
2641 if (!NILP (help_echo_string)
2642 || !NILP (previous_help_echo_string))
2643 do_help = 1;
2645 goto done;
2647 else {
2648 f->mouse_moved = 0;
2649 term_mouse_click (&ie, event, f);
2652 done:
2653 if (ie.kind != NO_EVENT)
2655 kbd_buffer_store_event_hold (&ie, hold_quit);
2656 count++;
2659 if (do_help
2660 && !(hold_quit && hold_quit->kind != NO_EVENT))
2662 Lisp_Object frame;
2664 if (f)
2665 XSETFRAME (frame, f);
2666 else
2667 frame = Qnil;
2669 gen_help_event (help_echo_string, frame, help_echo_window,
2670 help_echo_object, help_echo_pos);
2671 count++;
2674 return count;
2677 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2678 0, 0, 0,
2679 doc: /* Open a connection to Gpm.
2680 Gpm-mouse can only be activated for one tty at a time. */)
2681 (void)
2683 struct frame *f = SELECTED_FRAME ();
2684 struct tty_display_info *tty
2685 = ((f)->output_method == output_termcap
2686 ? (f)->terminal->display_info.tty : NULL);
2687 Gpm_Connect connection;
2689 if (!tty)
2690 error ("Gpm-mouse only works in the GNU/Linux console");
2691 if (gpm_tty == tty)
2692 return Qnil; /* Already activated, nothing to do. */
2693 if (gpm_tty)
2694 error ("Gpm-mouse can only be activated for one tty at a time");
2696 connection.eventMask = ~0;
2697 connection.defaultMask = ~GPM_HARD;
2698 connection.maxMod = ~0;
2699 connection.minMod = 0;
2700 gpm_zerobased = 1;
2702 if (Gpm_Open (&connection, 0) < 0)
2703 error ("Gpm-mouse failed to connect to the gpm daemon");
2704 else
2706 gpm_tty = tty;
2707 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2708 to generate SIGIOs. Apparently we need to call reset_sys_modes
2709 before calling init_sys_modes. */
2710 reset_sys_modes (tty);
2711 init_sys_modes (tty);
2712 add_gpm_wait_descriptor (gpm_fd);
2713 return Qnil;
2717 void
2718 close_gpm (int fd)
2720 if (fd >= 0)
2721 delete_gpm_wait_descriptor (fd);
2722 while (Gpm_Close()); /* close all the stack */
2723 gpm_tty = NULL;
2726 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2727 0, 0, 0,
2728 doc: /* Close a connection to Gpm. */)
2729 (void)
2731 struct frame *f = SELECTED_FRAME ();
2732 struct tty_display_info *tty
2733 = ((f)->output_method == output_termcap
2734 ? (f)->terminal->display_info.tty : NULL);
2736 if (!tty || gpm_tty != tty)
2737 return Qnil; /* Not activated on this terminal, nothing to do. */
2739 close_gpm (gpm_fd);
2740 return Qnil;
2742 #endif /* HAVE_GPM */
2745 /***********************************************************************
2746 Menus
2747 ***********************************************************************/
2749 #if !defined (MSDOS)
2751 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2753 However, unlike on MSDOS, where the menu text is drawn directly to
2754 the display video memory, on a TTY we use display_string (see
2755 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2756 the menu items into the frame's 'desired_matrix' glyph matrix, and
2757 then call update_frame_with_menu to deliver the results to the
2758 glass. The previous contents of the screen, in the form of the
2759 current_matrix, is stashed away, and used to restore screen
2760 contents when the menu selection changes or when the final
2761 selection is made and the menu should be popped down.
2763 The idea of this implementation was suggested by Gerd Moellmann. */
2765 #define TTYM_FAILURE -1
2766 #define TTYM_SUCCESS 1
2767 #define TTYM_NO_SELECT 2
2768 #define TTYM_IA_SELECT 3
2769 #define TTYM_NEXT 4
2770 #define TTYM_PREV 5
2772 /* These hold text of the current and the previous menu help messages. */
2773 static const char *menu_help_message, *prev_menu_help_message;
2774 /* Pane number and item number of the menu item which generated the
2775 last menu help message. */
2776 static int menu_help_paneno, menu_help_itemno;
2778 static Lisp_Object Qtty_menu_navigation_map, Qtty_menu_exit;
2779 static Lisp_Object Qtty_menu_prev_item, Qtty_menu_next_item;
2780 static Lisp_Object Qtty_menu_next_menu, Qtty_menu_prev_menu;
2781 static Lisp_Object Qtty_menu_select, Qtty_menu_ignore;
2782 static Lisp_Object Qtty_menu_mouse_movement;
2784 typedef struct tty_menu_struct
2786 int count;
2787 char **text;
2788 struct tty_menu_struct **submenu;
2789 int *panenumber; /* Also used as enabled flag. */
2790 ptrdiff_t allocated;
2791 int panecount;
2792 int width;
2793 const char **help_text;
2794 } tty_menu;
2796 /* Create a brand new menu structure. */
2798 static tty_menu *
2799 tty_menu_create (void)
2801 return xzalloc (sizeof *tty_menu_create ());
2804 /* Allocate some (more) memory for MENU ensuring that there is room for one
2805 more item. */
2807 static void
2808 tty_menu_make_room (tty_menu *menu)
2810 if (menu->allocated == menu->count)
2812 ptrdiff_t allocated = menu->allocated;
2813 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2814 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2815 menu->submenu = xrealloc (menu->submenu,
2816 allocated * sizeof *menu->submenu);
2817 menu->panenumber = xrealloc (menu->panenumber,
2818 allocated * sizeof *menu->panenumber);
2819 menu->help_text = xrealloc (menu->help_text,
2820 allocated * sizeof *menu->help_text);
2821 menu->allocated = allocated;
2825 /* Search the given menu structure for a given pane number. */
2827 static tty_menu *
2828 tty_menu_search_pane (tty_menu *menu, int pane)
2830 int i;
2831 tty_menu *try;
2833 for (i = 0; i < menu->count; i++)
2834 if (menu->submenu[i])
2836 if (pane == menu->panenumber[i])
2837 return menu->submenu[i];
2838 try = tty_menu_search_pane (menu->submenu[i], pane);
2839 if (try)
2840 return try;
2842 return (tty_menu *) 0;
2845 /* Determine how much screen space a given menu needs. */
2847 static void
2848 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2850 int i, h2, w2, maxsubwidth, maxheight;
2852 maxsubwidth = menu->width;
2853 maxheight = menu->count;
2854 for (i = 0; i < menu->count; i++)
2856 if (menu->submenu[i])
2858 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2859 if (w2 > maxsubwidth) maxsubwidth = w2;
2860 if (i + h2 > maxheight) maxheight = i + h2;
2863 *width = maxsubwidth;
2864 *height = maxheight;
2867 static void
2868 mouse_get_xy (int *x, int *y)
2870 struct frame *sf = SELECTED_FRAME ();
2871 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2872 enum scroll_bar_part part_dummy;
2873 Time time_dummy;
2875 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2876 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2877 &lisp_dummy, &part_dummy,
2878 &lmx, &lmy,
2879 &time_dummy);
2880 if (!NILP (lmx))
2882 *x = XINT (lmx);
2883 *y = XINT (lmy);
2887 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2888 (zero-based). */
2890 static void
2891 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2892 int mx, int my, int first_item, bool disp_help)
2894 int i, face, width, enabled, mousehere, row, col;
2895 struct frame *sf = SELECTED_FRAME ();
2896 struct tty_display_info *tty = FRAME_TTY (sf);
2897 /* Don't try to display more menu items than the console can display
2898 using the available screen lines. Exclude the echo area line, as
2899 it will be overwritten by the help-echo anyway. */
2900 int max_items = min (menu->count - first_item, FRAME_LINES (sf) - 1 - y);
2902 menu_help_message = NULL;
2904 width = menu->width;
2905 col = cursorX (tty);
2906 row = cursorY (tty);
2907 for (i = 0; i < max_items; i++)
2909 int max_width = width + 2; /* +2 for padding blanks on each side */
2910 int j = i + first_item;
2912 if (menu->submenu[j])
2913 max_width += 2; /* for displaying " >" after the item */
2914 enabled
2915 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2916 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2917 face = faces[enabled + mousehere * 2];
2918 /* Display the menu help string for the i-th menu item even if
2919 the menu item is currently disabled. That's what the GUI
2920 code does. */
2921 if (disp_help && enabled + mousehere * 2 >= 2)
2923 menu_help_message = menu->help_text[j];
2924 menu_help_paneno = pn - 1;
2925 menu_help_itemno = j;
2927 /* Take note of the coordinates of the active menu item, to
2928 display the cursor there. */
2929 if (mousehere)
2931 row = y + i;
2932 col = x;
2934 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2935 menu->submenu[j] != NULL);
2937 update_frame_with_menu (sf);
2938 cursor_to (sf, row, col);
2941 /* --------------------------- X Menu emulation ---------------------- */
2943 /* Create a new pane and place it on the outer-most level. */
2945 static int
2946 tty_menu_add_pane (tty_menu *menu, const char *txt)
2948 int len;
2949 const unsigned char *p;
2951 tty_menu_make_room (menu);
2952 menu->submenu[menu->count] = tty_menu_create ();
2953 menu->text[menu->count] = (char *)txt;
2954 menu->panenumber[menu->count] = ++menu->panecount;
2955 menu->help_text[menu->count] = NULL;
2956 menu->count++;
2958 /* Update the menu width, if necessary. */
2959 for (len = 0, p = (unsigned char *) txt; *p; )
2961 int ch_len;
2962 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
2964 len += CHAR_WIDTH (ch);
2965 p += ch_len;
2968 if (len > menu->width)
2969 menu->width = len;
2971 return menu->panecount;
2974 /* Create a new item in a menu pane. */
2976 static bool
2977 tty_menu_add_selection (tty_menu *menu, int pane,
2978 char *txt, bool enable, char const *help_text)
2980 int len;
2981 unsigned char *p;
2983 if (pane)
2985 menu = tty_menu_search_pane (menu, pane);
2986 if (! menu)
2987 return 0;
2989 tty_menu_make_room (menu);
2990 menu->submenu[menu->count] = (tty_menu *) 0;
2991 menu->text[menu->count] = txt;
2992 menu->panenumber[menu->count] = enable;
2993 menu->help_text[menu->count] = help_text;
2994 menu->count++;
2996 /* Update the menu width, if necessary. */
2997 for (len = 0, p = (unsigned char *) txt; *p; )
2999 int ch_len;
3000 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
3002 len += CHAR_WIDTH (ch);
3003 p += ch_len;
3006 if (len > menu->width)
3007 menu->width = len;
3009 return 1;
3012 /* Decide where the menu would be placed if requested at (X,Y). */
3014 static void
3015 tty_menu_locate (tty_menu *menu, int x, int y,
3016 int *ulx, int *uly, int *width, int *height)
3018 tty_menu_calc_size (menu, width, height);
3019 *ulx = x + 1;
3020 *uly = y;
3021 *width += 2;
3024 struct tty_menu_state
3026 struct glyph_matrix *screen_behind;
3027 tty_menu *menu;
3028 int pane;
3029 int x, y;
3032 /* Save away the contents of frame F's current frame matrix, and
3033 enable all its rows. Value is a glyph matrix holding the contents
3034 of F's current frame matrix with all its glyph rows enabled. */
3036 static struct glyph_matrix *
3037 save_and_enable_current_matrix (struct frame *f)
3039 int i;
3040 struct glyph_matrix *saved = xzalloc (sizeof *saved);
3041 saved->nrows = f->current_matrix->nrows;
3042 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
3044 for (i = 0; i < saved->nrows; ++i)
3046 struct glyph_row *from = f->current_matrix->rows + i;
3047 struct glyph_row *to = saved->rows + i;
3048 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3050 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
3051 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3052 to->used[TEXT_AREA] = from->used[TEXT_AREA];
3053 /* Make sure every row is enabled, or else update_frame will not
3054 redraw them. (Rows that are identical to what is already on
3055 screen will not be redrawn anyway.) */
3056 to->enabled_p = true;
3057 to->hash = from->hash;
3060 return saved;
3063 /* Restore the contents of frame F's desired frame matrix from SAVED,
3064 and free memory associated with SAVED. */
3066 static void
3067 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
3069 int i;
3071 for (i = 0; i < saved->nrows; ++i)
3073 struct glyph_row *from = saved->rows + i;
3074 struct glyph_row *to = f->desired_matrix->rows + i;
3075 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3077 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
3078 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3079 to->used[TEXT_AREA] = from->used[TEXT_AREA];
3080 to->enabled_p = from->enabled_p;
3081 to->hash = from->hash;
3085 static void
3086 free_saved_screen (struct glyph_matrix *saved)
3088 int i;
3090 if (!saved)
3091 return; /* Already freed! */
3093 for (i = 0; i < saved->nrows; ++i)
3095 struct glyph_row *from = saved->rows + i;
3097 xfree (from->glyphs[TEXT_AREA]);
3100 xfree (saved->rows);
3101 xfree (saved);
3104 /* Update the display of frame F from its saved contents. */
3105 static void
3106 screen_update (struct frame *f, struct glyph_matrix *mtx)
3108 restore_desired_matrix (f, mtx);
3109 update_frame_with_menu (f);
3112 typedef enum {
3113 MI_QUIT_MENU = -1,
3114 MI_CONTINUE = 0,
3115 MI_ITEM_SELECTED = 1,
3116 MI_NEXT_ITEM = 2,
3117 MI_PREV_ITEM = 3,
3118 MI_SCROLL_FORWARD = 4,
3119 MI_SCROLL_BACK = 5
3120 } mi_result;
3122 /* Read user input and return X and Y coordinates where that input
3123 puts us. We only consider mouse movement and click events, and
3124 keyboard movement commands; the rest are ignored. */
3125 static mi_result
3126 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3127 bool *first_time)
3129 if (*first_time)
3131 *first_time = false;
3132 sf->mouse_moved = 1;
3134 else
3136 Lisp_Object cmd;
3137 bool usable_input = 1;
3138 mi_result st = MI_CONTINUE;
3139 struct tty_display_info *tty = FRAME_TTY (sf);
3140 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3142 /* Signal the keyboard reading routines we are displaying a menu
3143 on this terminal. */
3144 tty->showing_menu = 1;
3145 /* We want mouse movements be reported by read_menu_command. */
3146 do_mouse_tracking = Qt;
3147 do {
3148 cmd = read_menu_command ();
3149 } while (NILP (cmd));
3150 tty->showing_menu = 0;
3151 do_mouse_tracking = saved_mouse_tracking;
3153 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3154 /* If some input switched frames under our feet, exit the
3155 menu, since the menu faces are no longer valid, and the
3156 menu is no longer relevant anyway. */
3157 || sf != SELECTED_FRAME ())
3158 return MI_QUIT_MENU;
3159 if (EQ (cmd, Qtty_menu_mouse_movement))
3160 mouse_get_xy (x, y);
3161 else if (EQ (cmd, Qtty_menu_next_menu))
3163 usable_input = 0;
3164 st = MI_NEXT_ITEM;
3166 else if (EQ (cmd, Qtty_menu_prev_menu))
3168 usable_input = 0;
3169 st = MI_PREV_ITEM;
3171 else if (EQ (cmd, Qtty_menu_next_item))
3173 if (*y < max_y)
3174 *y += 1;
3175 else
3176 st = MI_SCROLL_FORWARD;
3178 else if (EQ (cmd, Qtty_menu_prev_item))
3180 if (*y > min_y)
3181 *y -= 1;
3182 else
3183 st = MI_SCROLL_BACK;
3185 else if (EQ (cmd, Qtty_menu_select))
3186 st = MI_ITEM_SELECTED;
3187 else if (!EQ (cmd, Qtty_menu_ignore))
3188 usable_input = 0;
3189 if (usable_input)
3190 sf->mouse_moved = 1;
3191 return st;
3193 return MI_CONTINUE;
3196 /* Display menu, wait for user's response, and return that response. */
3197 static int
3198 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3199 int x0, int y0, char **txt,
3200 void (*help_callback)(char const *, int, int),
3201 bool kbd_navigation)
3203 struct tty_menu_state *state;
3204 int statecount, x, y, i;
3205 bool leave, onepane;
3206 int result IF_LINT (= 0);
3207 int title_faces[4]; /* Face to display the menu title. */
3208 int faces[4], buffers_num_deleted = 0;
3209 struct frame *sf = SELECTED_FRAME ();
3210 struct tty_display_info *tty = FRAME_TTY (sf);
3211 bool first_time;
3212 Lisp_Object selectface;
3213 int first_item = 0;
3214 int col, row;
3216 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3217 around the display. */
3218 if (x0 <= 0)
3219 x0 = 1;
3220 if (y0 <= 0)
3221 y0 = 1;
3223 state = alloca (menu->panecount * sizeof (struct tty_menu_state));
3224 memset (state, 0, sizeof (*state));
3225 faces[0]
3226 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3227 DEFAULT_FACE_ID, 1);
3228 faces[1]
3229 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3230 DEFAULT_FACE_ID, 1);
3231 selectface = intern ("tty-menu-selected-face");
3232 faces[2] = lookup_derived_face (sf, selectface,
3233 faces[0], 1);
3234 faces[3] = lookup_derived_face (sf, selectface,
3235 faces[1], 1);
3237 /* Make sure the menu title is always displayed with
3238 `tty-menu-selected-face', no matter where the mouse pointer is. */
3239 for (i = 0; i < 4; i++)
3240 title_faces[i] = faces[3];
3242 statecount = 1;
3244 /* Don't let the title for the "Buffers" popup menu include a
3245 digit (which is ugly).
3247 This is a terrible kludge, but I think the "Buffers" case is
3248 the only one where the title includes a number, so it doesn't
3249 seem to be necessary to make this more general. */
3250 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3252 menu->text[0][7] = '\0';
3253 buffers_num_deleted = 1;
3256 /* Force update of the current frame, so that the desired and the
3257 current matrices are identical. */
3258 update_frame_with_menu (sf);
3259 state[0].menu = menu;
3260 state[0].screen_behind = save_and_enable_current_matrix (sf);
3262 /* Display the menu title. We subtract 1 from x0 and y0 because we
3263 want to interpret them as zero-based column and row coordinates,
3264 and also because we want the first item of the menu, not its
3265 title, to appear at x0,y0. */
3266 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3268 /* Turn off the cursor. Otherwise it shows through the menu
3269 panes, which is ugly. */
3270 col = cursorX (tty);
3271 row = cursorY (tty);
3272 tty_hide_cursor (tty);
3274 if (buffers_num_deleted)
3275 menu->text[0][7] = ' ';
3276 onepane = menu->count == 1 && menu->submenu[0];
3277 if (onepane)
3279 menu->width = menu->submenu[0]->width;
3280 state[0].menu = menu->submenu[0];
3282 else
3284 state[0].menu = menu;
3286 state[0].x = x0 - 1;
3287 state[0].y = y0;
3288 state[0].pane = onepane;
3290 x = state[0].x;
3291 y = state[0].y;
3292 first_time = true;
3294 leave = 0;
3295 while (!leave)
3297 mi_result input_status;
3298 int min_y = state[0].y;
3299 int max_y = min (min_y + state[0].menu->count, FRAME_LINES (sf) - 1) - 1;
3301 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3302 if (input_status)
3304 leave = 1;
3305 switch (input_status)
3307 case MI_QUIT_MENU:
3308 /* Remove the last help-echo, so that it doesn't
3309 re-appear after "Quit". */
3310 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3311 result = TTYM_NO_SELECT;
3312 break;
3313 case MI_NEXT_ITEM:
3314 if (kbd_navigation)
3315 result = TTYM_NEXT;
3316 else
3317 leave = 0;
3318 break;
3319 case MI_PREV_ITEM:
3320 if (kbd_navigation)
3321 result = TTYM_PREV;
3322 else
3323 leave = 0;
3324 break;
3325 case MI_SCROLL_FORWARD:
3326 if (y - min_y == state[0].menu->count - 1 - first_item)
3328 y = min_y;
3329 first_item = 0;
3331 else
3332 first_item++;
3333 leave = 0;
3334 break;
3335 case MI_SCROLL_BACK:
3336 if (first_item == 0)
3338 y = max_y;
3339 first_item = state[0].menu->count - 1 - (y - min_y);
3341 else
3342 first_item--;
3343 leave = 0;
3344 break;
3345 default:
3346 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3347 break;
3350 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3352 sf->mouse_moved = 0;
3353 result = TTYM_IA_SELECT;
3354 for (i = 0; i < statecount; i++)
3355 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3357 int dy = y - state[i].y + first_item;
3358 if (0 <= dy && dy < state[i].menu->count)
3360 if (!state[i].menu->submenu[dy])
3362 if (state[i].menu->panenumber[dy])
3363 result = TTYM_SUCCESS;
3364 else
3365 result = TTYM_IA_SELECT;
3367 *pane = state[i].pane - 1;
3368 *selidx = dy;
3369 /* We hit some part of a menu, so drop extra menus that
3370 have been opened. That does not include an open and
3371 active submenu. */
3372 if (i != statecount - 2
3373 || state[i].menu->submenu[dy] != state[i + 1].menu)
3374 while (i != statecount - 1)
3376 statecount--;
3377 screen_update (sf, state[statecount].screen_behind);
3378 state[statecount].screen_behind = NULL;
3380 if (i == statecount - 1 && state[i].menu->submenu[dy])
3382 tty_menu_display (state[i].menu,
3383 state[i].x,
3384 state[i].y,
3385 state[i].pane,
3386 faces, x, y, first_item, 1);
3387 state[statecount].menu = state[i].menu->submenu[dy];
3388 state[statecount].pane = state[i].menu->panenumber[dy];
3389 state[statecount].screen_behind
3390 = save_and_enable_current_matrix (sf);
3391 state[statecount].x
3392 = state[i].x + state[i].menu->width + 2;
3393 state[statecount].y = y;
3394 statecount++;
3398 tty_menu_display (state[statecount - 1].menu,
3399 state[statecount - 1].x,
3400 state[statecount - 1].y,
3401 state[statecount - 1].pane,
3402 faces, x, y, first_item, 1);
3403 tty_hide_cursor (tty);
3404 fflush (tty->output);
3405 /* The call to display help-echo below will move the cursor,
3406 so remember its current position as computed by
3407 tty_menu_display. */
3408 col = cursorX (tty);
3409 row = cursorY (tty);
3412 /* Display the help-echo message for the currently-selected menu
3413 item. */
3414 if ((menu_help_message || prev_menu_help_message)
3415 && menu_help_message != prev_menu_help_message)
3417 help_callback (menu_help_message,
3418 menu_help_paneno, menu_help_itemno);
3419 /* Move the cursor to the beginning of the current menu
3420 item, so that screen readers and other accessibility aids
3421 know where the active region is. */
3422 cursor_to (sf, row, col);
3423 tty_hide_cursor (tty);
3424 fflush (tty->output);
3425 prev_menu_help_message = menu_help_message;
3429 sf->mouse_moved = 0;
3430 screen_update (sf, state[0].screen_behind);
3431 while (statecount--)
3432 free_saved_screen (state[statecount].screen_behind);
3433 tty_show_cursor (tty); /* Turn cursor back on. */
3434 fflush (tty->output);
3436 /* Clean up any mouse events that are waiting inside Emacs event queue.
3437 These events are likely to be generated before the menu was even
3438 displayed, probably because the user pressed and released the button
3439 (which invoked the menu) too quickly. If we don't remove these events,
3440 Emacs will process them after we return and surprise the user. */
3441 discard_mouse_events ();
3442 if (!kbd_buffer_events_waiting ())
3443 clear_input_pending ();
3444 return result;
3447 /* Dispose of a menu. */
3449 static void
3450 tty_menu_destroy (tty_menu *menu)
3452 int i;
3453 if (menu->allocated)
3455 for (i = 0; i < menu->count; i++)
3456 if (menu->submenu[i])
3457 tty_menu_destroy (menu->submenu[i]);
3458 xfree (menu->text);
3459 xfree (menu->submenu);
3460 xfree (menu->panenumber);
3461 xfree (menu->help_text);
3463 xfree (menu);
3464 menu_help_message = prev_menu_help_message = NULL;
3467 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3469 PANE is the pane number, and ITEM is the menu item number in
3470 the menu (currently not used). */
3472 static void
3473 tty_menu_help_callback (char const *help_string, int pane, int item)
3475 Lisp_Object *first_item;
3476 Lisp_Object pane_name;
3477 Lisp_Object menu_object;
3479 first_item = XVECTOR (menu_items)->contents;
3480 if (EQ (first_item[0], Qt))
3481 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3482 else if (EQ (first_item[0], Qquote))
3483 /* This shouldn't happen, see xmenu_show. */
3484 pane_name = empty_unibyte_string;
3485 else
3486 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3488 /* (menu-item MENU-NAME PANE-NUMBER) */
3489 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3490 show_help_echo (help_string ? build_string (help_string) : Qnil,
3491 Qnil, menu_object, make_number (item));
3494 static void
3495 tty_pop_down_menu (Lisp_Object arg)
3497 tty_menu *menu = XSAVE_POINTER (arg, 0);
3499 block_input ();
3500 tty_menu_destroy (menu);
3501 unblock_input ();
3504 /* Return the zero-based index of the last menu-bar item on frame F. */
3505 static int
3506 tty_menu_last_menubar_item (struct frame *f)
3508 int i = 0;
3510 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3511 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3513 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3515 while (i < ASIZE (items))
3517 Lisp_Object str;
3519 str = AREF (items, i + 1);
3520 if (NILP (str))
3521 break;
3522 i += 4;
3524 i -= 4; /* Went one too far! */
3526 return i;
3529 /* Find in frame F's menu bar the menu item that is next or previous
3530 to the item at X/Y, and return that item's position in X/Y. WHICH
3531 says which one--next or previous--item to look for. X and Y are
3532 measured in character cells. This should only be called on TTY
3533 frames. */
3534 static void
3535 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3537 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3538 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3540 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3541 int last_i = tty_menu_last_menubar_item (f);
3542 int i, prev_x;
3544 /* This loop assumes a single menu-bar line, and will fail to
3545 find an item if it is not in the first line. Note that
3546 make_lispy_event in keyboard.c makes the same assumption. */
3547 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3549 Lisp_Object pos, str;
3550 int ix;
3552 str = AREF (items, i + 1);
3553 pos = AREF (items, i + 3);
3554 if (NILP (str))
3555 return;
3556 ix = XINT (pos);
3557 if (ix <= *x
3558 /* We use <= so the blank between 2 items on a TTY is
3559 considered part of the previous item. */
3560 && *x <= ix + menu_item_width (SDATA (str)))
3562 /* Found current item. Now compute the X coordinate of
3563 the previous or next item. */
3564 if (which == TTYM_NEXT)
3566 if (i < last_i)
3567 *x = XINT (AREF (items, i + 4 + 3));
3568 else
3569 *x = 0; /* Wrap around to the first item. */
3571 else if (prev_x < 0)
3573 /* Wrap around to the last item. */
3574 *x = XINT (AREF (items, last_i + 3));
3576 else
3577 *x = prev_x;
3578 return;
3580 prev_x = ix;
3585 Lisp_Object
3586 tty_menu_show (struct frame *f, int x, int y, bool for_click, bool keymaps,
3587 Lisp_Object title, bool kbd_navigation, const char **error_name)
3589 tty_menu *menu;
3590 int pane, selidx, lpane, status;
3591 Lisp_Object entry, pane_prefix;
3592 char *datap;
3593 int ulx, uly, width, height;
3594 int item_x, item_y;
3595 int dispwidth, dispheight;
3596 int i, j, lines, maxlines;
3597 int maxwidth;
3598 ptrdiff_t specpdl_count;
3600 eassert (FRAME_TERMCAP_P (f));
3602 *error_name = 0;
3603 if (menu_items_n_panes == 0)
3604 return Qnil;
3606 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3608 *error_name = "Empty menu";
3609 return Qnil;
3612 /* Make the menu on that window. */
3613 menu = tty_menu_create ();
3614 if (menu == NULL)
3616 *error_name = "Can't create menu";
3617 return Qnil;
3620 /* Don't GC while we prepare and show the menu, because we give the
3621 menu functions pointers to the contents of strings. */
3622 specpdl_count = inhibit_garbage_collection ();
3624 /* Adjust coordinates to be root-window-relative. */
3625 item_x = x += f->left_pos;
3626 item_y = y += f->top_pos;
3628 /* Create all the necessary panes and their items. */
3629 maxwidth = maxlines = lines = i = 0;
3630 lpane = TTYM_FAILURE;
3631 while (i < menu_items_used)
3633 if (EQ (AREF (menu_items, i), Qt))
3635 /* Create a new pane. */
3636 Lisp_Object pane_name, prefix;
3637 const char *pane_string;
3639 maxlines = max (maxlines, lines);
3640 lines = 0;
3641 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3642 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3643 pane_string = (NILP (pane_name)
3644 ? "" : SSDATA (pane_name));
3645 if (keymaps && !NILP (prefix))
3646 pane_string++;
3648 lpane = tty_menu_add_pane (menu, pane_string);
3649 if (lpane == TTYM_FAILURE)
3651 tty_menu_destroy (menu);
3652 *error_name = "Can't create pane";
3653 entry = Qnil;
3654 goto tty_menu_end;
3656 i += MENU_ITEMS_PANE_LENGTH;
3658 /* Find the width of the widest item in this pane. */
3659 j = i;
3660 while (j < menu_items_used)
3662 Lisp_Object item;
3663 item = AREF (menu_items, j);
3664 if (EQ (item, Qt))
3665 break;
3666 if (NILP (item))
3668 j++;
3669 continue;
3671 width = SBYTES (item);
3672 if (width > maxwidth)
3673 maxwidth = width;
3675 j += MENU_ITEMS_ITEM_LENGTH;
3678 /* Ignore a nil in the item list.
3679 It's meaningful only for dialog boxes. */
3680 else if (EQ (AREF (menu_items, i), Qquote))
3681 i += 1;
3682 else
3684 /* Create a new item within current pane. */
3685 Lisp_Object item_name, enable, descrip, help;
3686 char *item_data;
3687 char const *help_string;
3689 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3690 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3691 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3692 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3693 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3695 if (!NILP (descrip))
3697 /* If alloca is fast, use that to make the space,
3698 to reduce gc needs. */
3699 item_data = (char *) alloca (maxwidth + SBYTES (descrip) + 1);
3700 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3701 for (j = SCHARS (item_name); j < maxwidth; j++)
3702 item_data[j] = ' ';
3703 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3704 item_data[j + SBYTES (descrip)] = 0;
3706 else
3707 item_data = SSDATA (item_name);
3709 if (lpane == TTYM_FAILURE
3710 || (! tty_menu_add_selection (menu, lpane, item_data,
3711 !NILP (enable), help_string)))
3713 tty_menu_destroy (menu);
3714 *error_name = "Can't add selection to menu";
3715 entry = Qnil;
3716 goto tty_menu_end;
3718 i += MENU_ITEMS_ITEM_LENGTH;
3719 lines++;
3723 maxlines = max (maxlines, lines);
3725 /* All set and ready to fly. */
3726 dispwidth = f->text_cols;
3727 dispheight = f->text_lines;
3728 x = min (x, dispwidth);
3729 y = min (y, dispheight);
3730 x = max (x, 1);
3731 y = max (y, 1);
3732 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3733 if (ulx + width > dispwidth)
3735 x -= (ulx + width) - dispwidth;
3736 ulx = dispwidth - width;
3738 if (uly + height > dispheight)
3740 y -= (uly + height) - dispheight;
3741 uly = dispheight - height;
3744 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3746 /* Move the menu away of the echo area, to avoid overwriting the
3747 menu with help echo messages or vice versa. */
3748 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3750 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3751 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3753 else
3755 y -= 2;
3756 uly -= 2;
3760 if (ulx < 0) x -= ulx;
3761 if (uly < 0) y -= uly;
3763 #if 0
3764 /* This code doesn't make sense on a TTY, since it can easily annul
3765 the adjustments above that carefully avoid truncation of the menu
3766 items. I think it was written to fix some problem that only
3767 happens on X11. */
3768 if (! for_click)
3770 /* If position was not given by a mouse click, adjust so upper left
3771 corner of the menu as a whole ends up at given coordinates. This
3772 is what x-popup-menu says in its documentation. */
3773 x += width / 2;
3774 y += 1.5 * height / (maxlines + 2);
3776 #endif
3778 pane = selidx = 0;
3780 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3782 specbind (Qoverriding_terminal_local_map,
3783 Fsymbol_value (Qtty_menu_navigation_map));
3784 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3785 tty_menu_help_callback, kbd_navigation);
3786 entry = pane_prefix = Qnil;
3788 switch (status)
3790 case TTYM_SUCCESS:
3791 /* Find the item number SELIDX in pane number PANE. */
3792 i = 0;
3793 while (i < menu_items_used)
3795 if (EQ (AREF (menu_items, i), Qt))
3797 if (pane == 0)
3798 pane_prefix
3799 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3800 pane--;
3801 i += MENU_ITEMS_PANE_LENGTH;
3803 else
3805 if (pane == -1)
3807 if (selidx == 0)
3809 entry
3810 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3811 if (keymaps != 0)
3813 entry = Fcons (entry, Qnil);
3814 if (!NILP (pane_prefix))
3815 entry = Fcons (pane_prefix, entry);
3817 break;
3819 selidx--;
3821 i += MENU_ITEMS_ITEM_LENGTH;
3824 break;
3826 case TTYM_NEXT:
3827 case TTYM_PREV:
3828 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3829 entry = Fcons (make_number (item_x), make_number (item_y));
3830 break;
3832 case TTYM_FAILURE:
3833 *error_name = "Can't activate menu";
3834 case TTYM_IA_SELECT:
3835 break;
3836 case TTYM_NO_SELECT:
3837 /* If the selected frame was changed while we displayed a menu,
3838 throw to top level in order to undo any temporary settings
3839 made by TTY menu code. */
3840 if (f != SELECTED_FRAME ())
3841 Ftop_level ();
3842 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3843 the menu was invoked with a mouse event as POSITION). */
3844 if (! for_click)
3845 Fsignal (Qquit, Qnil);
3846 break;
3849 tty_menu_end:
3851 unbind_to (specpdl_count, Qnil);
3852 return entry;
3855 #endif /* !MSDOS */
3858 #ifndef MSDOS
3859 /***********************************************************************
3860 Initialization
3861 ***********************************************************************/
3863 /* Initialize the tty-dependent part of frame F. The frame must
3864 already have its device initialized. */
3866 void
3867 create_tty_output (struct frame *f)
3869 struct tty_output *t = xzalloc (sizeof *t);
3871 eassert (FRAME_TERMCAP_P (f));
3873 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3875 f->output_data.tty = t;
3878 /* Delete frame F's face cache, and its tty-dependent part. */
3880 static void
3881 tty_free_frame_resources (struct frame *f)
3883 eassert (FRAME_TERMCAP_P (f));
3884 free_frame_faces (f);
3885 xfree (f->output_data.tty);
3888 #else /* MSDOS */
3890 /* Delete frame F's face cache. */
3892 static void
3893 tty_free_frame_resources (struct frame *f)
3895 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3896 free_frame_faces (f);
3898 #endif /* MSDOS */
3900 /* Reset the hooks in TERMINAL. */
3902 static void
3903 clear_tty_hooks (struct terminal *terminal)
3905 terminal->rif = 0;
3906 terminal->cursor_to_hook = 0;
3907 terminal->raw_cursor_to_hook = 0;
3908 terminal->clear_to_end_hook = 0;
3909 terminal->clear_frame_hook = 0;
3910 terminal->clear_end_of_line_hook = 0;
3911 terminal->ins_del_lines_hook = 0;
3912 terminal->insert_glyphs_hook = 0;
3913 terminal->write_glyphs_hook = 0;
3914 terminal->delete_glyphs_hook = 0;
3915 terminal->ring_bell_hook = 0;
3916 terminal->reset_terminal_modes_hook = 0;
3917 terminal->set_terminal_modes_hook = 0;
3918 terminal->update_begin_hook = 0;
3919 terminal->update_end_hook = 0;
3920 terminal->set_terminal_window_hook = 0;
3921 terminal->mouse_position_hook = 0;
3922 terminal->frame_rehighlight_hook = 0;
3923 terminal->frame_raise_lower_hook = 0;
3924 terminal->fullscreen_hook = 0;
3925 terminal->set_vertical_scroll_bar_hook = 0;
3926 terminal->condemn_scroll_bars_hook = 0;
3927 terminal->redeem_scroll_bar_hook = 0;
3928 terminal->judge_scroll_bars_hook = 0;
3929 terminal->read_socket_hook = 0;
3930 terminal->frame_up_to_date_hook = 0;
3932 /* Leave these two set, or suspended frames are not deleted
3933 correctly. */
3934 terminal->delete_frame_hook = &tty_free_frame_resources;
3935 terminal->delete_terminal_hook = &delete_tty;
3938 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3940 static void
3941 set_tty_hooks (struct terminal *terminal)
3943 terminal->cursor_to_hook = &tty_cursor_to;
3944 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3945 terminal->clear_to_end_hook = &tty_clear_to_end;
3946 terminal->clear_frame_hook = &tty_clear_frame;
3947 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3948 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3949 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3950 terminal->write_glyphs_hook = &tty_write_glyphs;
3951 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3952 terminal->ring_bell_hook = &tty_ring_bell;
3953 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3954 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3955 terminal->update_end_hook = &tty_update_end;
3956 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3957 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3958 terminal->delete_frame_hook = &tty_free_frame_resources;
3959 terminal->delete_terminal_hook = &delete_tty;
3960 /* Other hooks are NULL by default. */
3963 /* If FD is the controlling terminal, drop it. */
3964 static void
3965 dissociate_if_controlling_tty (int fd)
3967 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3968 so dissociate it by invoking setsid. */
3969 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3971 #ifdef TIOCNOTTY
3972 /* setsid failed, presumably because Emacs is already a process
3973 group leader. Fall back on the obsolescent way to dissociate
3974 a controlling tty. */
3975 sigset_t oldset;
3976 block_tty_out_signal (&oldset);
3977 ioctl (fd, TIOCNOTTY, 0);
3978 unblock_tty_out_signal (&oldset);
3979 #endif
3983 /* Create a termcap display on the tty device with the given name and
3984 type.
3986 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3987 Otherwise NAME should be a path to the tty device file,
3988 e.g. "/dev/pts/7".
3990 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3992 If MUST_SUCCEED is true, then all errors are fatal. */
3994 struct terminal *
3995 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3997 char *area;
3998 char **address = &area;
3999 int status;
4000 struct tty_display_info *tty = NULL;
4001 struct terminal *terminal = NULL;
4002 sigset_t oldset;
4003 bool ctty = false; /* True if asked to open controlling tty. */
4005 if (!terminal_type)
4006 maybe_fatal (must_succeed, 0,
4007 "Unknown terminal type",
4008 "Unknown terminal type");
4010 if (name == NULL)
4011 name = DEV_TTY;
4012 if (!strcmp (name, DEV_TTY))
4013 ctty = 1;
4015 /* If we already have a terminal on the given device, use that. If
4016 all such terminals are suspended, create a new one instead. */
4017 /* XXX Perhaps this should be made explicit by having init_tty
4018 always create a new terminal and separating terminal and frame
4019 creation on Lisp level. */
4020 terminal = get_named_tty (name);
4021 if (terminal)
4022 return terminal;
4024 terminal = create_terminal (output_termcap, NULL);
4025 #ifdef MSDOS
4026 if (been_here > 0)
4027 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
4028 name, "");
4029 been_here = 1;
4030 tty = &the_only_display_info;
4031 #else
4032 tty = xzalloc (sizeof *tty);
4033 #endif
4034 tty->top_frame = Qnil;
4035 tty->next = tty_list;
4036 tty_list = tty;
4038 terminal->display_info.tty = tty;
4039 tty->terminal = terminal;
4041 tty->Wcm = xmalloc (sizeof *tty->Wcm);
4042 Wcm_clear (tty);
4044 encode_terminal_src_size = 0;
4045 encode_terminal_dst_size = 0;
4048 #ifndef DOS_NT
4049 set_tty_hooks (terminal);
4052 /* Open the terminal device. */
4054 /* If !ctty, don't recognize it as our controlling terminal, and
4055 don't make it the controlling tty if we don't have one now.
4057 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
4058 defined on Hurd. On other systems, we need to explicitly
4059 dissociate ourselves from the controlling tty when we want to
4060 open a frame on the same terminal. */
4061 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
4062 int fd = emacs_open (name, flags, 0);
4063 tty->input = tty->output =
4064 ((fd < 0 || ! isatty (fd))
4065 ? NULL
4066 : fdopen (fd, "w+"));
4068 if (! tty->input)
4070 char const *diagnostic
4071 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
4072 emacs_close (fd);
4073 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4076 tty->name = xstrdup (name);
4077 terminal->name = xstrdup (name);
4079 if (!O_IGNORE_CTTY && !ctty)
4080 dissociate_if_controlling_tty (fd);
4083 tty->type = xstrdup (terminal_type);
4085 add_keyboard_wait_descriptor (fileno (tty->input));
4087 Wcm_clear (tty);
4089 /* On some systems, tgetent tries to access the controlling
4090 terminal. */
4091 block_tty_out_signal (&oldset);
4092 status = tgetent (tty->termcap_term_buffer, terminal_type);
4093 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4094 emacs_abort ();
4095 unblock_tty_out_signal (&oldset);
4097 if (status < 0)
4099 #ifdef TERMINFO
4100 maybe_fatal (must_succeed, terminal,
4101 "Cannot open terminfo database file",
4102 "Cannot open terminfo database file");
4103 #else
4104 maybe_fatal (must_succeed, terminal,
4105 "Cannot open termcap database file",
4106 "Cannot open termcap database file");
4107 #endif
4109 if (status == 0)
4111 maybe_fatal (must_succeed, terminal,
4112 "Terminal type %s is not defined",
4113 "Terminal type %s is not defined.\n\
4114 If that is not the actual type of terminal you have,\n\
4115 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4116 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4117 #ifdef TERMINFO
4118 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4119 #else
4120 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4121 #endif
4122 terminal_type);
4125 area = tty->termcap_strings_buffer;
4126 tty->TS_ins_line = tgetstr ("al", address);
4127 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4128 tty->TS_bell = tgetstr ("bl", address);
4129 BackTab (tty) = tgetstr ("bt", address);
4130 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4131 tty->TS_clr_line = tgetstr ("ce", address);
4132 tty->TS_clr_frame = tgetstr ("cl", address);
4133 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4134 AbsPosition (tty) = tgetstr ("cm", address);
4135 CR (tty) = tgetstr ("cr", address);
4136 tty->TS_set_scroll_region = tgetstr ("cs", address);
4137 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4138 RowPosition (tty) = tgetstr ("cv", address);
4139 tty->TS_del_char = tgetstr ("dc", address);
4140 tty->TS_del_multi_chars = tgetstr ("DC", address);
4141 tty->TS_del_line = tgetstr ("dl", address);
4142 tty->TS_del_multi_lines = tgetstr ("DL", address);
4143 tty->TS_delete_mode = tgetstr ("dm", address);
4144 tty->TS_end_delete_mode = tgetstr ("ed", address);
4145 tty->TS_end_insert_mode = tgetstr ("ei", address);
4146 Home (tty) = tgetstr ("ho", address);
4147 tty->TS_ins_char = tgetstr ("ic", address);
4148 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4149 tty->TS_insert_mode = tgetstr ("im", address);
4150 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4151 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4152 tty->TS_keypad_mode = tgetstr ("ks", address);
4153 LastLine (tty) = tgetstr ("ll", address);
4154 Right (tty) = tgetstr ("nd", address);
4155 Down (tty) = tgetstr ("do", address);
4156 if (!Down (tty))
4157 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4158 if (tgetflag ("bs"))
4159 Left (tty) = "\b"; /* Can't possibly be longer! */
4160 else /* (Actually, "bs" is obsolete...) */
4161 Left (tty) = tgetstr ("le", address);
4162 if (!Left (tty))
4163 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4164 tty->TS_pad_char = tgetstr ("pc", address);
4165 tty->TS_repeat = tgetstr ("rp", address);
4166 tty->TS_end_standout_mode = tgetstr ("se", address);
4167 tty->TS_fwd_scroll = tgetstr ("sf", address);
4168 tty->TS_standout_mode = tgetstr ("so", address);
4169 tty->TS_rev_scroll = tgetstr ("sr", address);
4170 tty->Wcm->cm_tab = tgetstr ("ta", address);
4171 tty->TS_end_termcap_modes = tgetstr ("te", address);
4172 tty->TS_termcap_modes = tgetstr ("ti", address);
4173 Up (tty) = tgetstr ("up", address);
4174 tty->TS_visible_bell = tgetstr ("vb", address);
4175 tty->TS_cursor_normal = tgetstr ("ve", address);
4176 tty->TS_cursor_visible = tgetstr ("vs", address);
4177 tty->TS_cursor_invisible = tgetstr ("vi", address);
4178 tty->TS_set_window = tgetstr ("wi", address);
4180 tty->TS_enter_underline_mode = tgetstr ("us", address);
4181 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4182 tty->TS_enter_bold_mode = tgetstr ("md", address);
4183 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4184 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4185 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4186 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4187 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4188 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4190 MultiUp (tty) = tgetstr ("UP", address);
4191 MultiDown (tty) = tgetstr ("DO", address);
4192 MultiLeft (tty) = tgetstr ("LE", address);
4193 MultiRight (tty) = tgetstr ("RI", address);
4195 /* SVr4/ANSI color support. If "op" isn't available, don't support
4196 color because we can't switch back to the default foreground and
4197 background. */
4198 tty->TS_orig_pair = tgetstr ("op", address);
4199 if (tty->TS_orig_pair)
4201 tty->TS_set_foreground = tgetstr ("AF", address);
4202 tty->TS_set_background = tgetstr ("AB", address);
4203 if (!tty->TS_set_foreground)
4205 /* SVr4. */
4206 tty->TS_set_foreground = tgetstr ("Sf", address);
4207 tty->TS_set_background = tgetstr ("Sb", address);
4210 tty->TN_max_colors = tgetnum ("Co");
4211 tty->TN_max_pairs = tgetnum ("pa");
4213 tty->TN_no_color_video = tgetnum ("NC");
4214 if (tty->TN_no_color_video == -1)
4215 tty->TN_no_color_video = 0;
4218 tty_default_color_capabilities (tty, 1);
4220 MagicWrap (tty) = tgetflag ("xn");
4221 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4222 the former flag imply the latter. */
4223 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4224 tty->memory_below_frame = tgetflag ("db");
4225 tty->TF_hazeltine = tgetflag ("hz");
4226 tty->must_write_spaces = tgetflag ("in");
4227 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4228 tty->TF_insmode_motion = tgetflag ("mi");
4229 tty->TF_standout_motion = tgetflag ("ms");
4230 tty->TF_underscore = tgetflag ("ul");
4231 tty->TF_teleray = tgetflag ("xt");
4233 #else /* DOS_NT */
4234 #ifdef WINDOWSNT
4236 struct frame *f = XFRAME (selected_frame);
4237 int height, width;
4239 initialize_w32_display (terminal, &width, &height);
4241 FrameRows (tty) = height;
4242 FrameCols (tty) = width;
4243 tty->specified_window = height;
4245 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4246 tty->char_ins_del_ok = 1;
4247 baud_rate = 19200;
4249 #else /* MSDOS */
4251 int height, width;
4252 if (strcmp (terminal_type, "internal") == 0)
4253 terminal->type = output_msdos_raw;
4254 initialize_msdos_display (terminal);
4256 get_tty_size (fileno (tty->input), &width, &height);
4257 FrameCols (tty) = width;
4258 FrameRows (tty) = height;
4259 tty->char_ins_del_ok = 0;
4260 init_baud_rate (fileno (tty->input));
4262 #endif /* MSDOS */
4263 tty->output = stdout;
4264 tty->input = stdin;
4265 /* The following two are inaccessible from w32console.c. */
4266 terminal->delete_frame_hook = &tty_free_frame_resources;
4267 terminal->delete_terminal_hook = &delete_tty;
4269 tty->name = xstrdup (name);
4270 terminal->name = xstrdup (name);
4271 tty->type = xstrdup (terminal_type);
4273 add_keyboard_wait_descriptor (0);
4275 tty->delete_in_insert_mode = 1;
4277 UseTabs (tty) = 0;
4278 tty->scroll_region_ok = 0;
4280 /* Seems to insert lines when it's not supposed to, messing up the
4281 display. In doing a trace, it didn't seem to be called much, so I
4282 don't think we're losing anything by turning it off. */
4283 tty->line_ins_del_ok = 0;
4285 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4286 #endif /* DOS_NT */
4288 #ifdef HAVE_GPM
4289 terminal->mouse_position_hook = term_mouse_position;
4290 tty->mouse_highlight.mouse_face_window = Qnil;
4291 #endif
4293 terminal->kboard = allocate_kboard (Qnil);
4294 terminal->kboard->reference_count++;
4295 /* Don't let the initial kboard remain current longer than necessary.
4296 That would cause problems if a file loaded on startup tries to
4297 prompt in the mini-buffer. */
4298 if (current_kboard == initial_kboard)
4299 current_kboard = terminal->kboard;
4300 #ifndef DOS_NT
4301 term_get_fkeys (address, terminal->kboard);
4303 /* Get frame size from system, or else from termcap. */
4305 int height, width;
4306 get_tty_size (fileno (tty->input), &width, &height);
4307 FrameCols (tty) = width;
4308 FrameRows (tty) = height;
4311 if (FrameCols (tty) <= 0)
4312 FrameCols (tty) = tgetnum ("co");
4313 if (FrameRows (tty) <= 0)
4314 FrameRows (tty) = tgetnum ("li");
4316 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4317 maybe_fatal (must_succeed, terminal,
4318 "Screen size %dx%d is too small",
4319 "Screen size %dx%d is too small",
4320 FrameCols (tty), FrameRows (tty));
4322 TabWidth (tty) = tgetnum ("tw");
4324 if (!tty->TS_bell)
4325 tty->TS_bell = "\07";
4327 if (!tty->TS_fwd_scroll)
4328 tty->TS_fwd_scroll = Down (tty);
4330 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4332 if (TabWidth (tty) < 0)
4333 TabWidth (tty) = 8;
4335 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4336 and newer termcap doc does not seem to say there is a default.
4337 if (!tty->Wcm->cm_tab)
4338 tty->Wcm->cm_tab = "\t";
4341 /* We don't support standout modes that use `magic cookies', so
4342 turn off any that do. */
4343 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4345 tty->TS_standout_mode = 0;
4346 tty->TS_end_standout_mode = 0;
4348 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4350 tty->TS_enter_underline_mode = 0;
4351 tty->TS_exit_underline_mode = 0;
4354 /* If there's no standout mode, try to use underlining instead. */
4355 if (tty->TS_standout_mode == 0)
4357 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4358 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4361 /* If no `se' string, try using a `me' string instead.
4362 If that fails, we can't use standout mode at all. */
4363 if (tty->TS_end_standout_mode == 0)
4365 char *s = tgetstr ("me", address);
4366 if (s != 0)
4367 tty->TS_end_standout_mode = s;
4368 else
4369 tty->TS_standout_mode = 0;
4372 if (tty->TF_teleray)
4374 tty->Wcm->cm_tab = 0;
4375 /* We can't support standout mode, because it uses magic cookies. */
4376 tty->TS_standout_mode = 0;
4377 /* But that means we cannot rely on ^M to go to column zero! */
4378 CR (tty) = 0;
4379 /* LF can't be trusted either -- can alter hpos. */
4380 /* If move at column 0 thru a line with TS_standout_mode. */
4381 Down (tty) = 0;
4384 tty->specified_window = FrameRows (tty);
4386 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4388 maybe_fatal (must_succeed, terminal,
4389 "Terminal type \"%s\" is not powerful enough to run Emacs",
4390 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4391 It lacks the ability to position the cursor.\n\
4392 If that is not the actual type of terminal you have,\n\
4393 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4394 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4395 # ifdef TERMINFO
4396 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4397 # else /* TERMCAP */
4398 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4399 # endif /* TERMINFO */
4400 terminal_type);
4403 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4404 maybe_fatal (must_succeed, terminal,
4405 "Could not determine the frame size",
4406 "Could not determine the frame size");
4408 tty->delete_in_insert_mode
4409 = tty->TS_delete_mode && tty->TS_insert_mode
4410 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4412 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4414 tty->scroll_region_ok
4415 = (tty->Wcm->cm_abs
4416 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4418 tty->line_ins_del_ok
4419 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4420 && (tty->TS_del_line || tty->TS_del_multi_lines))
4421 || (tty->scroll_region_ok
4422 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4424 tty->char_ins_del_ok
4425 = ((tty->TS_ins_char || tty->TS_insert_mode
4426 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4427 && (tty->TS_del_char || tty->TS_del_multi_chars));
4429 init_baud_rate (fileno (tty->input));
4431 #endif /* not DOS_NT */
4433 /* Init system terminal modes (RAW or CBREAK, etc.). */
4434 init_sys_modes (tty);
4436 return terminal;
4440 static void
4441 vfatal (const char *str, va_list ap)
4443 fprintf (stderr, "emacs: ");
4444 vfprintf (stderr, str, ap);
4445 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4446 fprintf (stderr, "\n");
4447 fflush (stderr);
4448 exit (1);
4452 /* Auxiliary error-handling function for init_tty.
4453 Delete TERMINAL, then call error or fatal with str1 or str2,
4454 respectively, according to whether MUST_SUCCEED is true. */
4456 static void
4457 maybe_fatal (bool must_succeed, struct terminal *terminal,
4458 const char *str1, const char *str2, ...)
4460 va_list ap;
4461 va_start (ap, str2);
4462 if (terminal)
4463 delete_tty (terminal);
4465 if (must_succeed)
4466 vfatal (str2, ap);
4467 else
4468 verror (str1, ap);
4471 void
4472 fatal (const char *str, ...)
4474 va_list ap;
4475 va_start (ap, str);
4476 vfatal (str, ap);
4481 /* Delete the given tty terminal, closing all frames on it. */
4483 static void
4484 delete_tty (struct terminal *terminal)
4486 struct tty_display_info *tty;
4488 /* Protect against recursive calls. delete_frame in
4489 delete_terminal calls us back when it deletes our last frame. */
4490 if (!terminal->name)
4491 return;
4493 eassert (terminal->type == output_termcap);
4495 tty = terminal->display_info.tty;
4497 if (tty == tty_list)
4498 tty_list = tty->next;
4499 else
4501 struct tty_display_info *p;
4502 for (p = tty_list; p && p->next != tty; p = p->next)
4505 if (! p)
4506 /* This should not happen. */
4507 emacs_abort ();
4509 p->next = tty->next;
4510 tty->next = 0;
4513 /* reset_sys_modes needs a valid device, so this call needs to be
4514 before delete_terminal. */
4515 reset_sys_modes (tty);
4517 delete_terminal (terminal);
4519 xfree (tty->name);
4520 xfree (tty->type);
4522 if (tty->input)
4524 delete_keyboard_wait_descriptor (fileno (tty->input));
4525 if (tty->input != stdin)
4526 fclose (tty->input);
4528 if (tty->output && tty->output != stdout && tty->output != tty->input)
4529 fclose (tty->output);
4530 if (tty->termscript)
4531 fclose (tty->termscript);
4533 xfree (tty->old_tty);
4534 xfree (tty->Wcm);
4535 xfree (tty);
4538 void
4539 syms_of_term (void)
4541 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4542 doc: /* Non-nil means the system uses terminfo rather than termcap.
4543 This variable can be used by terminal emulator packages. */);
4544 #ifdef TERMINFO
4545 system_uses_terminfo = 1;
4546 #else
4547 system_uses_terminfo = 0;
4548 #endif
4550 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4551 doc: /* Functions run after suspending a tty.
4552 The functions are run with one argument, the terminal object to be suspended.
4553 See `suspend-tty'. */);
4554 Vsuspend_tty_functions = Qnil;
4557 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4558 doc: /* Functions run after resuming a tty.
4559 The functions are run with one argument, the terminal object that was revived.
4560 See `resume-tty'. */);
4561 Vresume_tty_functions = Qnil;
4563 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4564 doc: /* Non-nil means to make the cursor very visible.
4565 This only has an effect when running in a text terminal.
4566 What means \"very visible\" is up to your terminal. It may make the cursor
4567 bigger, or it may make it blink, or it may do nothing at all. */);
4568 visible_cursor = 1;
4570 defsubr (&Stty_display_color_p);
4571 defsubr (&Stty_display_color_cells);
4572 defsubr (&Stty_no_underline);
4573 defsubr (&Stty_type);
4574 defsubr (&Scontrolling_tty_p);
4575 defsubr (&Stty_top_frame);
4576 defsubr (&Ssuspend_tty);
4577 defsubr (&Sresume_tty);
4578 #ifdef HAVE_GPM
4579 defsubr (&Sgpm_mouse_start);
4580 defsubr (&Sgpm_mouse_stop);
4581 #endif /* HAVE_GPM */
4583 #ifndef DOS_NT
4584 default_orig_pair = NULL;
4585 default_set_foreground = NULL;
4586 default_set_background = NULL;
4587 #endif /* !DOS_NT */
4589 encode_terminal_src = NULL;
4590 encode_terminal_dst = NULL;
4592 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4593 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4595 #ifndef MSDOS
4596 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4597 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4598 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4599 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4600 DEFSYM (Qtty_menu_select, "tty-menu-select");
4601 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4602 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4603 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4604 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4605 #endif