(eww-save-history): Don't let the history grow infinitely.
[emacs.git] / src / term.c
blob04f6e3318a0fe1b4823ac1155db97f967deaaee8
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 void clear_tty_hooks (struct terminal *terminal);
81 static void set_tty_hooks (struct terminal *terminal);
82 static void dissociate_if_controlling_tty (int fd);
83 static void delete_tty (struct terminal *);
84 static _Noreturn void maybe_fatal (bool, struct terminal *,
85 const char *, const char *, ...)
86 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
87 static _Noreturn void vfatal (const char *str, va_list ap)
88 ATTRIBUTE_FORMAT_PRINTF (1, 0);
91 #define OUTPUT(tty, a) \
92 emacs_tputs ((tty), a, \
93 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
94 cmputc)
96 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
97 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
99 #define OUTPUT_IF(tty, a) \
100 do { \
101 if (a) \
102 OUTPUT (tty, a); \
103 } while (0)
105 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
107 /* Display space properties. */
109 /* Chain of all tty device parameters. */
110 struct tty_display_info *tty_list;
112 /* Meaning of bits in no_color_video. Each bit set means that the
113 corresponding attribute cannot be combined with colors. */
115 enum no_color_bit
117 NC_STANDOUT = 1 << 0,
118 NC_UNDERLINE = 1 << 1,
119 NC_REVERSE = 1 << 2,
120 NC_ITALIC = 1 << 3,
121 NC_DIM = 1 << 4,
122 NC_BOLD = 1 << 5,
123 NC_INVIS = 1 << 6,
124 NC_PROTECT = 1 << 7
127 /* internal state */
129 /* The largest frame width in any call to calculate_costs. */
131 static int max_frame_cols;
133 static Lisp_Object Qtty_mode_set_strings;
134 static Lisp_Object Qtty_mode_reset_strings;
138 #ifdef HAVE_GPM
139 #include <sys/fcntl.h>
141 /* The device for which we have enabled gpm support (or NULL). */
142 struct tty_display_info *gpm_tty = NULL;
144 /* Last recorded mouse coordinates. */
145 static int last_mouse_x, last_mouse_y;
146 #endif /* HAVE_GPM */
148 /* Ring the bell on a tty. */
150 static void
151 tty_ring_bell (struct frame *f)
153 struct tty_display_info *tty = FRAME_TTY (f);
155 if (tty->output)
157 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
158 ? tty->TS_visible_bell
159 : tty->TS_bell));
160 fflush (tty->output);
164 /* Set up termcap modes for Emacs. */
166 static void
167 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
169 Lisp_Object lisp_terminal;
170 Lisp_Object extra_codes;
171 struct tty_display_info *tty = terminal->display_info.tty;
173 XSETTERMINAL (lisp_terminal, terminal);
174 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
175 CONSP (extra_codes);
176 extra_codes = XCDR (extra_codes))
178 Lisp_Object string = XCAR (extra_codes);
179 if (STRINGP (string))
181 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
182 if (tty->termscript)
183 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
188 static void
189 tty_set_terminal_modes (struct terminal *terminal)
191 struct tty_display_info *tty = terminal->display_info.tty;
193 if (tty->output)
195 if (tty->TS_termcap_modes)
196 OUTPUT (tty, tty->TS_termcap_modes);
197 else
199 /* Output enough newlines to scroll all the old screen contents
200 off the screen, so it won't be overwritten and lost. */
201 int i;
202 current_tty = tty;
203 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
204 cmputc ('\n');
207 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
208 OUTPUT_IF (tty, tty->TS_keypad_mode);
209 losecursor (tty);
210 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
211 fflush (tty->output);
215 /* Reset termcap modes before exiting Emacs. */
217 static void
218 tty_reset_terminal_modes (struct terminal *terminal)
220 struct tty_display_info *tty = terminal->display_info.tty;
222 if (tty->output)
224 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
225 tty_turn_off_highlight (tty);
226 tty_turn_off_insert (tty);
227 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
228 OUTPUT_IF (tty, tty->TS_cursor_normal);
229 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
230 OUTPUT_IF (tty, tty->TS_orig_pair);
231 /* Output raw CR so kernel can track the cursor hpos. */
232 current_tty = tty;
233 cmputc ('\r');
234 fflush (tty->output);
238 /* Flag the end of a display update on a termcap terminal. */
240 static void
241 tty_update_end (struct frame *f)
243 struct tty_display_info *tty = FRAME_TTY (f);
245 if (!XWINDOW (selected_window)->cursor_off_p)
246 tty_show_cursor (tty);
247 tty_turn_off_insert (tty);
248 tty_background_highlight (tty);
249 fflush (tty->output);
252 /* The implementation of set_terminal_window for termcap frames. */
254 static void
255 tty_set_terminal_window (struct frame *f, int size)
257 struct tty_display_info *tty = FRAME_TTY (f);
259 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
260 if (FRAME_SCROLL_REGION_OK (f))
261 tty_set_scroll_region (f, 0, tty->specified_window);
264 static void
265 tty_set_scroll_region (struct frame *f, int start, int stop)
267 char *buf;
268 struct tty_display_info *tty = FRAME_TTY (f);
270 if (tty->TS_set_scroll_region)
271 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
272 else if (tty->TS_set_scroll_region_1)
273 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
274 FRAME_TOTAL_LINES (f), start,
275 FRAME_TOTAL_LINES (f) - stop,
276 FRAME_TOTAL_LINES (f));
277 else
278 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
280 OUTPUT (tty, buf);
281 xfree (buf);
282 losecursor (tty);
286 static void
287 tty_turn_on_insert (struct tty_display_info *tty)
289 if (!tty->insert_mode)
290 OUTPUT (tty, tty->TS_insert_mode);
291 tty->insert_mode = 1;
294 void
295 tty_turn_off_insert (struct tty_display_info *tty)
297 if (tty->insert_mode)
298 OUTPUT (tty, tty->TS_end_insert_mode);
299 tty->insert_mode = 0;
302 /* Handle highlighting. */
304 static void
305 tty_turn_off_highlight (struct tty_display_info *tty)
307 if (tty->standout_mode)
308 OUTPUT_IF (tty, tty->TS_end_standout_mode);
309 tty->standout_mode = 0;
312 static void
313 tty_turn_on_highlight (struct tty_display_info *tty)
315 if (!tty->standout_mode)
316 OUTPUT_IF (tty, tty->TS_standout_mode);
317 tty->standout_mode = 1;
320 static void
321 tty_toggle_highlight (struct tty_display_info *tty)
323 if (tty->standout_mode)
324 tty_turn_off_highlight (tty);
325 else
326 tty_turn_on_highlight (tty);
330 /* Make cursor invisible. */
332 static void
333 tty_hide_cursor (struct tty_display_info *tty)
335 if (tty->cursor_hidden == 0)
337 tty->cursor_hidden = 1;
338 #ifdef WINDOWSNT
339 w32con_hide_cursor ();
340 #else
341 OUTPUT_IF (tty, tty->TS_cursor_invisible);
342 #endif
347 /* Ensure that cursor is visible. */
349 static void
350 tty_show_cursor (struct tty_display_info *tty)
352 if (tty->cursor_hidden)
354 tty->cursor_hidden = 0;
355 #ifdef WINDOWSNT
356 w32con_show_cursor ();
357 #else
358 OUTPUT_IF (tty, tty->TS_cursor_normal);
359 if (visible_cursor)
360 OUTPUT_IF (tty, tty->TS_cursor_visible);
361 #endif
366 /* Set standout mode to the state it should be in for
367 empty space inside windows. What this is,
368 depends on the user option inverse-video. */
370 static void
371 tty_background_highlight (struct tty_display_info *tty)
373 if (inverse_video)
374 tty_turn_on_highlight (tty);
375 else
376 tty_turn_off_highlight (tty);
379 /* Set standout mode to the mode specified for the text to be output. */
381 static void
382 tty_highlight_if_desired (struct tty_display_info *tty)
384 if (inverse_video)
385 tty_turn_on_highlight (tty);
386 else
387 tty_turn_off_highlight (tty);
391 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
392 frame-relative coordinates. */
394 static void
395 tty_cursor_to (struct frame *f, int vpos, int hpos)
397 struct tty_display_info *tty = FRAME_TTY (f);
399 /* Detect the case where we are called from reset_sys_modes
400 and the costs have never been calculated. Do nothing. */
401 if (! tty->costs_set)
402 return;
404 if (curY (tty) == vpos
405 && curX (tty) == hpos)
406 return;
407 if (!tty->TF_standout_motion)
408 tty_background_highlight (tty);
409 if (!tty->TF_insmode_motion)
410 tty_turn_off_insert (tty);
411 cmgoto (tty, vpos, hpos);
414 /* Similar but don't take any account of the wasted characters. */
416 static void
417 tty_raw_cursor_to (struct frame *f, int row, int col)
419 struct tty_display_info *tty = FRAME_TTY (f);
421 if (curY (tty) == row
422 && curX (tty) == col)
423 return;
424 if (!tty->TF_standout_motion)
425 tty_background_highlight (tty);
426 if (!tty->TF_insmode_motion)
427 tty_turn_off_insert (tty);
428 cmgoto (tty, row, col);
431 /* Erase operations */
433 /* Clear from cursor to end of frame on a termcap device. */
435 static void
436 tty_clear_to_end (struct frame *f)
438 register int i;
439 struct tty_display_info *tty = FRAME_TTY (f);
441 if (tty->TS_clr_to_bottom)
443 tty_background_highlight (tty);
444 OUTPUT (tty, tty->TS_clr_to_bottom);
446 else
448 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
450 cursor_to (f, i, 0);
451 clear_end_of_line (f, FRAME_COLS (f));
456 /* Clear an entire termcap frame. */
458 static void
459 tty_clear_frame (struct frame *f)
461 struct tty_display_info *tty = FRAME_TTY (f);
463 if (tty->TS_clr_frame)
465 tty_background_highlight (tty);
466 OUTPUT (tty, tty->TS_clr_frame);
467 cmat (tty, 0, 0);
469 else
471 cursor_to (f, 0, 0);
472 clear_to_end (f);
476 /* An implementation of clear_end_of_line for termcap frames.
478 Note that the cursor may be moved, on terminals lacking a `ce' string. */
480 static void
481 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
483 register int i;
484 struct tty_display_info *tty = FRAME_TTY (f);
486 /* Detect the case where we are called from reset_sys_modes
487 and the costs have never been calculated. Do nothing. */
488 if (! tty->costs_set)
489 return;
491 if (curX (tty) >= first_unused_hpos)
492 return;
493 tty_background_highlight (tty);
494 if (tty->TS_clr_line)
496 OUTPUT1 (tty, tty->TS_clr_line);
498 else
499 { /* have to do it the hard way */
500 tty_turn_off_insert (tty);
502 /* Do not write in last row last col with Auto-wrap on. */
503 if (AutoWrap (tty)
504 && curY (tty) == FrameRows (tty) - 1
505 && first_unused_hpos == FrameCols (tty))
506 first_unused_hpos--;
508 for (i = curX (tty); i < first_unused_hpos; i++)
510 if (tty->termscript)
511 fputc (' ', tty->termscript);
512 fputc (' ', tty->output);
514 cmplus (tty, first_unused_hpos - curX (tty));
518 /* Buffers to store the source and result of code conversion for terminal. */
519 static unsigned char *encode_terminal_src;
520 static unsigned char *encode_terminal_dst;
521 /* Allocated sizes of the above buffers. */
522 static ptrdiff_t encode_terminal_src_size;
523 static ptrdiff_t encode_terminal_dst_size;
525 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
526 Set CODING->produced to the byte-length of the resulting byte
527 sequence, and return a pointer to that byte sequence. */
529 unsigned char *
530 encode_terminal_code (struct glyph *src, int src_len,
531 struct coding_system *coding)
533 struct glyph *src_end = src + src_len;
534 unsigned char *buf;
535 ptrdiff_t nchars, nbytes, required;
536 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
537 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
538 Lisp_Object charset_list;
540 /* Allocate sufficient size of buffer to store all characters in
541 multibyte-form. But, it may be enlarged on demand if
542 Vglyph_table contains a string or a composite glyph is
543 encountered. */
544 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
545 memory_full (SIZE_MAX);
546 required = src_len;
547 required *= MAX_MULTIBYTE_LENGTH;
548 if (encode_terminal_src_size < required)
550 encode_terminal_src = xrealloc (encode_terminal_src, required);
551 encode_terminal_src_size = required;
554 charset_list = coding_charset_list (coding);
556 buf = encode_terminal_src;
557 nchars = 0;
558 while (src < src_end)
560 if (src->type == COMPOSITE_GLYPH)
562 struct composition *cmp IF_LINT (= NULL);
563 Lisp_Object gstring IF_LINT (= Qnil);
564 int i;
566 nbytes = buf - encode_terminal_src;
567 if (src->u.cmp.automatic)
569 gstring = composition_gstring_from_id (src->u.cmp.id);
570 required = src->slice.cmp.to - src->slice.cmp.from + 1;
572 else
574 cmp = composition_table[src->u.cmp.id];
575 required = cmp->glyph_len;
576 required *= MAX_MULTIBYTE_LENGTH;
579 if (encode_terminal_src_size - nbytes < required)
581 encode_terminal_src =
582 xpalloc (encode_terminal_src, &encode_terminal_src_size,
583 required - (encode_terminal_src_size - nbytes),
584 -1, 1);
585 buf = encode_terminal_src + nbytes;
588 if (src->u.cmp.automatic)
589 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
591 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
592 int c = LGLYPH_CHAR (g);
594 if (! char_charset (c, charset_list, NULL))
595 c = '?';
596 buf += CHAR_STRING (c, buf);
597 nchars++;
599 else
600 for (i = 0; i < cmp->glyph_len; i++)
602 int c = COMPOSITION_GLYPH (cmp, i);
604 /* TAB in a composition means display glyphs with
605 padding space on the left or right. */
606 if (c == '\t')
607 continue;
608 if (char_charset (c, charset_list, NULL))
610 if (CHAR_WIDTH (c) == 0
611 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
612 /* Should be left-padded */
614 buf += CHAR_STRING (' ', buf);
615 nchars++;
618 else
619 c = '?';
620 buf += CHAR_STRING (c, buf);
621 nchars++;
624 /* We must skip glyphs to be padded for a wide character. */
625 else if (! CHAR_GLYPH_PADDING_P (*src))
627 GLYPH g;
628 int c IF_LINT (= 0);
629 Lisp_Object string;
631 string = Qnil;
632 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
634 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
636 /* This glyph doesn't have an entry in Vglyph_table. */
637 c = src->u.ch;
639 else
641 /* This glyph has an entry in Vglyph_table,
642 so process any alias before testing for simpleness. */
643 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
645 if (GLYPH_SIMPLE_P (tbase, tlen, g))
646 /* We set the multi-byte form of a character in G
647 (that should be an ASCII character) at WORKBUF. */
648 c = GLYPH_CHAR (g);
649 else
650 /* We have a string in Vglyph_table. */
651 string = tbase[GLYPH_CHAR (g)];
654 if (NILP (string))
656 nbytes = buf - encode_terminal_src;
657 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
659 encode_terminal_src =
660 xpalloc (encode_terminal_src, &encode_terminal_src_size,
661 MAX_MULTIBYTE_LENGTH, -1, 1);
662 buf = encode_terminal_src + nbytes;
664 if (CHAR_BYTE8_P (c)
665 || char_charset (c, charset_list, NULL))
667 /* Store the multibyte form of C at BUF. */
668 buf += CHAR_STRING (c, buf);
669 nchars++;
671 else
673 /* C is not encodable. */
674 *buf++ = '?';
675 nchars++;
676 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
678 *buf++ = '?';
679 nchars++;
680 src++;
684 else
686 if (! STRING_MULTIBYTE (string))
687 string = string_to_multibyte (string);
688 nbytes = buf - encode_terminal_src;
689 if (encode_terminal_src_size - nbytes < SBYTES (string))
691 encode_terminal_src =
692 xpalloc (encode_terminal_src, &encode_terminal_src_size,
693 (SBYTES (string)
694 - (encode_terminal_src_size - nbytes)),
695 -1, 1);
696 buf = encode_terminal_src + nbytes;
698 memcpy (buf, SDATA (string), SBYTES (string));
699 buf += SBYTES (string);
700 nchars += SCHARS (string);
703 src++;
706 if (nchars == 0)
708 coding->produced = 0;
709 return NULL;
712 nbytes = buf - encode_terminal_src;
713 coding->source = encode_terminal_src;
714 if (encode_terminal_dst_size == 0)
716 encode_terminal_dst = xrealloc (encode_terminal_dst,
717 encode_terminal_src_size);
718 encode_terminal_dst_size = encode_terminal_src_size;
720 coding->destination = encode_terminal_dst;
721 coding->dst_bytes = encode_terminal_dst_size;
722 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
723 /* coding->destination may have been reallocated. */
724 encode_terminal_dst = coding->destination;
725 encode_terminal_dst_size = coding->dst_bytes;
727 return (encode_terminal_dst);
732 /* An implementation of write_glyphs for termcap frames. */
734 static void
735 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
737 unsigned char *conversion_buffer;
738 struct coding_system *coding;
739 int n, stringlen;
741 struct tty_display_info *tty = FRAME_TTY (f);
743 tty_turn_off_insert (tty);
744 tty_hide_cursor (tty);
746 /* Don't dare write in last column of bottom line, if Auto-Wrap,
747 since that would scroll the whole frame on some terminals. */
749 if (AutoWrap (tty)
750 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
751 && (curX (tty) + len) == FRAME_COLS (f))
752 len --;
753 if (len <= 0)
754 return;
756 cmplus (tty, len);
758 /* If terminal_coding does any conversion, use it, otherwise use
759 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
760 because it always return 1 if the member src_multibyte is 1. */
761 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
762 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
763 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
764 the tail. */
765 coding->mode &= ~CODING_MODE_LAST_BLOCK;
767 for (stringlen = len; stringlen != 0; stringlen -= n)
769 /* Identify a run of glyphs with the same face. */
770 int face_id = string->face_id;
772 for (n = 1; n < stringlen; ++n)
773 if (string[n].face_id != face_id)
774 break;
776 /* Turn appearance modes of the face of the run on. */
777 tty_highlight_if_desired (tty);
778 turn_on_face (f, face_id);
780 if (n == stringlen)
781 /* This is the last run. */
782 coding->mode |= CODING_MODE_LAST_BLOCK;
783 conversion_buffer = encode_terminal_code (string, n, coding);
784 if (coding->produced > 0)
786 block_input ();
787 fwrite (conversion_buffer, 1, coding->produced, tty->output);
788 if (ferror (tty->output))
789 clearerr (tty->output);
790 if (tty->termscript)
791 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
792 unblock_input ();
794 string += n;
796 /* Turn appearance modes off. */
797 turn_off_face (f, face_id);
798 tty_turn_off_highlight (tty);
801 cmcheckmagic (tty);
804 #ifdef HAVE_GPM /* Only used by GPM code. */
806 static void
807 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
808 register int len, register int face_id)
810 unsigned char *conversion_buffer;
811 struct coding_system *coding;
813 struct tty_display_info *tty = FRAME_TTY (f);
815 tty_turn_off_insert (tty);
816 tty_hide_cursor (tty);
818 /* Don't dare write in last column of bottom line, if Auto-Wrap,
819 since that would scroll the whole frame on some terminals. */
821 if (AutoWrap (tty)
822 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
823 && (curX (tty) + len) == FRAME_COLS (f))
824 len --;
825 if (len <= 0)
826 return;
828 cmplus (tty, len);
830 /* If terminal_coding does any conversion, use it, otherwise use
831 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
832 because it always return 1 if the member src_multibyte is 1. */
833 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
834 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
835 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
836 the tail. */
837 coding->mode &= ~CODING_MODE_LAST_BLOCK;
839 /* Turn appearance modes of the face. */
840 tty_highlight_if_desired (tty);
841 turn_on_face (f, face_id);
843 coding->mode |= CODING_MODE_LAST_BLOCK;
844 conversion_buffer = encode_terminal_code (string, len, coding);
845 if (coding->produced > 0)
847 block_input ();
848 fwrite (conversion_buffer, 1, coding->produced, tty->output);
849 if (ferror (tty->output))
850 clearerr (tty->output);
851 if (tty->termscript)
852 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
853 unblock_input ();
856 /* Turn appearance modes off. */
857 turn_off_face (f, face_id);
858 tty_turn_off_highlight (tty);
860 cmcheckmagic (tty);
862 #endif
864 /* An implementation of insert_glyphs for termcap frames. */
866 static void
867 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
869 char *buf;
870 struct glyph *glyph = NULL;
871 unsigned char *conversion_buffer;
872 unsigned char space[1];
873 struct coding_system *coding;
875 struct tty_display_info *tty = FRAME_TTY (f);
877 if (tty->TS_ins_multi_chars)
879 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
880 OUTPUT1 (tty, buf);
881 xfree (buf);
882 if (start)
883 write_glyphs (f, start, len);
884 return;
887 tty_turn_on_insert (tty);
888 cmplus (tty, len);
890 if (! start)
891 space[0] = SPACEGLYPH;
893 /* If terminal_coding does any conversion, use it, otherwise use
894 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
895 because it always return 1 if the member src_multibyte is 1. */
896 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
897 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
898 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
899 the tail. */
900 coding->mode &= ~CODING_MODE_LAST_BLOCK;
902 while (len-- > 0)
904 OUTPUT1_IF (tty, tty->TS_ins_char);
905 if (!start)
907 conversion_buffer = space;
908 coding->produced = 1;
910 else
912 tty_highlight_if_desired (tty);
913 turn_on_face (f, start->face_id);
914 glyph = start;
915 ++start;
916 /* We must open sufficient space for a character which
917 occupies more than one column. */
918 while (len && CHAR_GLYPH_PADDING_P (*start))
920 OUTPUT1_IF (tty, tty->TS_ins_char);
921 start++, len--;
924 if (len <= 0)
925 /* This is the last glyph. */
926 coding->mode |= CODING_MODE_LAST_BLOCK;
928 conversion_buffer = encode_terminal_code (glyph, 1, coding);
931 if (coding->produced > 0)
933 block_input ();
934 fwrite (conversion_buffer, 1, coding->produced, tty->output);
935 if (ferror (tty->output))
936 clearerr (tty->output);
937 if (tty->termscript)
938 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
939 unblock_input ();
942 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
943 if (start)
945 turn_off_face (f, glyph->face_id);
946 tty_turn_off_highlight (tty);
950 cmcheckmagic (tty);
953 /* An implementation of delete_glyphs for termcap frames. */
955 static void
956 tty_delete_glyphs (struct frame *f, int n)
958 char *buf;
959 register int i;
961 struct tty_display_info *tty = FRAME_TTY (f);
963 if (tty->delete_in_insert_mode)
965 tty_turn_on_insert (tty);
967 else
969 tty_turn_off_insert (tty);
970 OUTPUT_IF (tty, tty->TS_delete_mode);
973 if (tty->TS_del_multi_chars)
975 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
976 OUTPUT1 (tty, buf);
977 xfree (buf);
979 else
980 for (i = 0; i < n; i++)
981 OUTPUT1 (tty, tty->TS_del_char);
982 if (!tty->delete_in_insert_mode)
983 OUTPUT_IF (tty, tty->TS_end_delete_mode);
986 /* An implementation of ins_del_lines for termcap frames. */
988 static void
989 tty_ins_del_lines (struct frame *f, int vpos, int n)
991 struct tty_display_info *tty = FRAME_TTY (f);
992 const char *multi =
993 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
994 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
995 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
997 int i = eabs (n);
998 char *buf;
1000 /* If the lines below the insertion are being pushed
1001 into the end of the window, this is the same as clearing;
1002 and we know the lines are already clear, since the matching
1003 deletion has already been done. So can ignore this. */
1004 /* If the lines below the deletion are blank lines coming
1005 out of the end of the window, don't bother,
1006 as there will be a matching inslines later that will flush them. */
1007 if (FRAME_SCROLL_REGION_OK (f)
1008 && vpos + i >= tty->specified_window)
1009 return;
1010 if (!FRAME_MEMORY_BELOW_FRAME (f)
1011 && vpos + i >= FRAME_TOTAL_LINES (f))
1012 return;
1014 if (multi)
1016 raw_cursor_to (f, vpos, 0);
1017 tty_background_highlight (tty);
1018 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1019 OUTPUT (tty, buf);
1020 xfree (buf);
1022 else if (single)
1024 raw_cursor_to (f, vpos, 0);
1025 tty_background_highlight (tty);
1026 while (--i >= 0)
1027 OUTPUT (tty, single);
1028 if (tty->TF_teleray)
1029 curX (tty) = 0;
1031 else
1033 tty_set_scroll_region (f, vpos, tty->specified_window);
1034 if (n < 0)
1035 raw_cursor_to (f, tty->specified_window - 1, 0);
1036 else
1037 raw_cursor_to (f, vpos, 0);
1038 tty_background_highlight (tty);
1039 while (--i >= 0)
1040 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1041 tty_set_scroll_region (f, 0, tty->specified_window);
1044 if (!FRAME_SCROLL_REGION_OK (f)
1045 && FRAME_MEMORY_BELOW_FRAME (f)
1046 && n < 0)
1048 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1049 clear_to_end (f);
1053 /* Compute cost of sending "str", in characters,
1054 not counting any line-dependent padding. */
1057 string_cost (const char *str)
1059 cost = 0;
1060 if (str)
1061 tputs (str, 0, evalcost);
1062 return cost;
1065 /* Compute cost of sending "str", in characters,
1066 counting any line-dependent padding at one line. */
1068 static int
1069 string_cost_one_line (const char *str)
1071 cost = 0;
1072 if (str)
1073 tputs (str, 1, evalcost);
1074 return cost;
1077 /* Compute per line amount of line-dependent padding,
1078 in tenths of characters. */
1081 per_line_cost (const char *str)
1083 cost = 0;
1084 if (str)
1085 tputs (str, 0, evalcost);
1086 cost = - cost;
1087 if (str)
1088 tputs (str, 10, evalcost);
1089 return cost;
1092 /* char_ins_del_cost[n] is cost of inserting N characters.
1093 char_ins_del_cost[-n] is cost of deleting N characters.
1094 The length of this vector is based on max_frame_cols. */
1096 int *char_ins_del_vector;
1098 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1100 /* ARGSUSED */
1101 static void
1102 calculate_ins_del_char_costs (struct frame *f)
1104 struct tty_display_info *tty = FRAME_TTY (f);
1105 int ins_startup_cost, del_startup_cost;
1106 int ins_cost_per_char, del_cost_per_char;
1107 register int i;
1108 register int *p;
1110 if (tty->TS_ins_multi_chars)
1112 ins_cost_per_char = 0;
1113 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1115 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1116 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1118 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1119 + string_cost (tty->TS_end_insert_mode))) / 100;
1120 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1121 + string_cost_one_line (tty->TS_pad_inserted_char));
1123 else
1125 ins_startup_cost = 9999;
1126 ins_cost_per_char = 0;
1129 if (tty->TS_del_multi_chars)
1131 del_cost_per_char = 0;
1132 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1134 else if (tty->TS_del_char)
1136 del_startup_cost = (string_cost (tty->TS_delete_mode)
1137 + string_cost (tty->TS_end_delete_mode));
1138 if (tty->delete_in_insert_mode)
1139 del_startup_cost /= 2;
1140 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1142 else
1144 del_startup_cost = 9999;
1145 del_cost_per_char = 0;
1148 /* Delete costs are at negative offsets */
1149 p = &char_ins_del_cost (f)[0];
1150 for (i = FRAME_COLS (f); --i >= 0;)
1151 *--p = (del_startup_cost += del_cost_per_char);
1153 /* Doing nothing is free */
1154 p = &char_ins_del_cost (f)[0];
1155 *p++ = 0;
1157 /* Insert costs are at positive offsets */
1158 for (i = FRAME_COLS (f); --i >= 0;)
1159 *p++ = (ins_startup_cost += ins_cost_per_char);
1162 void
1163 calculate_costs (struct frame *frame)
1165 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1167 if (FRAME_TERMCAP_P (frame))
1169 struct tty_display_info *tty = FRAME_TTY (frame);
1170 register const char *f = (tty->TS_set_scroll_region
1171 ? tty->TS_set_scroll_region
1172 : tty->TS_set_scroll_region_1);
1174 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1176 tty->costs_set = 1;
1178 /* These variables are only used for terminal stuff. They are
1179 allocated once for the terminal frame of X-windows emacs, but not
1180 used afterwards.
1182 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1183 X turns off char_ins_del_ok. */
1185 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1186 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1187 < max_frame_cols)
1188 memory_full (SIZE_MAX);
1190 char_ins_del_vector =
1191 xrealloc (char_ins_del_vector,
1192 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1194 memset (char_ins_del_vector, 0,
1195 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1198 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1199 do_line_insertion_deletion_costs (frame,
1200 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1201 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1202 f, f, 1);
1203 else
1204 do_line_insertion_deletion_costs (frame,
1205 tty->TS_ins_line, tty->TS_ins_multi_lines,
1206 tty->TS_del_line, tty->TS_del_multi_lines,
1207 0, 0, 1);
1209 calculate_ins_del_char_costs (frame);
1211 /* Don't use TS_repeat if its padding is worse than sending the chars */
1212 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1213 tty->RPov = string_cost (tty->TS_repeat);
1214 else
1215 tty->RPov = FRAME_COLS (frame) * 2;
1217 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1221 struct fkey_table {
1222 const char *cap, *name;
1225 /* Termcap capability names that correspond directly to X keysyms.
1226 Some of these (marked "terminfo") aren't supplied by old-style
1227 (Berkeley) termcap entries. They're listed in X keysym order;
1228 except we put the keypad keys first, so that if they clash with
1229 other keys (as on the IBM PC keyboard) they get overridden.
1232 static const struct fkey_table keys[] =
1234 {"kh", "home"}, /* termcap */
1235 {"kl", "left"}, /* termcap */
1236 {"ku", "up"}, /* termcap */
1237 {"kr", "right"}, /* termcap */
1238 {"kd", "down"}, /* termcap */
1239 {"%8", "prior"}, /* terminfo */
1240 {"%5", "next"}, /* terminfo */
1241 {"@7", "end"}, /* terminfo */
1242 {"@1", "begin"}, /* terminfo */
1243 {"*6", "select"}, /* terminfo */
1244 {"%9", "print"}, /* terminfo */
1245 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1247 * "insert" --- see below
1249 {"&8", "undo"}, /* terminfo */
1250 {"%0", "redo"}, /* terminfo */
1251 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1252 {"@0", "find"}, /* terminfo */
1253 {"@2", "cancel"}, /* terminfo */
1254 {"%1", "help"}, /* terminfo */
1256 * "break" goes here, but can't be reliably intercepted with termcap
1258 {"&4", "reset"}, /* terminfo --- actually `restart' */
1260 * "system" and "user" --- no termcaps
1262 {"kE", "clearline"}, /* terminfo */
1263 {"kA", "insertline"}, /* terminfo */
1264 {"kL", "deleteline"}, /* terminfo */
1265 {"kI", "insertchar"}, /* terminfo */
1266 {"kD", "deletechar"}, /* terminfo */
1267 {"kB", "backtab"}, /* terminfo */
1269 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1271 {"@8", "kp-enter"}, /* terminfo */
1273 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1274 * "kp-multiply", "kp-add", "kp-separator",
1275 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1276 * --- no termcaps for any of these.
1278 {"K4", "kp-1"}, /* terminfo */
1280 * "kp-2" --- no termcap
1282 {"K5", "kp-3"}, /* terminfo */
1284 * "kp-4" --- no termcap
1286 {"K2", "kp-5"}, /* terminfo */
1288 * "kp-6" --- no termcap
1290 {"K1", "kp-7"}, /* terminfo */
1292 * "kp-8" --- no termcap
1294 {"K3", "kp-9"}, /* terminfo */
1296 * "kp-equal" --- no termcap
1298 {"k1", "f1"},
1299 {"k2", "f2"},
1300 {"k3", "f3"},
1301 {"k4", "f4"},
1302 {"k5", "f5"},
1303 {"k6", "f6"},
1304 {"k7", "f7"},
1305 {"k8", "f8"},
1306 {"k9", "f9"},
1308 {"&0", "S-cancel"}, /*shifted cancel key*/
1309 {"&9", "S-begin"}, /*shifted begin key*/
1310 {"*0", "S-find"}, /*shifted find key*/
1311 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1312 {"*4", "S-delete"}, /*shifted delete-character key*/
1313 {"*7", "S-end"}, /*shifted end key*/
1314 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1315 {"#1", "S-help"}, /*shifted help key*/
1316 {"#2", "S-home"}, /*shifted home key*/
1317 {"#3", "S-insert"}, /*shifted insert-character key*/
1318 {"#4", "S-left"}, /*shifted left-arrow key*/
1319 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1320 {"%c", "S-next"}, /*shifted next key*/
1321 {"%e", "S-prior"}, /*shifted previous key*/
1322 {"%f", "S-print"}, /*shifted print key*/
1323 {"%g", "S-redo"}, /*shifted redo key*/
1324 {"%i", "S-right"}, /*shifted right-arrow key*/
1325 {"!3", "S-undo"} /*shifted undo key*/
1328 #ifndef DOS_NT
1329 static char **term_get_fkeys_address;
1330 static KBOARD *term_get_fkeys_kboard;
1331 static Lisp_Object term_get_fkeys_1 (void);
1333 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1334 This function scans the termcap function key sequence entries, and
1335 adds entries to Vinput_decode_map for each function key it finds. */
1337 static void
1338 term_get_fkeys (char **address, KBOARD *kboard)
1340 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1341 errors during the call. The only errors should be from Fdefine_key
1342 when given a key sequence containing an invalid prefix key. If the
1343 termcap defines function keys which use a prefix that is already bound
1344 to a command by the default bindings, we should silently ignore that
1345 function key specification, rather than giving the user an error and
1346 refusing to run at all on such a terminal. */
1348 term_get_fkeys_address = address;
1349 term_get_fkeys_kboard = kboard;
1350 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1353 static Lisp_Object
1354 term_get_fkeys_1 (void)
1356 int i;
1358 char **address = term_get_fkeys_address;
1359 KBOARD *kboard = term_get_fkeys_kboard;
1361 /* This can happen if CANNOT_DUMP or with strange options. */
1362 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1363 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1365 for (i = 0; i < ARRAYELTS (keys); i++)
1367 char *sequence = tgetstr (keys[i].cap, address);
1368 if (sequence)
1369 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1370 Fmake_vector (make_number (1),
1371 intern (keys[i].name)));
1374 /* The uses of the "k0" capability are inconsistent; sometimes it
1375 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1376 We will attempt to politely accommodate both systems by testing for
1377 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1380 const char *k_semi = tgetstr ("k;", address);
1381 const char *k0 = tgetstr ("k0", address);
1382 const char *k0_name = "f10";
1384 if (k_semi)
1386 if (k0)
1387 /* Define f0 first, so that f10 takes precedence in case the
1388 key sequences happens to be the same. */
1389 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1390 Fmake_vector (make_number (1), intern ("f0")));
1391 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1392 Fmake_vector (make_number (1), intern ("f10")));
1394 else if (k0)
1395 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1396 Fmake_vector (make_number (1), intern (k0_name)));
1399 /* Set up cookies for numbered function keys above f10. */
1401 char fcap[3], fkey[4];
1403 fcap[0] = 'F'; fcap[2] = '\0';
1404 for (i = 11; i < 64; i++)
1406 if (i <= 19)
1407 fcap[1] = '1' + i - 11;
1408 else if (i <= 45)
1409 fcap[1] = 'A' + i - 20;
1410 else
1411 fcap[1] = 'a' + i - 46;
1414 char *sequence = tgetstr (fcap, address);
1415 if (sequence)
1417 sprintf (fkey, "f%d", i);
1418 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1419 Fmake_vector (make_number (1),
1420 intern (fkey)));
1427 * Various mappings to try and get a better fit.
1430 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1431 if (!tgetstr (cap1, address)) \
1433 char *sequence = tgetstr (cap2, address); \
1434 if (sequence) \
1435 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1436 Fmake_vector (make_number (1), \
1437 intern (sym))); \
1440 /* if there's no key_next keycap, map key_npage to `next' keysym */
1441 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1442 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1443 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1444 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1445 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1446 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1447 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1448 #undef CONDITIONAL_REASSIGN
1451 return Qnil;
1453 #endif /* not DOS_NT */
1456 /***********************************************************************
1457 Character Display Information
1458 ***********************************************************************/
1459 static void append_glyph (struct it *);
1460 static void append_composite_glyph (struct it *);
1461 static void produce_composite_glyph (struct it *);
1462 static void append_glyphless_glyph (struct it *, int, const char *);
1463 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1465 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1466 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1467 the character for which to produce glyphs; IT->face_id contains the
1468 character's face. Padding glyphs are appended if IT->c has a
1469 IT->pixel_width > 1. */
1471 static void
1472 append_glyph (struct it *it)
1474 struct glyph *glyph, *end;
1475 int i;
1477 eassert (it->glyph_row);
1478 glyph = (it->glyph_row->glyphs[it->area]
1479 + it->glyph_row->used[it->area]);
1480 end = it->glyph_row->glyphs[1 + it->area];
1482 /* If the glyph row is reversed, we need to prepend the glyph rather
1483 than append it. */
1484 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1486 struct glyph *g;
1487 int move_by = it->pixel_width;
1489 /* Make room for the new glyphs. */
1490 if (move_by > end - glyph) /* don't overstep end of this area */
1491 move_by = end - glyph;
1492 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1493 g[move_by] = *g;
1494 glyph = it->glyph_row->glyphs[it->area];
1495 end = glyph + move_by;
1498 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1499 right, even in the REVERSED_P case, since (a) all of its u.ch are
1500 identical, and (b) the PADDING_P flag needs to be set for the
1501 leftmost one, because we write to the terminal left-to-right. */
1502 for (i = 0;
1503 i < it->pixel_width && glyph < end;
1504 ++i)
1506 glyph->type = CHAR_GLYPH;
1507 glyph->pixel_width = 1;
1508 glyph->u.ch = it->char_to_display;
1509 glyph->face_id = it->face_id;
1510 glyph->padding_p = i > 0;
1511 glyph->charpos = CHARPOS (it->position);
1512 glyph->object = it->object;
1513 if (it->bidi_p)
1515 glyph->resolved_level = it->bidi_it.resolved_level;
1516 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1517 glyph->bidi_type = it->bidi_it.type;
1519 else
1521 glyph->resolved_level = 0;
1522 glyph->bidi_type = UNKNOWN_BT;
1525 ++it->glyph_row->used[it->area];
1526 ++glyph;
1530 /* For external use. */
1531 void
1532 tty_append_glyph (struct it *it)
1534 append_glyph (it);
1538 /* Produce glyphs for the display element described by IT. *IT
1539 specifies what we want to produce a glyph for (character, image, ...),
1540 and where in the glyph matrix we currently are (glyph row and hpos).
1541 produce_glyphs fills in output fields of *IT with information such as the
1542 pixel width and height of a character, and maybe output actual glyphs at
1543 the same time if IT->glyph_row is non-null. For an overview, see
1544 the explanation in dispextern.h, before the definition of the
1545 display_element_type enumeration.
1547 produce_glyphs also stores the result of glyph width, ascent
1548 etc. computations in *IT.
1550 IT->glyph_row may be null, in which case produce_glyphs does not
1551 actually fill in the glyphs. This is used in the move_* functions
1552 in xdisp.c for text width and height computations.
1554 Callers usually don't call produce_glyphs directly;
1555 instead they use the macro PRODUCE_GLYPHS. */
1557 void
1558 produce_glyphs (struct it *it)
1560 /* If a hook is installed, let it do the work. */
1562 /* Nothing but characters are supported on terminal frames. */
1563 eassert (it->what == IT_CHARACTER
1564 || it->what == IT_COMPOSITION
1565 || it->what == IT_STRETCH
1566 || it->what == IT_GLYPHLESS);
1568 if (it->what == IT_STRETCH)
1570 produce_stretch_glyph (it);
1571 goto done;
1574 if (it->what == IT_COMPOSITION)
1576 produce_composite_glyph (it);
1577 goto done;
1580 if (it->what == IT_GLYPHLESS)
1582 produce_glyphless_glyph (it, Qnil);
1583 goto done;
1586 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1588 it->pixel_width = it->nglyphs = 1;
1589 if (it->glyph_row)
1590 append_glyph (it);
1592 else if (it->char_to_display == '\n')
1593 it->pixel_width = it->nglyphs = 0;
1594 else if (it->char_to_display == '\t')
1596 int absolute_x = (it->current_x
1597 + it->continuation_lines_width);
1598 int next_tab_x
1599 = (((1 + absolute_x + it->tab_width - 1)
1600 / it->tab_width)
1601 * it->tab_width);
1602 int nspaces;
1604 /* If part of the TAB has been displayed on the previous line
1605 which is continued now, continuation_lines_width will have
1606 been incremented already by the part that fitted on the
1607 continued line. So, we will get the right number of spaces
1608 here. */
1609 nspaces = next_tab_x - absolute_x;
1611 if (it->glyph_row)
1613 int n = nspaces;
1615 it->char_to_display = ' ';
1616 it->pixel_width = it->len = 1;
1618 while (n--)
1619 append_glyph (it);
1622 it->pixel_width = nspaces;
1623 it->nglyphs = nspaces;
1625 else if (CHAR_BYTE8_P (it->char_to_display))
1627 /* Coming here means that we must send the raw 8-bit byte as is
1628 to the terminal. Although there's no way to know how many
1629 columns it occupies on a screen, it is a good assumption that
1630 a single byte code has 1-column width. */
1631 it->pixel_width = it->nglyphs = 1;
1632 if (it->glyph_row)
1633 append_glyph (it);
1635 else
1637 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1639 if (char_charset (it->char_to_display, charset_list, NULL))
1641 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1642 it->nglyphs = it->pixel_width;
1643 if (it->glyph_row)
1644 append_glyph (it);
1646 else
1648 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1650 eassert (it->what == IT_GLYPHLESS);
1651 produce_glyphless_glyph (it, acronym);
1655 done:
1656 /* Advance current_x by the pixel width as a convenience for
1657 the caller. */
1658 if (it->area == TEXT_AREA)
1659 it->current_x += it->pixel_width;
1660 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1661 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1664 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1665 Called from produce_composite_glyph for terminal frames if
1666 IT->glyph_row != NULL. IT->face_id contains the character's
1667 face. */
1669 static void
1670 append_composite_glyph (struct it *it)
1672 struct glyph *glyph;
1674 eassert (it->glyph_row);
1675 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1676 if (glyph < it->glyph_row->glyphs[1 + it->area])
1678 /* If the glyph row is reversed, we need to prepend the glyph
1679 rather than append it. */
1680 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1682 struct glyph *g;
1684 /* Make room for the new glyph. */
1685 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1686 g[1] = *g;
1687 glyph = it->glyph_row->glyphs[it->area];
1689 glyph->type = COMPOSITE_GLYPH;
1690 glyph->pixel_width = it->pixel_width;
1691 glyph->u.cmp.id = it->cmp_it.id;
1692 if (it->cmp_it.ch < 0)
1694 glyph->u.cmp.automatic = 0;
1695 glyph->u.cmp.id = it->cmp_it.id;
1697 else
1699 glyph->u.cmp.automatic = 1;
1700 glyph->u.cmp.id = it->cmp_it.id;
1701 glyph->slice.cmp.from = it->cmp_it.from;
1702 glyph->slice.cmp.to = it->cmp_it.to - 1;
1705 glyph->face_id = it->face_id;
1706 glyph->padding_p = 0;
1707 glyph->charpos = CHARPOS (it->position);
1708 glyph->object = it->object;
1709 if (it->bidi_p)
1711 glyph->resolved_level = it->bidi_it.resolved_level;
1712 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1713 glyph->bidi_type = it->bidi_it.type;
1715 else
1717 glyph->resolved_level = 0;
1718 glyph->bidi_type = UNKNOWN_BT;
1721 ++it->glyph_row->used[it->area];
1722 ++glyph;
1727 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1728 the composition. We simply produces components of the composition
1729 assuming that the terminal has a capability to layout/render it
1730 correctly. */
1732 static void
1733 produce_composite_glyph (struct it *it)
1735 if (it->cmp_it.ch < 0)
1737 struct composition *cmp = composition_table[it->cmp_it.id];
1739 it->pixel_width = cmp->width;
1741 else
1743 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1745 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1746 it->cmp_it.to, NULL);
1748 it->nglyphs = 1;
1749 if (it->glyph_row)
1750 append_composite_glyph (it);
1754 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1755 is a face ID to be used for the glyph. What is actually appended
1756 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1757 comes from it->nglyphs bytes). */
1759 static void
1760 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1762 struct glyph *glyph, *end;
1763 int i;
1765 eassert (it->glyph_row);
1766 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1767 end = it->glyph_row->glyphs[1 + it->area];
1769 /* If the glyph row is reversed, we need to prepend the glyph rather
1770 than append it. */
1771 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1773 struct glyph *g;
1774 int move_by = it->pixel_width;
1776 /* Make room for the new glyphs. */
1777 if (move_by > end - glyph) /* don't overstep end of this area */
1778 move_by = end - glyph;
1779 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1780 g[move_by] = *g;
1781 glyph = it->glyph_row->glyphs[it->area];
1782 end = glyph + move_by;
1785 if (glyph >= end)
1786 return;
1787 glyph->type = CHAR_GLYPH;
1788 glyph->pixel_width = 1;
1789 glyph->face_id = face_id;
1790 glyph->padding_p = 0;
1791 glyph->charpos = CHARPOS (it->position);
1792 glyph->object = it->object;
1793 if (it->bidi_p)
1795 glyph->resolved_level = it->bidi_it.resolved_level;
1796 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1797 glyph->bidi_type = it->bidi_it.type;
1799 else
1801 glyph->resolved_level = 0;
1802 glyph->bidi_type = UNKNOWN_BT;
1805 /* BIDI Note: we put the glyphs of characters left to right, even in
1806 the REVERSED_P case because we write to the terminal
1807 left-to-right. */
1808 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1810 if (i > 0)
1811 glyph[0] = glyph[-1];
1812 glyph->u.ch = str[i];
1813 ++it->glyph_row->used[it->area];
1814 ++glyph;
1818 /* Produce glyphs for a glyphless character for iterator IT.
1819 IT->glyphless_method specifies which method to use for displaying
1820 the character. See the description of enum
1821 glyphless_display_method in dispextern.h for the details.
1823 ACRONYM, if non-nil, is an acronym string for the character.
1825 The glyphs actually produced are of type CHAR_GLYPH. */
1827 static void
1828 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1830 int len, face_id = merge_glyphless_glyph_face (it);
1831 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1832 char const *str = " ";
1834 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1836 /* As there's no way to produce a thin space, we produce a space
1837 of canonical width. */
1838 len = 1;
1840 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1842 len = CHAR_WIDTH (it->c);
1843 if (len == 0)
1844 len = 1;
1845 else if (len > 4)
1846 len = 4;
1847 len = sprintf (buf, "[%.*s]", len, str);
1848 str = buf;
1850 else
1852 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1854 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1855 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1856 if (CONSP (acronym))
1857 acronym = XCDR (acronym);
1858 buf[0] = '[';
1859 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1860 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1861 buf[1 + len] = str[len];
1862 buf[1 + len] = ']';
1863 len += 2;
1865 else
1867 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1868 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1869 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1870 : sprintf (buf, "\\x%06X", it->c));
1872 str = buf;
1875 it->pixel_width = len;
1876 it->nglyphs = len;
1877 if (it->glyph_row)
1878 append_glyphless_glyph (it, face_id, str);
1882 /***********************************************************************
1883 Faces
1884 ***********************************************************************/
1886 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1887 one of the enumerators from enum no_color_bit, or a bit set built
1888 from them. Some display attributes may not be used together with
1889 color; the termcap capability `NC' specifies which ones. */
1891 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1892 (tty->TN_max_colors > 0 \
1893 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1894 : 1)
1896 /* Turn appearances of face FACE_ID on tty frame F on.
1897 FACE_ID is a realized face ID number, in the face cache. */
1899 static void
1900 turn_on_face (struct frame *f, int face_id)
1902 struct face *face = FACE_FROM_ID (f, face_id);
1903 unsigned long fg = face->foreground;
1904 unsigned long bg = face->background;
1905 struct tty_display_info *tty = FRAME_TTY (f);
1907 /* Use reverse video if the face specifies that.
1908 Do this first because TS_end_standout_mode may be the same
1909 as TS_exit_attribute_mode, which turns all appearances off. */
1910 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1911 && (inverse_video
1912 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1913 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1914 tty_toggle_highlight (tty);
1916 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1917 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1919 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1921 if (tty->TS_enter_italic_mode)
1922 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1923 else
1924 /* Italics mode is unavailable on many terminals. In that
1925 case, map slant to dimmed text; we want italic text to
1926 appear different and dimming is not otherwise used. */
1927 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1930 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1931 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1933 if (tty->TN_max_colors > 0)
1935 const char *ts;
1936 char *p;
1938 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1939 if (face_tty_specified_color (fg) && ts)
1941 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1942 OUTPUT (tty, p);
1943 xfree (p);
1946 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1947 if (face_tty_specified_color (bg) && ts)
1949 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1950 OUTPUT (tty, p);
1951 xfree (p);
1957 /* Turn off appearances of face FACE_ID on tty frame F. */
1959 static void
1960 turn_off_face (struct frame *f, int face_id)
1962 struct face *face = FACE_FROM_ID (f, face_id);
1963 struct tty_display_info *tty = FRAME_TTY (f);
1965 eassert (face != NULL);
1967 if (tty->TS_exit_attribute_mode)
1969 /* Capability "me" will turn off appearance modes double-bright,
1970 half-bright, reverse-video, standout, underline. It may or
1971 may not turn off alt-char-mode. */
1972 if (face->tty_bold_p
1973 || face->tty_italic_p
1974 || face->tty_reverse_p
1975 || face->tty_underline_p)
1977 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1978 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1979 tty->standout_mode = 0;
1982 else
1984 /* If we don't have "me" we can only have those appearances
1985 that have exit sequences defined. */
1986 if (face->tty_underline_p)
1987 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1990 /* Switch back to default colors. */
1991 if (tty->TN_max_colors > 0
1992 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1993 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1994 || (face->background != FACE_TTY_DEFAULT_COLOR
1995 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1996 OUTPUT1_IF (tty, tty->TS_orig_pair);
2000 /* Return true if the terminal on frame F supports all of the
2001 capabilities in CAPS simultaneously. */
2003 bool
2004 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2006 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2007 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2008 return 0;
2010 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2011 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2012 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2013 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2014 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2016 /* We can do it! */
2017 return 1;
2020 /* Return non-zero if the terminal is capable to display colors. */
2022 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2023 0, 1, 0,
2024 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2026 TERMINAL can be a terminal object, a frame, or nil (meaning the
2027 selected frame's terminal). This function always returns nil if
2028 TERMINAL does not refer to a text terminal. */)
2029 (Lisp_Object terminal)
2031 struct terminal *t = decode_tty_terminal (terminal);
2033 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2036 /* Return the number of supported colors. */
2037 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2038 Stty_display_color_cells, 0, 1, 0,
2039 doc: /* Return the number of colors supported by the tty device TERMINAL.
2041 TERMINAL can be a terminal object, a frame, or nil (meaning the
2042 selected frame's terminal). This function always returns 0 if
2043 TERMINAL does not refer to a text terminal. */)
2044 (Lisp_Object terminal)
2046 struct terminal *t = decode_tty_terminal (terminal);
2048 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2051 #ifndef DOS_NT
2053 /* Declare here rather than in the function, as in the rest of Emacs,
2054 to work around an HPUX compiler bug (?). See
2055 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2056 static int default_max_colors;
2057 static int default_max_pairs;
2058 static int default_no_color_video;
2059 static char *default_orig_pair;
2060 static char *default_set_foreground;
2061 static char *default_set_background;
2063 /* Save or restore the default color-related capabilities of this
2064 terminal. */
2065 static void
2066 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2069 if (save)
2071 dupstring (&default_orig_pair, tty->TS_orig_pair);
2072 dupstring (&default_set_foreground, tty->TS_set_foreground);
2073 dupstring (&default_set_background, tty->TS_set_background);
2074 default_max_colors = tty->TN_max_colors;
2075 default_max_pairs = tty->TN_max_pairs;
2076 default_no_color_video = tty->TN_no_color_video;
2078 else
2080 tty->TS_orig_pair = default_orig_pair;
2081 tty->TS_set_foreground = default_set_foreground;
2082 tty->TS_set_background = default_set_background;
2083 tty->TN_max_colors = default_max_colors;
2084 tty->TN_max_pairs = default_max_pairs;
2085 tty->TN_no_color_video = default_no_color_video;
2089 /* Setup one of the standard tty color schemes according to MODE.
2090 MODE's value is generally the number of colors which we want to
2091 support; zero means set up for the default capabilities, the ones
2092 we saw at init_tty time; -1 means turn off color support. */
2093 static void
2094 tty_setup_colors (struct tty_display_info *tty, int mode)
2096 /* Canonicalize all negative values of MODE. */
2097 if (mode < -1)
2098 mode = -1;
2100 switch (mode)
2102 case -1: /* no colors at all */
2103 tty->TN_max_colors = 0;
2104 tty->TN_max_pairs = 0;
2105 tty->TN_no_color_video = 0;
2106 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2107 break;
2108 case 0: /* default colors, if any */
2109 default:
2110 tty_default_color_capabilities (tty, 0);
2111 break;
2112 case 8: /* 8 standard ANSI colors */
2113 tty->TS_orig_pair = "\033[0m";
2114 #ifdef TERMINFO
2115 tty->TS_set_foreground = "\033[3%p1%dm";
2116 tty->TS_set_background = "\033[4%p1%dm";
2117 #else
2118 tty->TS_set_foreground = "\033[3%dm";
2119 tty->TS_set_background = "\033[4%dm";
2120 #endif
2121 tty->TN_max_colors = 8;
2122 tty->TN_max_pairs = 64;
2123 tty->TN_no_color_video = 0;
2124 break;
2128 void
2129 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2131 Lisp_Object tem, val;
2132 Lisp_Object color_mode;
2133 int mode;
2134 Lisp_Object tty_color_mode_alist
2135 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2137 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2138 val = CONSP (tem) ? XCDR (tem) : Qnil;
2140 if (INTEGERP (val))
2141 color_mode = val;
2142 else if (SYMBOLP (tty_color_mode_alist))
2144 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2145 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2147 else
2148 color_mode = Qnil;
2150 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2152 if (mode != tty->previous_color_mode)
2154 tty->previous_color_mode = mode;
2155 tty_setup_colors (tty , mode);
2156 /* This recomputes all the faces given the new color definitions. */
2157 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2161 #endif /* !DOS_NT */
2163 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2164 doc: /* Return the type of the tty device that TERMINAL uses.
2165 Returns nil if TERMINAL is not on a tty device.
2167 TERMINAL can be a terminal object, a frame, or nil (meaning the
2168 selected frame's terminal). */)
2169 (Lisp_Object terminal)
2171 struct terminal *t = decode_tty_terminal (terminal);
2173 return (t && t->display_info.tty->type
2174 ? build_string (t->display_info.tty->type) : Qnil);
2177 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2178 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2180 TERMINAL can be a terminal object, a frame, or nil (meaning the
2181 selected frame's terminal). This function always returns nil if
2182 TERMINAL is not on a tty device. */)
2183 (Lisp_Object terminal)
2185 struct terminal *t = decode_tty_terminal (terminal);
2187 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2190 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2191 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2192 This is used to override the terminfo data, for certain terminals that
2193 do not really do underlining, but say that they do. This function has
2194 no effect if used on a non-tty terminal.
2196 TERMINAL can be a terminal object, a frame or nil (meaning the
2197 selected frame's terminal). This function always returns nil if
2198 TERMINAL does not refer to a text terminal. */)
2199 (Lisp_Object terminal)
2201 struct terminal *t = decode_live_terminal (terminal);
2203 if (t->type == output_termcap)
2204 t->display_info.tty->TS_enter_underline_mode = 0;
2205 return Qnil;
2208 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2209 doc: /* Return the topmost terminal frame on TERMINAL.
2210 TERMINAL can be a terminal object, a frame or nil (meaning the
2211 selected frame's terminal). This function returns nil if TERMINAL
2212 does not refer to a text terminal. Otherwise, it returns the
2213 top-most frame on the text terminal. */)
2214 (Lisp_Object terminal)
2216 struct terminal *t = decode_live_terminal (terminal);
2218 if (t->type == output_termcap)
2219 return t->display_info.tty->top_frame;
2220 return Qnil;
2225 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2226 doc: /* Suspend the terminal device TTY.
2228 The device is restored to its default state, and Emacs ceases all
2229 access to the tty device. Frames that use the device are not deleted,
2230 but input is not read from them and if they change, their display is
2231 not updated.
2233 TTY may be a terminal object, a frame, or nil for the terminal device
2234 of the currently selected frame.
2236 This function runs `suspend-tty-functions' after suspending the
2237 device. The functions are run with one arg, the id of the suspended
2238 terminal device.
2240 `suspend-tty' does nothing if it is called on a device that is already
2241 suspended.
2243 A suspended tty may be resumed by calling `resume-tty' on it. */)
2244 (Lisp_Object tty)
2246 struct terminal *t = decode_tty_terminal (tty);
2247 FILE *f;
2249 if (!t)
2250 error ("Attempt to suspend a non-text terminal device");
2252 f = t->display_info.tty->input;
2254 if (f)
2256 /* First run `suspend-tty-functions' and then clean up the tty
2257 state because `suspend-tty-functions' might need to change
2258 the tty state. */
2259 Lisp_Object args[2];
2260 args[0] = intern ("suspend-tty-functions");
2261 XSETTERMINAL (args[1], t);
2262 Frun_hook_with_args (2, args);
2264 reset_sys_modes (t->display_info.tty);
2265 delete_keyboard_wait_descriptor (fileno (f));
2267 #ifndef MSDOS
2268 fclose (f);
2269 if (f != t->display_info.tty->output)
2270 fclose (t->display_info.tty->output);
2271 #endif
2273 t->display_info.tty->input = 0;
2274 t->display_info.tty->output = 0;
2276 if (FRAMEP (t->display_info.tty->top_frame))
2277 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2281 /* Clear display hooks to prevent further output. */
2282 clear_tty_hooks (t);
2284 return Qnil;
2287 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2288 doc: /* Resume the previously suspended terminal device TTY.
2289 The terminal is opened and reinitialized. Frames that are on the
2290 suspended terminal are revived.
2292 It is an error to resume a terminal while another terminal is active
2293 on the same device.
2295 This function runs `resume-tty-functions' after resuming the terminal.
2296 The functions are run with one arg, the id of the resumed terminal
2297 device.
2299 `resume-tty' does nothing if it is called on a device that is not
2300 suspended.
2302 TTY may be a terminal object, a frame, or nil (meaning the selected
2303 frame's terminal). */)
2304 (Lisp_Object tty)
2306 struct terminal *t = decode_tty_terminal (tty);
2307 int fd;
2309 if (!t)
2310 error ("Attempt to resume a non-text terminal device");
2312 if (!t->display_info.tty->input)
2314 if (get_named_terminal (t->display_info.tty->name))
2315 error ("Cannot resume display while another display is active on the same device");
2317 #ifdef MSDOS
2318 t->display_info.tty->output = stdout;
2319 t->display_info.tty->input = stdin;
2320 #else /* !MSDOS */
2321 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2322 t->display_info.tty->input = t->display_info.tty->output
2323 = fd < 0 ? 0 : fdopen (fd, "w+");
2325 if (! t->display_info.tty->input)
2327 int open_errno = errno;
2328 emacs_close (fd);
2329 report_file_errno ("Cannot reopen tty device",
2330 build_string (t->display_info.tty->name),
2331 open_errno);
2334 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2335 dissociate_if_controlling_tty (fd);
2336 #endif
2338 add_keyboard_wait_descriptor (fd);
2340 if (FRAMEP (t->display_info.tty->top_frame))
2342 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2343 int width, height;
2344 int old_height = FRAME_COLS (f);
2345 int old_width = FRAME_TOTAL_LINES (f);
2347 /* Check if terminal/window size has changed while the frame
2348 was suspended. */
2349 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2350 if (width != old_width || height != old_height)
2351 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2352 0, 0, 0, 0);
2353 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2356 set_tty_hooks (t);
2357 init_sys_modes (t->display_info.tty);
2360 /* Run `resume-tty-functions'. */
2361 Lisp_Object args[2];
2362 args[0] = intern ("resume-tty-functions");
2363 XSETTERMINAL (args[1], t);
2364 Frun_hook_with_args (2, args);
2368 set_tty_hooks (t);
2370 return Qnil;
2374 /***********************************************************************
2375 Mouse
2376 ***********************************************************************/
2378 #ifdef HAVE_GPM
2380 #ifndef HAVE_WINDOW_SYSTEM
2381 void
2382 term_mouse_moveto (int x, int y)
2384 /* TODO: how to set mouse position?
2385 const char *name;
2386 int fd;
2387 name = (const char *) ttyname (0);
2388 fd = emacs_open (name, O_WRONLY, 0);
2389 SOME_FUNCTION (x, y, fd);
2390 emacs_close (fd);
2391 last_mouse_x = x;
2392 last_mouse_y = y; */
2394 #endif /* HAVE_WINDOW_SYSTEM */
2396 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2397 void
2398 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2399 int start_hpos, int end_hpos,
2400 enum draw_glyphs_face draw)
2402 int nglyphs = end_hpos - start_hpos;
2403 struct frame *f = XFRAME (WINDOW_FRAME (w));
2404 struct tty_display_info *tty = FRAME_TTY (f);
2405 int face_id = tty->mouse_highlight.mouse_face_face_id;
2406 int save_x, save_y, pos_x, pos_y;
2408 if (end_hpos >= row->used[TEXT_AREA])
2409 nglyphs = row->used[TEXT_AREA] - start_hpos;
2411 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2412 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2414 /* Save current cursor co-ordinates. */
2415 save_y = curY (tty);
2416 save_x = curX (tty);
2417 cursor_to (f, pos_y, pos_x);
2419 if (draw == DRAW_MOUSE_FACE)
2420 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2421 nglyphs, face_id);
2422 else if (draw == DRAW_NORMAL_TEXT)
2423 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2425 cursor_to (f, save_y, save_x);
2428 static bool
2429 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2431 /* Has the mouse moved off the glyph it was on at the last sighting? */
2432 if (event->x != last_mouse_x || event->y != last_mouse_y)
2434 frame->mouse_moved = 1;
2435 note_mouse_highlight (frame, event->x, event->y);
2436 /* Remember which glyph we're now on. */
2437 last_mouse_x = event->x;
2438 last_mouse_y = event->y;
2439 return 1;
2441 return 0;
2444 /* Return the Time that corresponds to T. Wrap around on overflow. */
2445 static Time
2446 timeval_to_Time (struct timeval const *t)
2448 Time s_1000, ms;
2450 s_1000 = t->tv_sec;
2451 s_1000 *= 1000;
2452 ms = t->tv_usec / 1000;
2453 return s_1000 + ms;
2456 /* Return the current position of the mouse.
2458 Set *f to the frame the mouse is in, or zero if the mouse is in no
2459 Emacs frame. If it is set to zero, all the other arguments are
2460 garbage.
2462 Set *bar_window to Qnil, and *x and *y to the column and
2463 row of the character cell the mouse is over.
2465 Set *timeptr to the time the mouse was at the returned position.
2467 This clears mouse_moved until the next motion
2468 event arrives. */
2469 static void
2470 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2471 enum scroll_bar_part *part, Lisp_Object *x,
2472 Lisp_Object *y, Time *timeptr)
2474 struct timeval now;
2476 *fp = SELECTED_FRAME ();
2477 (*fp)->mouse_moved = 0;
2479 *bar_window = Qnil;
2480 *part = scroll_bar_above_handle;
2482 XSETINT (*x, last_mouse_x);
2483 XSETINT (*y, last_mouse_y);
2484 gettimeofday(&now, 0);
2485 *timeptr = timeval_to_Time (&now);
2488 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2490 If the event is a button press, then note that we have grabbed
2491 the mouse. */
2493 static Lisp_Object
2494 term_mouse_click (struct input_event *result, Gpm_Event *event,
2495 struct frame *f)
2497 struct timeval now;
2498 int i, j;
2500 result->kind = GPM_CLICK_EVENT;
2501 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2503 if (event->buttons & j) {
2504 result->code = i; /* button number */
2505 break;
2508 gettimeofday(&now, 0);
2509 result->timestamp = timeval_to_Time (&now);
2511 if (event->type & GPM_UP)
2512 result->modifiers = up_modifier;
2513 else if (event->type & GPM_DOWN)
2514 result->modifiers = down_modifier;
2515 else
2516 result->modifiers = 0;
2518 if (event->type & GPM_SINGLE)
2519 result->modifiers |= click_modifier;
2521 if (event->type & GPM_DOUBLE)
2522 result->modifiers |= double_modifier;
2524 if (event->type & GPM_TRIPLE)
2525 result->modifiers |= triple_modifier;
2527 if (event->type & GPM_DRAG)
2528 result->modifiers |= drag_modifier;
2530 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2532 /* 1 << KG_SHIFT */
2533 if (event->modifiers & (1 << 0))
2534 result->modifiers |= shift_modifier;
2536 /* 1 << KG_CTRL */
2537 if (event->modifiers & (1 << 2))
2538 result->modifiers |= ctrl_modifier;
2540 /* 1 << KG_ALT || KG_ALTGR */
2541 if (event->modifiers & (1 << 3)
2542 || event->modifiers & (1 << 1))
2543 result->modifiers |= meta_modifier;
2546 XSETINT (result->x, event->x);
2547 XSETINT (result->y, event->y);
2548 XSETFRAME (result->frame_or_window, f);
2549 result->arg = Qnil;
2550 return Qnil;
2554 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2556 struct frame *f = XFRAME (tty->top_frame);
2557 struct input_event ie;
2558 bool do_help = 0;
2559 int count = 0;
2561 EVENT_INIT (ie);
2562 ie.kind = NO_EVENT;
2563 ie.arg = Qnil;
2565 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2566 previous_help_echo_string = help_echo_string;
2567 help_echo_string = Qnil;
2569 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2571 if (!term_mouse_movement (f, event))
2572 help_echo_string = previous_help_echo_string;
2574 /* If the contents of the global variable help_echo_string
2575 has changed, generate a HELP_EVENT. */
2576 if (!NILP (help_echo_string)
2577 || !NILP (previous_help_echo_string))
2578 do_help = 1;
2580 goto done;
2582 else {
2583 f->mouse_moved = 0;
2584 term_mouse_click (&ie, event, f);
2587 done:
2588 if (ie.kind != NO_EVENT)
2590 kbd_buffer_store_event_hold (&ie, hold_quit);
2591 count++;
2594 if (do_help
2595 && !(hold_quit && hold_quit->kind != NO_EVENT))
2597 Lisp_Object frame;
2599 if (f)
2600 XSETFRAME (frame, f);
2601 else
2602 frame = Qnil;
2604 gen_help_event (help_echo_string, frame, help_echo_window,
2605 help_echo_object, help_echo_pos);
2606 count++;
2609 return count;
2612 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2613 0, 0, 0,
2614 doc: /* Open a connection to Gpm.
2615 Gpm-mouse can only be activated for one tty at a time. */)
2616 (void)
2618 struct frame *f = SELECTED_FRAME ();
2619 struct tty_display_info *tty
2620 = ((f)->output_method == output_termcap
2621 ? (f)->terminal->display_info.tty : NULL);
2622 Gpm_Connect connection;
2624 if (!tty)
2625 error ("Gpm-mouse only works in the GNU/Linux console");
2626 if (gpm_tty == tty)
2627 return Qnil; /* Already activated, nothing to do. */
2628 if (gpm_tty)
2629 error ("Gpm-mouse can only be activated for one tty at a time");
2631 connection.eventMask = ~0;
2632 connection.defaultMask = ~GPM_HARD;
2633 connection.maxMod = ~0;
2634 connection.minMod = 0;
2635 gpm_zerobased = 1;
2637 if (Gpm_Open (&connection, 0) < 0)
2638 error ("Gpm-mouse failed to connect to the gpm daemon");
2639 else
2641 gpm_tty = tty;
2642 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2643 to generate SIGIOs. Apparently we need to call reset_sys_modes
2644 before calling init_sys_modes. */
2645 reset_sys_modes (tty);
2646 init_sys_modes (tty);
2647 add_gpm_wait_descriptor (gpm_fd);
2648 return Qnil;
2652 void
2653 close_gpm (int fd)
2655 if (fd >= 0)
2656 delete_gpm_wait_descriptor (fd);
2657 while (Gpm_Close()); /* close all the stack */
2658 gpm_tty = NULL;
2661 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2662 0, 0, 0,
2663 doc: /* Close a connection to Gpm. */)
2664 (void)
2666 struct frame *f = SELECTED_FRAME ();
2667 struct tty_display_info *tty
2668 = ((f)->output_method == output_termcap
2669 ? (f)->terminal->display_info.tty : NULL);
2671 if (!tty || gpm_tty != tty)
2672 return Qnil; /* Not activated on this terminal, nothing to do. */
2674 close_gpm (gpm_fd);
2675 return Qnil;
2677 #endif /* HAVE_GPM */
2680 /***********************************************************************
2681 Menus
2682 ***********************************************************************/
2684 #if !defined (MSDOS)
2686 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2688 However, unlike on MSDOS, where the menu text is drawn directly to
2689 the display video memory, on a TTY we use display_string (see
2690 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2691 the menu items into the frame's 'desired_matrix' glyph matrix, and
2692 then call update_frame_with_menu to deliver the results to the
2693 glass. The previous contents of the screen, in the form of the
2694 current_matrix, is stashed away, and used to restore screen
2695 contents when the menu selection changes or when the final
2696 selection is made and the menu should be popped down.
2698 The idea of this implementation was suggested by Gerd Moellmann. */
2700 #define TTYM_FAILURE -1
2701 #define TTYM_SUCCESS 1
2702 #define TTYM_NO_SELECT 2
2703 #define TTYM_IA_SELECT 3
2704 #define TTYM_NEXT 4
2705 #define TTYM_PREV 5
2707 /* These hold text of the current and the previous menu help messages. */
2708 static const char *menu_help_message, *prev_menu_help_message;
2709 /* Pane number and item number of the menu item which generated the
2710 last menu help message. */
2711 static int menu_help_paneno, menu_help_itemno;
2713 static Lisp_Object Qtty_menu_navigation_map, Qtty_menu_exit;
2714 static Lisp_Object Qtty_menu_prev_item, Qtty_menu_next_item;
2715 static Lisp_Object Qtty_menu_next_menu, Qtty_menu_prev_menu;
2716 static Lisp_Object Qtty_menu_select, Qtty_menu_ignore;
2717 static Lisp_Object Qtty_menu_mouse_movement;
2719 typedef struct tty_menu_struct
2721 int count;
2722 char **text;
2723 struct tty_menu_struct **submenu;
2724 int *panenumber; /* Also used as enabled flag. */
2725 ptrdiff_t allocated;
2726 int panecount;
2727 int width;
2728 const char **help_text;
2729 } tty_menu;
2731 /* Create a brand new menu structure. */
2733 static tty_menu *
2734 tty_menu_create (void)
2736 return xzalloc (sizeof *tty_menu_create ());
2739 /* Allocate some (more) memory for MENU ensuring that there is room for one
2740 more item. */
2742 static void
2743 tty_menu_make_room (tty_menu *menu)
2745 if (menu->allocated == menu->count)
2747 ptrdiff_t allocated = menu->allocated;
2748 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2749 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2750 menu->submenu = xrealloc (menu->submenu,
2751 allocated * sizeof *menu->submenu);
2752 menu->panenumber = xrealloc (menu->panenumber,
2753 allocated * sizeof *menu->panenumber);
2754 menu->help_text = xrealloc (menu->help_text,
2755 allocated * sizeof *menu->help_text);
2756 menu->allocated = allocated;
2760 /* Search the given menu structure for a given pane number. */
2762 static tty_menu *
2763 tty_menu_search_pane (tty_menu *menu, int pane)
2765 int i;
2766 tty_menu *try;
2768 for (i = 0; i < menu->count; i++)
2769 if (menu->submenu[i])
2771 if (pane == menu->panenumber[i])
2772 return menu->submenu[i];
2773 try = tty_menu_search_pane (menu->submenu[i], pane);
2774 if (try)
2775 return try;
2777 return (tty_menu *) 0;
2780 /* Determine how much screen space a given menu needs. */
2782 static void
2783 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2785 int i, h2, w2, maxsubwidth, maxheight;
2787 maxsubwidth = menu->width;
2788 maxheight = menu->count;
2789 for (i = 0; i < menu->count; i++)
2791 if (menu->submenu[i])
2793 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2794 if (w2 > maxsubwidth) maxsubwidth = w2;
2795 if (i + h2 > maxheight) maxheight = i + h2;
2798 *width = maxsubwidth;
2799 *height = maxheight;
2802 static void
2803 mouse_get_xy (int *x, int *y)
2805 struct frame *sf = SELECTED_FRAME ();
2806 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2807 enum scroll_bar_part part_dummy;
2808 Time time_dummy;
2810 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2811 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2812 &lisp_dummy, &part_dummy,
2813 &lmx, &lmy,
2814 &time_dummy);
2815 if (!NILP (lmx))
2817 *x = XINT (lmx);
2818 *y = XINT (lmy);
2822 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2823 (zero-based). */
2825 static void
2826 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2827 int mx, int my, int first_item, bool disp_help)
2829 int i, face, width, enabled, mousehere, row, col;
2830 struct frame *sf = SELECTED_FRAME ();
2831 struct tty_display_info *tty = FRAME_TTY (sf);
2832 /* Don't try to display more menu items than the console can display
2833 using the available screen lines. Exclude the echo area line, as
2834 it will be overwritten by the help-echo anyway. */
2835 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2837 menu_help_message = NULL;
2839 width = menu->width;
2840 col = cursorX (tty);
2841 row = cursorY (tty);
2842 for (i = 0; i < max_items; i++)
2844 int max_width = width + 2; /* +2 for padding blanks on each side */
2845 int j = i + first_item;
2847 if (menu->submenu[j])
2848 max_width += 2; /* for displaying " >" after the item */
2849 enabled
2850 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2851 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2852 face = faces[enabled + mousehere * 2];
2853 /* Display the menu help string for the i-th menu item even if
2854 the menu item is currently disabled. That's what the GUI
2855 code does. */
2856 if (disp_help && enabled + mousehere * 2 >= 2)
2858 menu_help_message = menu->help_text[j];
2859 menu_help_paneno = pn - 1;
2860 menu_help_itemno = j;
2862 /* Take note of the coordinates of the active menu item, to
2863 display the cursor there. */
2864 if (mousehere)
2866 row = y + i;
2867 col = x;
2869 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2870 menu->submenu[j] != NULL);
2872 update_frame_with_menu (sf, row, col);
2875 /* --------------------------- X Menu emulation ---------------------- */
2877 /* Create a new pane and place it on the outer-most level. */
2879 static int
2880 tty_menu_add_pane (tty_menu *menu, const char *txt)
2882 int len;
2884 tty_menu_make_room (menu);
2885 menu->submenu[menu->count] = tty_menu_create ();
2886 menu->text[menu->count] = (char *)txt;
2887 menu->panenumber[menu->count] = ++menu->panecount;
2888 menu->help_text[menu->count] = NULL;
2889 menu->count++;
2891 /* Update the menu width, if necessary. */
2892 len = menu_item_width ((const unsigned char *) txt);
2893 if (len > menu->width)
2894 menu->width = len;
2896 return menu->panecount;
2899 /* Create a new item in a menu pane. */
2901 static bool
2902 tty_menu_add_selection (tty_menu *menu, int pane,
2903 char *txt, bool enable, char const *help_text)
2905 int len;
2907 if (pane)
2909 menu = tty_menu_search_pane (menu, pane);
2910 if (! menu)
2911 return 0;
2913 tty_menu_make_room (menu);
2914 menu->submenu[menu->count] = (tty_menu *) 0;
2915 menu->text[menu->count] = txt;
2916 menu->panenumber[menu->count] = enable;
2917 menu->help_text[menu->count] = help_text;
2918 menu->count++;
2920 /* Update the menu width, if necessary. */
2921 len = menu_item_width ((const unsigned char *) txt);
2922 if (len > menu->width)
2923 menu->width = len;
2925 return 1;
2928 /* Decide where the menu would be placed if requested at (X,Y). */
2930 static void
2931 tty_menu_locate (tty_menu *menu, int x, int y,
2932 int *ulx, int *uly, int *width, int *height)
2934 tty_menu_calc_size (menu, width, height);
2935 *ulx = x + 1;
2936 *uly = y;
2937 *width += 2;
2940 struct tty_menu_state
2942 struct glyph_matrix *screen_behind;
2943 tty_menu *menu;
2944 int pane;
2945 int x, y;
2948 /* Save away the contents of frame F's current frame matrix, and
2949 enable all its rows. Value is a glyph matrix holding the contents
2950 of F's current frame matrix with all its glyph rows enabled. */
2952 static struct glyph_matrix *
2953 save_and_enable_current_matrix (struct frame *f)
2955 int i;
2956 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2957 saved->nrows = f->current_matrix->nrows;
2958 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2960 for (i = 0; i < saved->nrows; ++i)
2962 struct glyph_row *from = f->current_matrix->rows + i;
2963 struct glyph_row *to = saved->rows + i;
2964 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2966 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2967 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2968 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2969 /* Make sure every row is enabled, or else update_frame will not
2970 redraw them. (Rows that are identical to what is already on
2971 screen will not be redrawn anyway.) */
2972 to->enabled_p = true;
2973 to->hash = from->hash;
2976 return saved;
2979 /* Restore the contents of frame F's desired frame matrix from SAVED,
2980 and free memory associated with SAVED. */
2982 static void
2983 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2985 int i;
2987 for (i = 0; i < saved->nrows; ++i)
2989 struct glyph_row *from = saved->rows + i;
2990 struct glyph_row *to = f->desired_matrix->rows + i;
2991 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2993 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2994 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2995 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2996 to->enabled_p = from->enabled_p;
2997 to->hash = from->hash;
3001 static void
3002 free_saved_screen (struct glyph_matrix *saved)
3004 int i;
3006 if (!saved)
3007 return; /* Already freed! */
3009 for (i = 0; i < saved->nrows; ++i)
3011 struct glyph_row *from = saved->rows + i;
3013 xfree (from->glyphs[TEXT_AREA]);
3016 xfree (saved->rows);
3017 xfree (saved);
3020 /* Update the display of frame F from its saved contents. */
3021 static void
3022 screen_update (struct frame *f, struct glyph_matrix *mtx)
3024 restore_desired_matrix (f, mtx);
3025 update_frame_with_menu (f, -1, -1);
3028 typedef enum {
3029 MI_QUIT_MENU = -1,
3030 MI_CONTINUE = 0,
3031 MI_ITEM_SELECTED = 1,
3032 MI_NEXT_ITEM = 2,
3033 MI_PREV_ITEM = 3,
3034 MI_SCROLL_FORWARD = 4,
3035 MI_SCROLL_BACK = 5
3036 } mi_result;
3038 /* Read user input and return X and Y coordinates where that input
3039 puts us. We only consider mouse movement and click events, and
3040 keyboard movement commands; the rest are ignored. */
3041 static mi_result
3042 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3043 bool *first_time)
3045 if (*first_time)
3047 *first_time = false;
3048 sf->mouse_moved = 1;
3050 else
3052 Lisp_Object cmd;
3053 bool usable_input = 1;
3054 mi_result st = MI_CONTINUE;
3055 struct tty_display_info *tty = FRAME_TTY (sf);
3056 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3058 /* Signal the keyboard reading routines we are displaying a menu
3059 on this terminal. */
3060 tty->showing_menu = 1;
3061 /* We want mouse movements be reported by read_menu_command. */
3062 do_mouse_tracking = Qt;
3063 do {
3064 cmd = read_menu_command ();
3065 } while (NILP (cmd));
3066 tty->showing_menu = 0;
3067 do_mouse_tracking = saved_mouse_tracking;
3069 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3070 /* If some input switched frames under our feet, exit the
3071 menu, since the menu faces are no longer valid, and the
3072 menu is no longer relevant anyway. */
3073 || sf != SELECTED_FRAME ())
3074 return MI_QUIT_MENU;
3075 if (EQ (cmd, Qtty_menu_mouse_movement))
3076 mouse_get_xy (x, y);
3077 else if (EQ (cmd, Qtty_menu_next_menu))
3079 usable_input = 0;
3080 st = MI_NEXT_ITEM;
3082 else if (EQ (cmd, Qtty_menu_prev_menu))
3084 usable_input = 0;
3085 st = MI_PREV_ITEM;
3087 else if (EQ (cmd, Qtty_menu_next_item))
3089 if (*y < max_y)
3090 *y += 1;
3091 else
3092 st = MI_SCROLL_FORWARD;
3094 else if (EQ (cmd, Qtty_menu_prev_item))
3096 if (*y > min_y)
3097 *y -= 1;
3098 else
3099 st = MI_SCROLL_BACK;
3101 else if (EQ (cmd, Qtty_menu_select))
3102 st = MI_ITEM_SELECTED;
3103 else if (!EQ (cmd, Qtty_menu_ignore))
3104 usable_input = 0;
3105 if (usable_input)
3106 sf->mouse_moved = 1;
3107 return st;
3109 return MI_CONTINUE;
3112 /* Display menu, wait for user's response, and return that response. */
3113 static int
3114 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3115 int x0, int y0, char **txt,
3116 void (*help_callback)(char const *, int, int),
3117 bool kbd_navigation)
3119 struct tty_menu_state *state;
3120 int statecount, x, y, i;
3121 bool leave, onepane;
3122 int result IF_LINT (= 0);
3123 int title_faces[4]; /* Face to display the menu title. */
3124 int faces[4], buffers_num_deleted = 0;
3125 struct frame *sf = SELECTED_FRAME ();
3126 struct tty_display_info *tty = FRAME_TTY (sf);
3127 bool first_time;
3128 Lisp_Object selectface;
3129 int first_item = 0;
3130 int col, row;
3131 USE_SAFE_ALLOCA;
3133 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3134 around the display. */
3135 if (x0 <= 0)
3136 x0 = 1;
3137 if (y0 <= 0)
3138 y0 = 1;
3140 SAFE_NALLOCA (state, 1, menu->panecount);
3141 memset (state, 0, sizeof (*state));
3142 faces[0]
3143 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3144 DEFAULT_FACE_ID, 1);
3145 faces[1]
3146 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3147 DEFAULT_FACE_ID, 1);
3148 selectface = intern ("tty-menu-selected-face");
3149 faces[2] = lookup_derived_face (sf, selectface,
3150 faces[0], 1);
3151 faces[3] = lookup_derived_face (sf, selectface,
3152 faces[1], 1);
3154 /* Make sure the menu title is always displayed with
3155 `tty-menu-selected-face', no matter where the mouse pointer is. */
3156 for (i = 0; i < 4; i++)
3157 title_faces[i] = faces[3];
3159 statecount = 1;
3161 /* Don't let the title for the "Buffers" popup menu include a
3162 digit (which is ugly).
3164 This is a terrible kludge, but I think the "Buffers" case is
3165 the only one where the title includes a number, so it doesn't
3166 seem to be necessary to make this more general. */
3167 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3169 menu->text[0][7] = '\0';
3170 buffers_num_deleted = 1;
3173 /* Force update of the current frame, so that the desired and the
3174 current matrices are identical. */
3175 update_frame_with_menu (sf, -1, -1);
3176 state[0].menu = menu;
3177 state[0].screen_behind = save_and_enable_current_matrix (sf);
3179 /* Display the menu title. We subtract 1 from x0 and y0 because we
3180 want to interpret them as zero-based column and row coordinates,
3181 and also because we want the first item of the menu, not its
3182 title, to appear at x0,y0. */
3183 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3185 /* Turn off the cursor. Otherwise it shows through the menu
3186 panes, which is ugly. */
3187 col = cursorX (tty);
3188 row = cursorY (tty);
3189 tty_hide_cursor (tty);
3191 if (buffers_num_deleted)
3192 menu->text[0][7] = ' ';
3193 onepane = menu->count == 1 && menu->submenu[0];
3194 if (onepane)
3196 menu->width = menu->submenu[0]->width;
3197 state[0].menu = menu->submenu[0];
3199 else
3201 state[0].menu = menu;
3203 state[0].x = x0 - 1;
3204 state[0].y = y0;
3205 state[0].pane = onepane;
3207 x = state[0].x;
3208 y = state[0].y;
3209 first_time = true;
3211 leave = 0;
3212 while (!leave)
3214 mi_result input_status;
3215 int min_y = state[0].y;
3216 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3218 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3219 if (input_status)
3221 leave = 1;
3222 switch (input_status)
3224 case MI_QUIT_MENU:
3225 /* Remove the last help-echo, so that it doesn't
3226 re-appear after "Quit". */
3227 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3228 result = TTYM_NO_SELECT;
3229 break;
3230 case MI_NEXT_ITEM:
3231 if (kbd_navigation)
3232 result = TTYM_NEXT;
3233 else
3234 leave = 0;
3235 break;
3236 case MI_PREV_ITEM:
3237 if (kbd_navigation)
3238 result = TTYM_PREV;
3239 else
3240 leave = 0;
3241 break;
3242 case MI_SCROLL_FORWARD:
3243 if (y - min_y == state[0].menu->count - 1 - first_item)
3245 y = min_y;
3246 first_item = 0;
3248 else
3249 first_item++;
3250 leave = 0;
3251 break;
3252 case MI_SCROLL_BACK:
3253 if (first_item == 0)
3255 y = max_y;
3256 first_item = state[0].menu->count - 1 - (y - min_y);
3258 else
3259 first_item--;
3260 leave = 0;
3261 break;
3262 default:
3263 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3264 break;
3267 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3269 sf->mouse_moved = 0;
3270 result = TTYM_IA_SELECT;
3271 for (i = 0; i < statecount; i++)
3272 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3274 int dy = y - state[i].y + first_item;
3275 if (0 <= dy && dy < state[i].menu->count)
3277 if (!state[i].menu->submenu[dy])
3279 if (state[i].menu->panenumber[dy])
3280 result = TTYM_SUCCESS;
3281 else
3282 result = TTYM_IA_SELECT;
3284 *pane = state[i].pane - 1;
3285 *selidx = dy;
3286 /* We hit some part of a menu, so drop extra menus that
3287 have been opened. That does not include an open and
3288 active submenu. */
3289 if (i != statecount - 2
3290 || state[i].menu->submenu[dy] != state[i + 1].menu)
3291 while (i != statecount - 1)
3293 statecount--;
3294 screen_update (sf, state[statecount].screen_behind);
3295 state[statecount].screen_behind = NULL;
3297 if (i == statecount - 1 && state[i].menu->submenu[dy])
3299 tty_menu_display (state[i].menu,
3300 state[i].x,
3301 state[i].y,
3302 state[i].pane,
3303 faces, x, y, first_item, 1);
3304 state[statecount].menu = state[i].menu->submenu[dy];
3305 state[statecount].pane = state[i].menu->panenumber[dy];
3306 state[statecount].screen_behind
3307 = save_and_enable_current_matrix (sf);
3308 state[statecount].x
3309 = state[i].x + state[i].menu->width + 2;
3310 state[statecount].y = y;
3311 statecount++;
3315 tty_menu_display (state[statecount - 1].menu,
3316 state[statecount - 1].x,
3317 state[statecount - 1].y,
3318 state[statecount - 1].pane,
3319 faces, x, y, first_item, 1);
3320 /* The call to display help-echo below will move the cursor,
3321 so remember its current position as computed by
3322 tty_menu_display. */
3323 col = cursorX (tty);
3324 row = cursorY (tty);
3327 /* Display the help-echo message for the currently-selected menu
3328 item. */
3329 if ((menu_help_message || prev_menu_help_message)
3330 && menu_help_message != prev_menu_help_message)
3332 help_callback (menu_help_message,
3333 menu_help_paneno, menu_help_itemno);
3334 /* Move the cursor to the beginning of the current menu
3335 item, so that screen readers and other accessibility aids
3336 know where the active region is. */
3337 cursor_to (sf, row, col);
3338 prev_menu_help_message = menu_help_message;
3340 /* Both tty_menu_display and help_callback invoke update_end,
3341 which calls tty_show_cursor. Re-hide it, so it doesn't show
3342 through the menus. */
3343 tty_hide_cursor (tty);
3344 fflush (tty->output);
3347 sf->mouse_moved = 0;
3348 screen_update (sf, state[0].screen_behind);
3349 while (statecount--)
3350 free_saved_screen (state[statecount].screen_behind);
3351 tty_show_cursor (tty); /* Turn cursor back on. */
3352 fflush (tty->output);
3354 /* Clean up any mouse events that are waiting inside Emacs event queue.
3355 These events are likely to be generated before the menu was even
3356 displayed, probably because the user pressed and released the button
3357 (which invoked the menu) too quickly. If we don't remove these events,
3358 Emacs will process them after we return and surprise the user. */
3359 discard_mouse_events ();
3360 if (!kbd_buffer_events_waiting ())
3361 clear_input_pending ();
3362 SAFE_FREE ();
3363 return result;
3366 /* Dispose of a menu. */
3368 static void
3369 tty_menu_destroy (tty_menu *menu)
3371 int i;
3372 if (menu->allocated)
3374 for (i = 0; i < menu->count; i++)
3375 if (menu->submenu[i])
3376 tty_menu_destroy (menu->submenu[i]);
3377 xfree (menu->text);
3378 xfree (menu->submenu);
3379 xfree (menu->panenumber);
3380 xfree (menu->help_text);
3382 xfree (menu);
3383 menu_help_message = prev_menu_help_message = NULL;
3386 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3388 PANE is the pane number, and ITEM is the menu item number in
3389 the menu (currently not used). */
3391 static void
3392 tty_menu_help_callback (char const *help_string, int pane, int item)
3394 Lisp_Object *first_item;
3395 Lisp_Object pane_name;
3396 Lisp_Object menu_object;
3398 first_item = XVECTOR (menu_items)->contents;
3399 if (EQ (first_item[0], Qt))
3400 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3401 else if (EQ (first_item[0], Qquote))
3402 /* This shouldn't happen, see xmenu_show. */
3403 pane_name = empty_unibyte_string;
3404 else
3405 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3407 /* (menu-item MENU-NAME PANE-NUMBER) */
3408 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3409 show_help_echo (help_string ? build_string (help_string) : Qnil,
3410 Qnil, menu_object, make_number (item));
3413 static void
3414 tty_pop_down_menu (Lisp_Object arg)
3416 tty_menu *menu = XSAVE_POINTER (arg, 0);
3418 block_input ();
3419 tty_menu_destroy (menu);
3420 unblock_input ();
3423 /* Return the zero-based index of the last menu-bar item on frame F. */
3424 static int
3425 tty_menu_last_menubar_item (struct frame *f)
3427 int i = 0;
3429 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3430 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3432 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3434 while (i < ASIZE (items))
3436 Lisp_Object str;
3438 str = AREF (items, i + 1);
3439 if (NILP (str))
3440 break;
3441 i += 4;
3443 i -= 4; /* Went one too far! */
3445 return i;
3448 /* Find in frame F's menu bar the menu item that is next or previous
3449 to the item at X/Y, and return that item's position in X/Y. WHICH
3450 says which one--next or previous--item to look for. X and Y are
3451 measured in character cells. This should only be called on TTY
3452 frames. */
3453 static void
3454 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3456 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3457 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3459 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3460 int last_i = tty_menu_last_menubar_item (f);
3461 int i, prev_x;
3463 /* This loop assumes a single menu-bar line, and will fail to
3464 find an item if it is not in the first line. Note that
3465 make_lispy_event in keyboard.c makes the same assumption. */
3466 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3468 Lisp_Object pos, str;
3469 int ix;
3471 str = AREF (items, i + 1);
3472 pos = AREF (items, i + 3);
3473 if (NILP (str))
3474 return;
3475 ix = XINT (pos);
3476 if (ix <= *x
3477 /* We use <= so the blank between 2 items on a TTY is
3478 considered part of the previous item. */
3479 && *x <= ix + menu_item_width (SDATA (str)))
3481 /* Found current item. Now compute the X coordinate of
3482 the previous or next item. */
3483 if (which == TTYM_NEXT)
3485 if (i < last_i)
3486 *x = XINT (AREF (items, i + 4 + 3));
3487 else
3488 *x = 0; /* Wrap around to the first item. */
3490 else if (prev_x < 0)
3492 /* Wrap around to the last item. */
3493 *x = XINT (AREF (items, last_i + 3));
3495 else
3496 *x = prev_x;
3497 return;
3499 prev_x = ix;
3504 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3505 Lisp_Object
3506 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3507 Lisp_Object title, const char **error_name)
3509 tty_menu *menu;
3510 int pane, selidx, lpane, status;
3511 Lisp_Object entry, pane_prefix;
3512 char *datap;
3513 int ulx, uly, width, height;
3514 int item_x, item_y;
3515 int dispwidth, dispheight;
3516 int i, j, lines, maxlines;
3517 int maxwidth;
3518 ptrdiff_t specpdl_count;
3520 eassert (FRAME_TERMCAP_P (f));
3522 *error_name = 0;
3523 if (menu_items_n_panes == 0)
3524 return Qnil;
3526 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3528 *error_name = "Empty menu";
3529 return Qnil;
3532 /* Make the menu on that window. */
3533 menu = tty_menu_create ();
3535 /* Don't GC while we prepare and show the menu, because we give the
3536 menu functions pointers to the contents of strings. */
3537 specpdl_count = inhibit_garbage_collection ();
3539 /* Avoid crashes if, e.g., another client will connect while we
3540 are in a menu. */
3541 temporarily_switch_to_single_kboard (f);
3543 /* Adjust coordinates to be root-window-relative. */
3544 item_x = x += f->left_pos;
3545 item_y = y += f->top_pos;
3547 /* Create all the necessary panes and their items. */
3548 USE_SAFE_ALLOCA;
3549 maxwidth = maxlines = lines = i = 0;
3550 lpane = TTYM_FAILURE;
3551 while (i < menu_items_used)
3553 if (EQ (AREF (menu_items, i), Qt))
3555 /* Create a new pane. */
3556 Lisp_Object pane_name, prefix;
3557 const char *pane_string;
3559 maxlines = max (maxlines, lines);
3560 lines = 0;
3561 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3562 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3563 pane_string = (NILP (pane_name)
3564 ? "" : SSDATA (pane_name));
3565 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3566 pane_string++;
3568 lpane = tty_menu_add_pane (menu, pane_string);
3569 if (lpane == TTYM_FAILURE)
3571 tty_menu_destroy (menu);
3572 *error_name = "Can't create pane";
3573 entry = Qnil;
3574 goto tty_menu_end;
3576 i += MENU_ITEMS_PANE_LENGTH;
3578 /* Find the width of the widest item in this pane. */
3579 j = i;
3580 while (j < menu_items_used)
3582 Lisp_Object item;
3583 item = AREF (menu_items, j);
3584 if (EQ (item, Qt))
3585 break;
3586 if (NILP (item))
3588 j++;
3589 continue;
3591 width = SBYTES (item);
3592 if (width > maxwidth)
3593 maxwidth = width;
3595 j += MENU_ITEMS_ITEM_LENGTH;
3598 /* Ignore a nil in the item list.
3599 It's meaningful only for dialog boxes. */
3600 else if (EQ (AREF (menu_items, i), Qquote))
3601 i += 1;
3602 else
3604 /* Create a new item within current pane. */
3605 Lisp_Object item_name, enable, descrip, help;
3606 char *item_data;
3607 char const *help_string;
3609 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3610 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3611 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3612 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3613 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3615 if (!NILP (descrip))
3617 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3618 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3619 for (j = SCHARS (item_name); j < maxwidth; j++)
3620 item_data[j] = ' ';
3621 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3622 item_data[j + SBYTES (descrip)] = 0;
3624 else
3625 item_data = SSDATA (item_name);
3627 if (lpane == TTYM_FAILURE
3628 || (! tty_menu_add_selection (menu, lpane, item_data,
3629 !NILP (enable), help_string)))
3631 tty_menu_destroy (menu);
3632 *error_name = "Can't add selection to menu";
3633 entry = Qnil;
3634 goto tty_menu_end;
3636 i += MENU_ITEMS_ITEM_LENGTH;
3637 lines++;
3641 maxlines = max (maxlines, lines);
3643 /* All set and ready to fly. */
3644 dispwidth = f->text_cols;
3645 dispheight = f->text_lines;
3646 x = min (x, dispwidth);
3647 y = min (y, dispheight);
3648 x = max (x, 1);
3649 y = max (y, 1);
3650 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3651 if (ulx + width > dispwidth)
3653 x -= (ulx + width) - dispwidth;
3654 ulx = dispwidth - width;
3656 if (uly + height > dispheight)
3658 y -= (uly + height) - dispheight;
3659 uly = dispheight - height;
3662 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3664 /* Move the menu away of the echo area, to avoid overwriting the
3665 menu with help echo messages or vice versa. */
3666 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3668 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3669 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3671 else
3673 y -= 2;
3674 uly -= 2;
3678 if (ulx < 0) x -= ulx;
3679 if (uly < 0) y -= uly;
3681 #if 0
3682 /* This code doesn't make sense on a TTY, since it can easily annul
3683 the adjustments above that carefully avoid truncation of the menu
3684 items. I think it was written to fix some problem that only
3685 happens on X11. */
3686 if (! for_click)
3688 /* If position was not given by a mouse click, adjust so upper left
3689 corner of the menu as a whole ends up at given coordinates. This
3690 is what x-popup-menu says in its documentation. */
3691 x += width / 2;
3692 y += 1.5 * height / (maxlines + 2);
3694 #endif
3696 pane = selidx = 0;
3698 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3700 specbind (Qoverriding_terminal_local_map,
3701 Fsymbol_value (Qtty_menu_navigation_map));
3702 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3703 tty_menu_help_callback,
3704 menuflags & MENU_KBD_NAVIGATION);
3705 entry = pane_prefix = Qnil;
3707 switch (status)
3709 case TTYM_SUCCESS:
3710 /* Find the item number SELIDX in pane number PANE. */
3711 i = 0;
3712 while (i < menu_items_used)
3714 if (EQ (AREF (menu_items, i), Qt))
3716 if (pane == 0)
3717 pane_prefix
3718 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3719 pane--;
3720 i += MENU_ITEMS_PANE_LENGTH;
3722 else
3724 if (pane == -1)
3726 if (selidx == 0)
3728 entry
3729 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3730 if (menuflags & MENU_KEYMAPS)
3732 entry = Fcons (entry, Qnil);
3733 if (!NILP (pane_prefix))
3734 entry = Fcons (pane_prefix, entry);
3736 break;
3738 selidx--;
3740 i += MENU_ITEMS_ITEM_LENGTH;
3743 break;
3745 case TTYM_NEXT:
3746 case TTYM_PREV:
3747 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3748 entry = Fcons (make_number (item_x), make_number (item_y));
3749 break;
3751 case TTYM_FAILURE:
3752 *error_name = "Can't activate menu";
3753 case TTYM_IA_SELECT:
3754 break;
3755 case TTYM_NO_SELECT:
3756 /* If the selected frame was changed while we displayed a menu,
3757 throw to top level in order to undo any temporary settings
3758 made by TTY menu code. */
3759 if (f != SELECTED_FRAME ())
3760 Ftop_level ();
3761 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3762 the menu was invoked with a mouse event as POSITION). */
3763 if (!(menuflags & MENU_FOR_CLICK))
3764 Fsignal (Qquit, Qnil);
3765 break;
3768 tty_menu_end:
3770 SAFE_FREE ();
3771 unbind_to (specpdl_count, Qnil);
3772 return entry;
3775 #endif /* !MSDOS */
3778 #ifndef MSDOS
3779 /***********************************************************************
3780 Initialization
3781 ***********************************************************************/
3783 /* Initialize the tty-dependent part of frame F. The frame must
3784 already have its device initialized. */
3786 void
3787 create_tty_output (struct frame *f)
3789 struct tty_output *t = xzalloc (sizeof *t);
3791 eassert (FRAME_TERMCAP_P (f));
3793 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3795 f->output_data.tty = t;
3798 /* Delete frame F's face cache, and its tty-dependent part. */
3800 static void
3801 tty_free_frame_resources (struct frame *f)
3803 eassert (FRAME_TERMCAP_P (f));
3804 free_frame_faces (f);
3805 xfree (f->output_data.tty);
3808 #else /* MSDOS */
3810 /* Delete frame F's face cache. */
3812 static void
3813 tty_free_frame_resources (struct frame *f)
3815 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3816 free_frame_faces (f);
3818 #endif /* MSDOS */
3820 /* Reset the hooks in TERMINAL. */
3822 static void
3823 clear_tty_hooks (struct terminal *terminal)
3825 terminal->rif = 0;
3826 terminal->cursor_to_hook = 0;
3827 terminal->raw_cursor_to_hook = 0;
3828 terminal->clear_to_end_hook = 0;
3829 terminal->clear_frame_hook = 0;
3830 terminal->clear_end_of_line_hook = 0;
3831 terminal->ins_del_lines_hook = 0;
3832 terminal->insert_glyphs_hook = 0;
3833 terminal->write_glyphs_hook = 0;
3834 terminal->delete_glyphs_hook = 0;
3835 terminal->ring_bell_hook = 0;
3836 terminal->reset_terminal_modes_hook = 0;
3837 terminal->set_terminal_modes_hook = 0;
3838 terminal->update_begin_hook = 0;
3839 terminal->update_end_hook = 0;
3840 terminal->set_terminal_window_hook = 0;
3841 terminal->mouse_position_hook = 0;
3842 terminal->frame_rehighlight_hook = 0;
3843 terminal->frame_raise_lower_hook = 0;
3844 terminal->fullscreen_hook = 0;
3845 terminal->menu_show_hook = 0;
3846 terminal->set_vertical_scroll_bar_hook = 0;
3847 terminal->set_horizontal_scroll_bar_hook = 0;
3848 terminal->condemn_scroll_bars_hook = 0;
3849 terminal->redeem_scroll_bar_hook = 0;
3850 terminal->judge_scroll_bars_hook = 0;
3851 terminal->read_socket_hook = 0;
3852 terminal->frame_up_to_date_hook = 0;
3854 /* Leave these two set, or suspended frames are not deleted
3855 correctly. */
3856 terminal->delete_frame_hook = &tty_free_frame_resources;
3857 terminal->delete_terminal_hook = &delete_tty;
3860 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3862 static void
3863 set_tty_hooks (struct terminal *terminal)
3865 terminal->cursor_to_hook = &tty_cursor_to;
3866 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3867 terminal->clear_to_end_hook = &tty_clear_to_end;
3868 terminal->clear_frame_hook = &tty_clear_frame;
3869 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3870 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3871 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3872 terminal->write_glyphs_hook = &tty_write_glyphs;
3873 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3874 terminal->ring_bell_hook = &tty_ring_bell;
3875 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3876 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3877 terminal->update_end_hook = &tty_update_end;
3878 #ifdef MSDOS
3879 terminal->menu_show_hook = &x_menu_show;
3880 #else
3881 terminal->menu_show_hook = &tty_menu_show;
3882 #endif
3883 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3884 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3885 terminal->delete_frame_hook = &tty_free_frame_resources;
3886 terminal->delete_terminal_hook = &delete_tty;
3887 /* Other hooks are NULL by default. */
3890 /* If FD is the controlling terminal, drop it. */
3891 static void
3892 dissociate_if_controlling_tty (int fd)
3894 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3895 so dissociate it by invoking setsid. */
3896 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3898 #ifdef TIOCNOTTY
3899 /* setsid failed, presumably because Emacs is already a process
3900 group leader. Fall back on the obsolescent way to dissociate
3901 a controlling tty. */
3902 sigset_t oldset;
3903 block_tty_out_signal (&oldset);
3904 ioctl (fd, TIOCNOTTY, 0);
3905 unblock_tty_out_signal (&oldset);
3906 #endif
3910 /* Create a termcap display on the tty device with the given name and
3911 type.
3913 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3914 Otherwise NAME should be a path to the tty device file,
3915 e.g. "/dev/pts/7".
3917 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3919 If MUST_SUCCEED is true, then all errors are fatal. */
3921 struct terminal *
3922 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3924 char *area;
3925 char **address = &area;
3926 int status;
3927 struct tty_display_info *tty = NULL;
3928 struct terminal *terminal = NULL;
3929 sigset_t oldset;
3930 bool ctty = false; /* True if asked to open controlling tty. */
3932 if (!terminal_type)
3933 maybe_fatal (must_succeed, 0,
3934 "Unknown terminal type",
3935 "Unknown terminal type");
3937 if (name == NULL)
3938 name = DEV_TTY;
3939 if (!strcmp (name, DEV_TTY))
3940 ctty = 1;
3942 /* If we already have a terminal on the given device, use that. If
3943 all such terminals are suspended, create a new one instead. */
3944 /* XXX Perhaps this should be made explicit by having init_tty
3945 always create a new terminal and separating terminal and frame
3946 creation on Lisp level. */
3947 terminal = get_named_terminal (name);
3948 if (terminal)
3949 return terminal;
3951 terminal = create_terminal (output_termcap, NULL);
3952 #ifdef MSDOS
3953 if (been_here > 0)
3954 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3955 name, "");
3956 been_here = 1;
3957 tty = &the_only_display_info;
3958 #else
3959 tty = xzalloc (sizeof *tty);
3960 #endif
3961 tty->top_frame = Qnil;
3962 tty->next = tty_list;
3963 tty_list = tty;
3965 terminal->display_info.tty = tty;
3966 tty->terminal = terminal;
3968 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3969 Wcm_clear (tty);
3971 encode_terminal_src_size = 0;
3972 encode_terminal_dst_size = 0;
3975 #ifndef DOS_NT
3976 set_tty_hooks (terminal);
3979 /* Open the terminal device. */
3981 /* If !ctty, don't recognize it as our controlling terminal, and
3982 don't make it the controlling tty if we don't have one now.
3984 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3985 defined on Hurd. On other systems, we need to explicitly
3986 dissociate ourselves from the controlling tty when we want to
3987 open a frame on the same terminal. */
3988 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3989 int fd = emacs_open (name, flags, 0);
3990 tty->input = tty->output
3991 = ((fd < 0 || ! isatty (fd))
3992 ? NULL
3993 : fdopen (fd, "w+"));
3995 if (! tty->input)
3997 char const *diagnostic
3998 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3999 emacs_close (fd);
4000 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4003 tty->name = xstrdup (name);
4004 terminal->name = xstrdup (name);
4006 if (!O_IGNORE_CTTY && !ctty)
4007 dissociate_if_controlling_tty (fd);
4010 tty->type = xstrdup (terminal_type);
4012 add_keyboard_wait_descriptor (fileno (tty->input));
4014 Wcm_clear (tty);
4016 /* On some systems, tgetent tries to access the controlling
4017 terminal. */
4018 block_tty_out_signal (&oldset);
4019 status = tgetent (tty->termcap_term_buffer, terminal_type);
4020 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4021 emacs_abort ();
4022 unblock_tty_out_signal (&oldset);
4024 if (status < 0)
4026 #ifdef TERMINFO
4027 maybe_fatal (must_succeed, terminal,
4028 "Cannot open terminfo database file",
4029 "Cannot open terminfo database file");
4030 #else
4031 maybe_fatal (must_succeed, terminal,
4032 "Cannot open termcap database file",
4033 "Cannot open termcap database file");
4034 #endif
4036 if (status == 0)
4038 maybe_fatal (must_succeed, terminal,
4039 "Terminal type %s is not defined",
4040 "Terminal type %s is not defined.\n\
4041 If that is not the actual type of terminal you have,\n\
4042 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4043 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4044 #ifdef TERMINFO
4045 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4046 #else
4047 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4048 #endif
4049 terminal_type);
4052 area = tty->termcap_strings_buffer;
4053 tty->TS_ins_line = tgetstr ("al", address);
4054 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4055 tty->TS_bell = tgetstr ("bl", address);
4056 BackTab (tty) = tgetstr ("bt", address);
4057 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4058 tty->TS_clr_line = tgetstr ("ce", address);
4059 tty->TS_clr_frame = tgetstr ("cl", address);
4060 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4061 AbsPosition (tty) = tgetstr ("cm", address);
4062 CR (tty) = tgetstr ("cr", address);
4063 tty->TS_set_scroll_region = tgetstr ("cs", address);
4064 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4065 RowPosition (tty) = tgetstr ("cv", address);
4066 tty->TS_del_char = tgetstr ("dc", address);
4067 tty->TS_del_multi_chars = tgetstr ("DC", address);
4068 tty->TS_del_line = tgetstr ("dl", address);
4069 tty->TS_del_multi_lines = tgetstr ("DL", address);
4070 tty->TS_delete_mode = tgetstr ("dm", address);
4071 tty->TS_end_delete_mode = tgetstr ("ed", address);
4072 tty->TS_end_insert_mode = tgetstr ("ei", address);
4073 Home (tty) = tgetstr ("ho", address);
4074 tty->TS_ins_char = tgetstr ("ic", address);
4075 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4076 tty->TS_insert_mode = tgetstr ("im", address);
4077 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4078 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4079 tty->TS_keypad_mode = tgetstr ("ks", address);
4080 LastLine (tty) = tgetstr ("ll", address);
4081 Right (tty) = tgetstr ("nd", address);
4082 Down (tty) = tgetstr ("do", address);
4083 if (!Down (tty))
4084 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4085 if (tgetflag ("bs"))
4086 Left (tty) = "\b"; /* Can't possibly be longer! */
4087 else /* (Actually, "bs" is obsolete...) */
4088 Left (tty) = tgetstr ("le", address);
4089 if (!Left (tty))
4090 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4091 tty->TS_pad_char = tgetstr ("pc", address);
4092 tty->TS_repeat = tgetstr ("rp", address);
4093 tty->TS_end_standout_mode = tgetstr ("se", address);
4094 tty->TS_fwd_scroll = tgetstr ("sf", address);
4095 tty->TS_standout_mode = tgetstr ("so", address);
4096 tty->TS_rev_scroll = tgetstr ("sr", address);
4097 tty->Wcm->cm_tab = tgetstr ("ta", address);
4098 tty->TS_end_termcap_modes = tgetstr ("te", address);
4099 tty->TS_termcap_modes = tgetstr ("ti", address);
4100 Up (tty) = tgetstr ("up", address);
4101 tty->TS_visible_bell = tgetstr ("vb", address);
4102 tty->TS_cursor_normal = tgetstr ("ve", address);
4103 tty->TS_cursor_visible = tgetstr ("vs", address);
4104 tty->TS_cursor_invisible = tgetstr ("vi", address);
4105 tty->TS_set_window = tgetstr ("wi", address);
4107 tty->TS_enter_underline_mode = tgetstr ("us", address);
4108 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4109 tty->TS_enter_bold_mode = tgetstr ("md", address);
4110 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4111 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4112 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4113 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4114 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4115 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4117 MultiUp (tty) = tgetstr ("UP", address);
4118 MultiDown (tty) = tgetstr ("DO", address);
4119 MultiLeft (tty) = tgetstr ("LE", address);
4120 MultiRight (tty) = tgetstr ("RI", address);
4122 /* SVr4/ANSI color support. If "op" isn't available, don't support
4123 color because we can't switch back to the default foreground and
4124 background. */
4125 tty->TS_orig_pair = tgetstr ("op", address);
4126 if (tty->TS_orig_pair)
4128 tty->TS_set_foreground = tgetstr ("AF", address);
4129 tty->TS_set_background = tgetstr ("AB", address);
4130 if (!tty->TS_set_foreground)
4132 /* SVr4. */
4133 tty->TS_set_foreground = tgetstr ("Sf", address);
4134 tty->TS_set_background = tgetstr ("Sb", address);
4137 tty->TN_max_colors = tgetnum ("Co");
4138 tty->TN_max_pairs = tgetnum ("pa");
4140 tty->TN_no_color_video = tgetnum ("NC");
4141 if (tty->TN_no_color_video == -1)
4142 tty->TN_no_color_video = 0;
4145 tty_default_color_capabilities (tty, 1);
4147 MagicWrap (tty) = tgetflag ("xn");
4148 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4149 the former flag imply the latter. */
4150 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4151 tty->memory_below_frame = tgetflag ("db");
4152 tty->TF_hazeltine = tgetflag ("hz");
4153 tty->must_write_spaces = tgetflag ("in");
4154 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4155 tty->TF_insmode_motion = tgetflag ("mi");
4156 tty->TF_standout_motion = tgetflag ("ms");
4157 tty->TF_underscore = tgetflag ("ul");
4158 tty->TF_teleray = tgetflag ("xt");
4160 #else /* DOS_NT */
4161 #ifdef WINDOWSNT
4163 struct frame *f = XFRAME (selected_frame);
4164 int height, width;
4166 initialize_w32_display (terminal, &width, &height);
4168 FrameRows (tty) = height;
4169 FrameCols (tty) = width;
4170 tty->specified_window = height;
4172 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4173 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4174 tty->char_ins_del_ok = 1;
4175 baud_rate = 19200;
4177 #else /* MSDOS */
4179 int height, width;
4180 if (strcmp (terminal_type, "internal") == 0)
4181 terminal->type = output_msdos_raw;
4182 initialize_msdos_display (terminal);
4184 get_tty_size (fileno (tty->input), &width, &height);
4185 FrameCols (tty) = width;
4186 FrameRows (tty) = height;
4187 tty->char_ins_del_ok = 0;
4188 init_baud_rate (fileno (tty->input));
4190 #endif /* MSDOS */
4191 tty->output = stdout;
4192 tty->input = stdin;
4193 /* The following two are inaccessible from w32console.c. */
4194 terminal->delete_frame_hook = &tty_free_frame_resources;
4195 terminal->delete_terminal_hook = &delete_tty;
4197 tty->name = xstrdup (name);
4198 terminal->name = xstrdup (name);
4199 tty->type = xstrdup (terminal_type);
4201 add_keyboard_wait_descriptor (0);
4203 tty->delete_in_insert_mode = 1;
4205 UseTabs (tty) = 0;
4206 tty->scroll_region_ok = 0;
4208 /* Seems to insert lines when it's not supposed to, messing up the
4209 display. In doing a trace, it didn't seem to be called much, so I
4210 don't think we're losing anything by turning it off. */
4211 tty->line_ins_del_ok = 0;
4213 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4214 #endif /* DOS_NT */
4216 #ifdef HAVE_GPM
4217 terminal->mouse_position_hook = term_mouse_position;
4218 tty->mouse_highlight.mouse_face_window = Qnil;
4219 #endif
4221 terminal->kboard = allocate_kboard (Qnil);
4222 terminal->kboard->reference_count++;
4223 /* Don't let the initial kboard remain current longer than necessary.
4224 That would cause problems if a file loaded on startup tries to
4225 prompt in the mini-buffer. */
4226 if (current_kboard == initial_kboard)
4227 current_kboard = terminal->kboard;
4228 #ifndef DOS_NT
4229 term_get_fkeys (address, terminal->kboard);
4231 /* Get frame size from system, or else from termcap. */
4233 int height, width;
4234 get_tty_size (fileno (tty->input), &width, &height);
4235 FrameCols (tty) = width;
4236 FrameRows (tty) = height;
4239 if (FrameCols (tty) <= 0)
4240 FrameCols (tty) = tgetnum ("co");
4241 if (FrameRows (tty) <= 0)
4242 FrameRows (tty) = tgetnum ("li");
4244 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4245 maybe_fatal (must_succeed, terminal,
4246 "Screen size %dx%d is too small",
4247 "Screen size %dx%d is too small",
4248 FrameCols (tty), FrameRows (tty));
4250 TabWidth (tty) = tgetnum ("tw");
4252 if (!tty->TS_bell)
4253 tty->TS_bell = "\07";
4255 if (!tty->TS_fwd_scroll)
4256 tty->TS_fwd_scroll = Down (tty);
4258 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4260 if (TabWidth (tty) < 0)
4261 TabWidth (tty) = 8;
4263 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4264 and newer termcap doc does not seem to say there is a default.
4265 if (!tty->Wcm->cm_tab)
4266 tty->Wcm->cm_tab = "\t";
4269 /* We don't support standout modes that use `magic cookies', so
4270 turn off any that do. */
4271 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4273 tty->TS_standout_mode = 0;
4274 tty->TS_end_standout_mode = 0;
4276 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4278 tty->TS_enter_underline_mode = 0;
4279 tty->TS_exit_underline_mode = 0;
4282 /* If there's no standout mode, try to use underlining instead. */
4283 if (tty->TS_standout_mode == 0)
4285 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4286 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4289 /* If no `se' string, try using a `me' string instead.
4290 If that fails, we can't use standout mode at all. */
4291 if (tty->TS_end_standout_mode == 0)
4293 char *s = tgetstr ("me", address);
4294 if (s != 0)
4295 tty->TS_end_standout_mode = s;
4296 else
4297 tty->TS_standout_mode = 0;
4300 if (tty->TF_teleray)
4302 tty->Wcm->cm_tab = 0;
4303 /* We can't support standout mode, because it uses magic cookies. */
4304 tty->TS_standout_mode = 0;
4305 /* But that means we cannot rely on ^M to go to column zero! */
4306 CR (tty) = 0;
4307 /* LF can't be trusted either -- can alter hpos. */
4308 /* If move at column 0 thru a line with TS_standout_mode. */
4309 Down (tty) = 0;
4312 tty->specified_window = FrameRows (tty);
4314 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4316 maybe_fatal (must_succeed, terminal,
4317 "Terminal type \"%s\" is not powerful enough to run Emacs",
4318 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4319 It lacks the ability to position the cursor.\n\
4320 If that is not the actual type of terminal you have,\n\
4321 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4322 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4323 # ifdef TERMINFO
4324 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4325 # else /* TERMCAP */
4326 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4327 # endif /* TERMINFO */
4328 terminal_type);
4331 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4332 maybe_fatal (must_succeed, terminal,
4333 "Could not determine the frame size",
4334 "Could not determine the frame size");
4336 tty->delete_in_insert_mode
4337 = tty->TS_delete_mode && tty->TS_insert_mode
4338 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4340 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4342 tty->scroll_region_ok
4343 = (tty->Wcm->cm_abs
4344 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4346 tty->line_ins_del_ok
4347 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4348 && (tty->TS_del_line || tty->TS_del_multi_lines))
4349 || (tty->scroll_region_ok
4350 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4352 tty->char_ins_del_ok
4353 = ((tty->TS_ins_char || tty->TS_insert_mode
4354 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4355 && (tty->TS_del_char || tty->TS_del_multi_chars));
4357 init_baud_rate (fileno (tty->input));
4359 #endif /* not DOS_NT */
4361 /* Init system terminal modes (RAW or CBREAK, etc.). */
4362 init_sys_modes (tty);
4364 return terminal;
4368 static void
4369 vfatal (const char *str, va_list ap)
4371 fprintf (stderr, "emacs: ");
4372 vfprintf (stderr, str, ap);
4373 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4374 fprintf (stderr, "\n");
4375 fflush (stderr);
4376 exit (1);
4380 /* Auxiliary error-handling function for init_tty.
4381 Delete TERMINAL, then call error or fatal with str1 or str2,
4382 respectively, according to whether MUST_SUCCEED is true. */
4384 static void
4385 maybe_fatal (bool must_succeed, struct terminal *terminal,
4386 const char *str1, const char *str2, ...)
4388 va_list ap;
4389 va_start (ap, str2);
4390 if (terminal)
4391 delete_tty (terminal);
4393 if (must_succeed)
4394 vfatal (str2, ap);
4395 else
4396 verror (str1, ap);
4399 void
4400 fatal (const char *str, ...)
4402 va_list ap;
4403 va_start (ap, str);
4404 vfatal (str, ap);
4409 /* Delete the given tty terminal, closing all frames on it. */
4411 static void
4412 delete_tty (struct terminal *terminal)
4414 struct tty_display_info *tty;
4416 /* Protect against recursive calls. delete_frame in
4417 delete_terminal calls us back when it deletes our last frame. */
4418 if (!terminal->name)
4419 return;
4421 eassert (terminal->type == output_termcap);
4423 tty = terminal->display_info.tty;
4425 if (tty == tty_list)
4426 tty_list = tty->next;
4427 else
4429 struct tty_display_info *p;
4430 for (p = tty_list; p && p->next != tty; p = p->next)
4433 if (! p)
4434 /* This should not happen. */
4435 emacs_abort ();
4437 p->next = tty->next;
4438 tty->next = 0;
4441 /* reset_sys_modes needs a valid device, so this call needs to be
4442 before delete_terminal. */
4443 reset_sys_modes (tty);
4445 delete_terminal (terminal);
4447 xfree (tty->name);
4448 xfree (tty->type);
4450 if (tty->input)
4452 delete_keyboard_wait_descriptor (fileno (tty->input));
4453 if (tty->input != stdin)
4454 fclose (tty->input);
4456 if (tty->output && tty->output != stdout && tty->output != tty->input)
4457 fclose (tty->output);
4458 if (tty->termscript)
4459 fclose (tty->termscript);
4461 xfree (tty->old_tty);
4462 xfree (tty->Wcm);
4463 xfree (tty);
4466 void
4467 syms_of_term (void)
4469 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4470 doc: /* Non-nil means the system uses terminfo rather than termcap.
4471 This variable can be used by terminal emulator packages. */);
4472 #ifdef TERMINFO
4473 system_uses_terminfo = 1;
4474 #else
4475 system_uses_terminfo = 0;
4476 #endif
4478 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4479 doc: /* Functions run after suspending a tty.
4480 The functions are run with one argument, the terminal object to be suspended.
4481 See `suspend-tty'. */);
4482 Vsuspend_tty_functions = Qnil;
4485 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4486 doc: /* Functions run after resuming a tty.
4487 The functions are run with one argument, the terminal object that was revived.
4488 See `resume-tty'. */);
4489 Vresume_tty_functions = Qnil;
4491 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4492 doc: /* Non-nil means to make the cursor very visible.
4493 This only has an effect when running in a text terminal.
4494 What means \"very visible\" is up to your terminal. It may make the cursor
4495 bigger, or it may make it blink, or it may do nothing at all. */);
4496 visible_cursor = 1;
4498 defsubr (&Stty_display_color_p);
4499 defsubr (&Stty_display_color_cells);
4500 defsubr (&Stty_no_underline);
4501 defsubr (&Stty_type);
4502 defsubr (&Scontrolling_tty_p);
4503 defsubr (&Stty_top_frame);
4504 defsubr (&Ssuspend_tty);
4505 defsubr (&Sresume_tty);
4506 #ifdef HAVE_GPM
4507 defsubr (&Sgpm_mouse_start);
4508 defsubr (&Sgpm_mouse_stop);
4509 #endif /* HAVE_GPM */
4511 #ifndef DOS_NT
4512 default_orig_pair = NULL;
4513 default_set_foreground = NULL;
4514 default_set_background = NULL;
4515 #endif /* !DOS_NT */
4517 encode_terminal_src = NULL;
4518 encode_terminal_dst = NULL;
4520 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4521 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4523 #ifndef MSDOS
4524 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4525 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4526 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4527 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4528 DEFSYM (Qtty_menu_select, "tty-menu-select");
4529 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4530 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4531 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4532 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4533 #endif