Merge from emacs-24; up to r117586
[emacs/old-mirror.git] / src / term.c
blob0c36469f6554e57e100af33c7374f5799eacd277
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 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1517 emacs_abort ();
1518 glyph->bidi_type = it->bidi_it.type;
1520 else
1522 glyph->resolved_level = 0;
1523 glyph->bidi_type = UNKNOWN_BT;
1526 ++it->glyph_row->used[it->area];
1527 ++glyph;
1531 /* For external use. */
1532 void
1533 tty_append_glyph (struct it *it)
1535 append_glyph (it);
1539 /* Produce glyphs for the display element described by IT. *IT
1540 specifies what we want to produce a glyph for (character, image, ...),
1541 and where in the glyph matrix we currently are (glyph row and hpos).
1542 produce_glyphs fills in output fields of *IT with information such as the
1543 pixel width and height of a character, and maybe output actual glyphs at
1544 the same time if IT->glyph_row is non-null. For an overview, see
1545 the explanation in dispextern.h, before the definition of the
1546 display_element_type enumeration.
1548 produce_glyphs also stores the result of glyph width, ascent
1549 etc. computations in *IT.
1551 IT->glyph_row may be null, in which case produce_glyphs does not
1552 actually fill in the glyphs. This is used in the move_* functions
1553 in xdisp.c for text width and height computations.
1555 Callers usually don't call produce_glyphs directly;
1556 instead they use the macro PRODUCE_GLYPHS. */
1558 void
1559 produce_glyphs (struct it *it)
1561 /* If a hook is installed, let it do the work. */
1563 /* Nothing but characters are supported on terminal frames. */
1564 eassert (it->what == IT_CHARACTER
1565 || it->what == IT_COMPOSITION
1566 || it->what == IT_STRETCH
1567 || it->what == IT_GLYPHLESS);
1569 if (it->what == IT_STRETCH)
1571 produce_stretch_glyph (it);
1572 goto done;
1575 if (it->what == IT_COMPOSITION)
1577 produce_composite_glyph (it);
1578 goto done;
1581 if (it->what == IT_GLYPHLESS)
1583 produce_glyphless_glyph (it, Qnil);
1584 goto done;
1587 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1589 it->pixel_width = it->nglyphs = 1;
1590 if (it->glyph_row)
1591 append_glyph (it);
1593 else if (it->char_to_display == '\n')
1594 it->pixel_width = it->nglyphs = 0;
1595 else if (it->char_to_display == '\t')
1597 int absolute_x = (it->current_x
1598 + it->continuation_lines_width);
1599 int next_tab_x
1600 = (((1 + absolute_x + it->tab_width - 1)
1601 / it->tab_width)
1602 * it->tab_width);
1603 int nspaces;
1605 /* If part of the TAB has been displayed on the previous line
1606 which is continued now, continuation_lines_width will have
1607 been incremented already by the part that fitted on the
1608 continued line. So, we will get the right number of spaces
1609 here. */
1610 nspaces = next_tab_x - absolute_x;
1612 if (it->glyph_row)
1614 int n = nspaces;
1616 it->char_to_display = ' ';
1617 it->pixel_width = it->len = 1;
1619 while (n--)
1620 append_glyph (it);
1623 it->pixel_width = nspaces;
1624 it->nglyphs = nspaces;
1626 else if (CHAR_BYTE8_P (it->char_to_display))
1628 /* Coming here means that we must send the raw 8-bit byte as is
1629 to the terminal. Although there's no way to know how many
1630 columns it occupies on a screen, it is a good assumption that
1631 a single byte code has 1-column width. */
1632 it->pixel_width = it->nglyphs = 1;
1633 if (it->glyph_row)
1634 append_glyph (it);
1636 else
1638 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1640 if (char_charset (it->char_to_display, charset_list, NULL))
1642 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1643 it->nglyphs = it->pixel_width;
1644 if (it->glyph_row)
1645 append_glyph (it);
1647 else
1649 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1651 eassert (it->what == IT_GLYPHLESS);
1652 produce_glyphless_glyph (it, acronym);
1656 done:
1657 /* Advance current_x by the pixel width as a convenience for
1658 the caller. */
1659 if (it->area == TEXT_AREA)
1660 it->current_x += it->pixel_width;
1661 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1662 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1665 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1666 Called from produce_composite_glyph for terminal frames if
1667 IT->glyph_row != NULL. IT->face_id contains the character's
1668 face. */
1670 static void
1671 append_composite_glyph (struct it *it)
1673 struct glyph *glyph;
1675 eassert (it->glyph_row);
1676 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1677 if (glyph < it->glyph_row->glyphs[1 + it->area])
1679 /* If the glyph row is reversed, we need to prepend the glyph
1680 rather than append it. */
1681 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1683 struct glyph *g;
1685 /* Make room for the new glyph. */
1686 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1687 g[1] = *g;
1688 glyph = it->glyph_row->glyphs[it->area];
1690 glyph->type = COMPOSITE_GLYPH;
1691 glyph->pixel_width = it->pixel_width;
1692 glyph->u.cmp.id = it->cmp_it.id;
1693 if (it->cmp_it.ch < 0)
1695 glyph->u.cmp.automatic = 0;
1696 glyph->u.cmp.id = it->cmp_it.id;
1698 else
1700 glyph->u.cmp.automatic = 1;
1701 glyph->u.cmp.id = it->cmp_it.id;
1702 glyph->slice.cmp.from = it->cmp_it.from;
1703 glyph->slice.cmp.to = it->cmp_it.to - 1;
1706 glyph->face_id = it->face_id;
1707 glyph->padding_p = 0;
1708 glyph->charpos = CHARPOS (it->position);
1709 glyph->object = it->object;
1710 if (it->bidi_p)
1712 glyph->resolved_level = it->bidi_it.resolved_level;
1713 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1714 emacs_abort ();
1715 glyph->bidi_type = it->bidi_it.type;
1717 else
1719 glyph->resolved_level = 0;
1720 glyph->bidi_type = UNKNOWN_BT;
1723 ++it->glyph_row->used[it->area];
1724 ++glyph;
1729 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1730 the composition. We simply produces components of the composition
1731 assuming that the terminal has a capability to layout/render it
1732 correctly. */
1734 static void
1735 produce_composite_glyph (struct it *it)
1737 if (it->cmp_it.ch < 0)
1739 struct composition *cmp = composition_table[it->cmp_it.id];
1741 it->pixel_width = cmp->width;
1743 else
1745 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1747 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1748 it->cmp_it.to, NULL);
1750 it->nglyphs = 1;
1751 if (it->glyph_row)
1752 append_composite_glyph (it);
1756 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1757 is a face ID to be used for the glyph. What is actually appended
1758 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1759 comes from it->nglyphs bytes). */
1761 static void
1762 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1764 struct glyph *glyph, *end;
1765 int i;
1767 eassert (it->glyph_row);
1768 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1769 end = it->glyph_row->glyphs[1 + it->area];
1771 /* If the glyph row is reversed, we need to prepend the glyph rather
1772 than append it. */
1773 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1775 struct glyph *g;
1776 int move_by = it->pixel_width;
1778 /* Make room for the new glyphs. */
1779 if (move_by > end - glyph) /* don't overstep end of this area */
1780 move_by = end - glyph;
1781 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1782 g[move_by] = *g;
1783 glyph = it->glyph_row->glyphs[it->area];
1784 end = glyph + move_by;
1787 if (glyph >= end)
1788 return;
1789 glyph->type = CHAR_GLYPH;
1790 glyph->pixel_width = 1;
1791 glyph->face_id = face_id;
1792 glyph->padding_p = 0;
1793 glyph->charpos = CHARPOS (it->position);
1794 glyph->object = it->object;
1795 if (it->bidi_p)
1797 glyph->resolved_level = it->bidi_it.resolved_level;
1798 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1799 emacs_abort ();
1800 glyph->bidi_type = it->bidi_it.type;
1802 else
1804 glyph->resolved_level = 0;
1805 glyph->bidi_type = UNKNOWN_BT;
1808 /* BIDI Note: we put the glyphs of characters left to right, even in
1809 the REVERSED_P case because we write to the terminal
1810 left-to-right. */
1811 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1813 if (i > 0)
1814 glyph[0] = glyph[-1];
1815 glyph->u.ch = str[i];
1816 ++it->glyph_row->used[it->area];
1817 ++glyph;
1821 /* Produce glyphs for a glyphless character for iterator IT.
1822 IT->glyphless_method specifies which method to use for displaying
1823 the character. See the description of enum
1824 glyphless_display_method in dispextern.h for the details.
1826 ACRONYM, if non-nil, is an acronym string for the character.
1828 The glyphs actually produced are of type CHAR_GLYPH. */
1830 static void
1831 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1833 int len, face_id = merge_glyphless_glyph_face (it);
1834 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1835 char const *str = " ";
1837 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1839 /* As there's no way to produce a thin space, we produce a space
1840 of canonical width. */
1841 len = 1;
1843 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1845 len = CHAR_WIDTH (it->c);
1846 if (len == 0)
1847 len = 1;
1848 else if (len > 4)
1849 len = 4;
1850 len = sprintf (buf, "[%.*s]", len, str);
1851 str = buf;
1853 else
1855 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1857 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1858 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1859 if (CONSP (acronym))
1860 acronym = XCDR (acronym);
1861 buf[0] = '[';
1862 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1863 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1864 buf[1 + len] = str[len];
1865 buf[1 + len] = ']';
1866 len += 2;
1868 else
1870 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1871 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1872 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1873 : sprintf (buf, "\\x%06X", it->c));
1875 str = buf;
1878 it->pixel_width = len;
1879 it->nglyphs = len;
1880 if (it->glyph_row)
1881 append_glyphless_glyph (it, face_id, str);
1885 /***********************************************************************
1886 Faces
1887 ***********************************************************************/
1889 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1890 one of the enumerators from enum no_color_bit, or a bit set built
1891 from them. Some display attributes may not be used together with
1892 color; the termcap capability `NC' specifies which ones. */
1894 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1895 (tty->TN_max_colors > 0 \
1896 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1897 : 1)
1899 /* Turn appearances of face FACE_ID on tty frame F on.
1900 FACE_ID is a realized face ID number, in the face cache. */
1902 static void
1903 turn_on_face (struct frame *f, int face_id)
1905 struct face *face = FACE_FROM_ID (f, face_id);
1906 unsigned long fg = face->foreground;
1907 unsigned long bg = face->background;
1908 struct tty_display_info *tty = FRAME_TTY (f);
1910 /* Use reverse video if the face specifies that.
1911 Do this first because TS_end_standout_mode may be the same
1912 as TS_exit_attribute_mode, which turns all appearances off. */
1913 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1914 && (inverse_video
1915 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1916 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1917 tty_toggle_highlight (tty);
1919 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1920 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1922 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1924 if (tty->TS_enter_italic_mode)
1925 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1926 else
1927 /* Italics mode is unavailable on many terminals. In that
1928 case, map slant to dimmed text; we want italic text to
1929 appear different and dimming is not otherwise used. */
1930 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1933 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1934 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1936 if (tty->TN_max_colors > 0)
1938 const char *ts;
1939 char *p;
1941 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1942 if (face_tty_specified_color (fg) && ts)
1944 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1945 OUTPUT (tty, p);
1946 xfree (p);
1949 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1950 if (face_tty_specified_color (bg) && ts)
1952 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1953 OUTPUT (tty, p);
1954 xfree (p);
1960 /* Turn off appearances of face FACE_ID on tty frame F. */
1962 static void
1963 turn_off_face (struct frame *f, int face_id)
1965 struct face *face = FACE_FROM_ID (f, face_id);
1966 struct tty_display_info *tty = FRAME_TTY (f);
1968 eassert (face != NULL);
1970 if (tty->TS_exit_attribute_mode)
1972 /* Capability "me" will turn off appearance modes double-bright,
1973 half-bright, reverse-video, standout, underline. It may or
1974 may not turn off alt-char-mode. */
1975 if (face->tty_bold_p
1976 || face->tty_italic_p
1977 || face->tty_reverse_p
1978 || face->tty_underline_p)
1980 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1981 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1982 tty->standout_mode = 0;
1985 else
1987 /* If we don't have "me" we can only have those appearances
1988 that have exit sequences defined. */
1989 if (face->tty_underline_p)
1990 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1993 /* Switch back to default colors. */
1994 if (tty->TN_max_colors > 0
1995 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1996 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1997 || (face->background != FACE_TTY_DEFAULT_COLOR
1998 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1999 OUTPUT1_IF (tty, tty->TS_orig_pair);
2003 /* Return true if the terminal on frame F supports all of the
2004 capabilities in CAPS simultaneously. */
2006 bool
2007 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2009 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2010 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2011 return 0;
2013 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2014 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2015 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2016 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2017 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2019 /* We can do it! */
2020 return 1;
2023 /* Return non-zero if the terminal is capable to display colors. */
2025 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2026 0, 1, 0,
2027 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2029 TERMINAL can be a terminal object, a frame, or nil (meaning the
2030 selected frame's terminal). This function always returns nil if
2031 TERMINAL does not refer to a text terminal. */)
2032 (Lisp_Object terminal)
2034 struct terminal *t = decode_tty_terminal (terminal);
2036 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2039 /* Return the number of supported colors. */
2040 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2041 Stty_display_color_cells, 0, 1, 0,
2042 doc: /* Return the number of colors supported by the tty device TERMINAL.
2044 TERMINAL can be a terminal object, a frame, or nil (meaning the
2045 selected frame's terminal). This function always returns 0 if
2046 TERMINAL does not refer to a text terminal. */)
2047 (Lisp_Object terminal)
2049 struct terminal *t = decode_tty_terminal (terminal);
2051 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2054 #ifndef DOS_NT
2056 /* Declare here rather than in the function, as in the rest of Emacs,
2057 to work around an HPUX compiler bug (?). See
2058 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2059 static int default_max_colors;
2060 static int default_max_pairs;
2061 static int default_no_color_video;
2062 static char *default_orig_pair;
2063 static char *default_set_foreground;
2064 static char *default_set_background;
2066 /* Save or restore the default color-related capabilities of this
2067 terminal. */
2068 static void
2069 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2072 if (save)
2074 dupstring (&default_orig_pair, tty->TS_orig_pair);
2075 dupstring (&default_set_foreground, tty->TS_set_foreground);
2076 dupstring (&default_set_background, tty->TS_set_background);
2077 default_max_colors = tty->TN_max_colors;
2078 default_max_pairs = tty->TN_max_pairs;
2079 default_no_color_video = tty->TN_no_color_video;
2081 else
2083 tty->TS_orig_pair = default_orig_pair;
2084 tty->TS_set_foreground = default_set_foreground;
2085 tty->TS_set_background = default_set_background;
2086 tty->TN_max_colors = default_max_colors;
2087 tty->TN_max_pairs = default_max_pairs;
2088 tty->TN_no_color_video = default_no_color_video;
2092 /* Setup one of the standard tty color schemes according to MODE.
2093 MODE's value is generally the number of colors which we want to
2094 support; zero means set up for the default capabilities, the ones
2095 we saw at init_tty time; -1 means turn off color support. */
2096 static void
2097 tty_setup_colors (struct tty_display_info *tty, int mode)
2099 /* Canonicalize all negative values of MODE. */
2100 if (mode < -1)
2101 mode = -1;
2103 switch (mode)
2105 case -1: /* no colors at all */
2106 tty->TN_max_colors = 0;
2107 tty->TN_max_pairs = 0;
2108 tty->TN_no_color_video = 0;
2109 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2110 break;
2111 case 0: /* default colors, if any */
2112 default:
2113 tty_default_color_capabilities (tty, 0);
2114 break;
2115 case 8: /* 8 standard ANSI colors */
2116 tty->TS_orig_pair = "\033[0m";
2117 #ifdef TERMINFO
2118 tty->TS_set_foreground = "\033[3%p1%dm";
2119 tty->TS_set_background = "\033[4%p1%dm";
2120 #else
2121 tty->TS_set_foreground = "\033[3%dm";
2122 tty->TS_set_background = "\033[4%dm";
2123 #endif
2124 tty->TN_max_colors = 8;
2125 tty->TN_max_pairs = 64;
2126 tty->TN_no_color_video = 0;
2127 break;
2131 void
2132 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2134 Lisp_Object tem, val;
2135 Lisp_Object color_mode;
2136 int mode;
2137 Lisp_Object tty_color_mode_alist
2138 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2140 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2141 val = CONSP (tem) ? XCDR (tem) : Qnil;
2143 if (INTEGERP (val))
2144 color_mode = val;
2145 else if (SYMBOLP (tty_color_mode_alist))
2147 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2148 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2150 else
2151 color_mode = Qnil;
2153 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2155 if (mode != tty->previous_color_mode)
2157 tty->previous_color_mode = mode;
2158 tty_setup_colors (tty , mode);
2159 /* This recomputes all the faces given the new color definitions. */
2160 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2164 #endif /* !DOS_NT */
2166 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2167 doc: /* Return the type of the tty device that TERMINAL uses.
2168 Returns nil if TERMINAL is not on a tty device.
2170 TERMINAL can be a terminal object, a frame, or nil (meaning the
2171 selected frame's terminal). */)
2172 (Lisp_Object terminal)
2174 struct terminal *t = decode_tty_terminal (terminal);
2176 return (t && t->display_info.tty->type
2177 ? build_string (t->display_info.tty->type) : Qnil);
2180 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2181 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2183 TERMINAL can be a terminal object, a frame, or nil (meaning the
2184 selected frame's terminal). This function always returns nil if
2185 TERMINAL is not on a tty device. */)
2186 (Lisp_Object terminal)
2188 struct terminal *t = decode_tty_terminal (terminal);
2190 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2193 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2194 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2195 This is used to override the terminfo data, for certain terminals that
2196 do not really do underlining, but say that they do. This function has
2197 no effect if used on a non-tty terminal.
2199 TERMINAL can be a terminal object, a frame or nil (meaning the
2200 selected frame's terminal). This function always returns nil if
2201 TERMINAL does not refer to a text terminal. */)
2202 (Lisp_Object terminal)
2204 struct terminal *t = decode_live_terminal (terminal);
2206 if (t->type == output_termcap)
2207 t->display_info.tty->TS_enter_underline_mode = 0;
2208 return Qnil;
2211 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2212 doc: /* Return the topmost terminal frame on TERMINAL.
2213 TERMINAL can be a terminal object, a frame or nil (meaning the
2214 selected frame's terminal). This function returns nil if TERMINAL
2215 does not refer to a text terminal. Otherwise, it returns the
2216 top-most frame on the text terminal. */)
2217 (Lisp_Object terminal)
2219 struct terminal *t = decode_live_terminal (terminal);
2221 if (t->type == output_termcap)
2222 return t->display_info.tty->top_frame;
2223 return Qnil;
2228 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2229 doc: /* Suspend the terminal device TTY.
2231 The device is restored to its default state, and Emacs ceases all
2232 access to the tty device. Frames that use the device are not deleted,
2233 but input is not read from them and if they change, their display is
2234 not updated.
2236 TTY may be a terminal object, a frame, or nil for the terminal device
2237 of the currently selected frame.
2239 This function runs `suspend-tty-functions' after suspending the
2240 device. The functions are run with one arg, the id of the suspended
2241 terminal device.
2243 `suspend-tty' does nothing if it is called on a device that is already
2244 suspended.
2246 A suspended tty may be resumed by calling `resume-tty' on it. */)
2247 (Lisp_Object tty)
2249 struct terminal *t = decode_tty_terminal (tty);
2250 FILE *f;
2252 if (!t)
2253 error ("Attempt to suspend a non-text terminal device");
2255 f = t->display_info.tty->input;
2257 if (f)
2259 /* First run `suspend-tty-functions' and then clean up the tty
2260 state because `suspend-tty-functions' might need to change
2261 the tty state. */
2262 Lisp_Object args[2];
2263 args[0] = intern ("suspend-tty-functions");
2264 XSETTERMINAL (args[1], t);
2265 Frun_hook_with_args (2, args);
2267 reset_sys_modes (t->display_info.tty);
2268 delete_keyboard_wait_descriptor (fileno (f));
2270 #ifndef MSDOS
2271 fclose (f);
2272 if (f != t->display_info.tty->output)
2273 fclose (t->display_info.tty->output);
2274 #endif
2276 t->display_info.tty->input = 0;
2277 t->display_info.tty->output = 0;
2279 if (FRAMEP (t->display_info.tty->top_frame))
2280 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2284 /* Clear display hooks to prevent further output. */
2285 clear_tty_hooks (t);
2287 return Qnil;
2290 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2291 doc: /* Resume the previously suspended terminal device TTY.
2292 The terminal is opened and reinitialized. Frames that are on the
2293 suspended terminal are revived.
2295 It is an error to resume a terminal while another terminal is active
2296 on the same device.
2298 This function runs `resume-tty-functions' after resuming the terminal.
2299 The functions are run with one arg, the id of the resumed terminal
2300 device.
2302 `resume-tty' does nothing if it is called on a device that is not
2303 suspended.
2305 TTY may be a terminal object, a frame, or nil (meaning the selected
2306 frame's terminal). */)
2307 (Lisp_Object tty)
2309 struct terminal *t = decode_tty_terminal (tty);
2310 int fd;
2312 if (!t)
2313 error ("Attempt to resume a non-text terminal device");
2315 if (!t->display_info.tty->input)
2317 if (get_named_terminal (t->display_info.tty->name))
2318 error ("Cannot resume display while another display is active on the same device");
2320 #ifdef MSDOS
2321 t->display_info.tty->output = stdout;
2322 t->display_info.tty->input = stdin;
2323 #else /* !MSDOS */
2324 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2325 t->display_info.tty->input = t->display_info.tty->output
2326 = fd < 0 ? 0 : fdopen (fd, "w+");
2328 if (! t->display_info.tty->input)
2330 int open_errno = errno;
2331 emacs_close (fd);
2332 report_file_errno ("Cannot reopen tty device",
2333 build_string (t->display_info.tty->name),
2334 open_errno);
2337 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2338 dissociate_if_controlling_tty (fd);
2339 #endif
2341 add_keyboard_wait_descriptor (fd);
2343 if (FRAMEP (t->display_info.tty->top_frame))
2345 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2346 int width, height;
2347 int old_height = FRAME_COLS (f);
2348 int old_width = FRAME_TOTAL_LINES (f);
2350 /* Check if terminal/window size has changed while the frame
2351 was suspended. */
2352 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2353 if (width != old_width || height != old_height)
2354 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2355 0, 0, 0, 0);
2356 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2359 set_tty_hooks (t);
2360 init_sys_modes (t->display_info.tty);
2363 /* Run `resume-tty-functions'. */
2364 Lisp_Object args[2];
2365 args[0] = intern ("resume-tty-functions");
2366 XSETTERMINAL (args[1], t);
2367 Frun_hook_with_args (2, args);
2371 set_tty_hooks (t);
2373 return Qnil;
2377 /***********************************************************************
2378 Mouse
2379 ***********************************************************************/
2381 #ifdef HAVE_GPM
2383 #ifndef HAVE_WINDOW_SYSTEM
2384 void
2385 term_mouse_moveto (int x, int y)
2387 /* TODO: how to set mouse position?
2388 const char *name;
2389 int fd;
2390 name = (const char *) ttyname (0);
2391 fd = emacs_open (name, O_WRONLY, 0);
2392 SOME_FUNCTION (x, y, fd);
2393 emacs_close (fd);
2394 last_mouse_x = x;
2395 last_mouse_y = y; */
2397 #endif /* HAVE_WINDOW_SYSTEM */
2399 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2400 void
2401 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2402 int start_hpos, int end_hpos,
2403 enum draw_glyphs_face draw)
2405 int nglyphs = end_hpos - start_hpos;
2406 struct frame *f = XFRAME (WINDOW_FRAME (w));
2407 struct tty_display_info *tty = FRAME_TTY (f);
2408 int face_id = tty->mouse_highlight.mouse_face_face_id;
2409 int save_x, save_y, pos_x, pos_y;
2411 if (end_hpos >= row->used[TEXT_AREA])
2412 nglyphs = row->used[TEXT_AREA] - start_hpos;
2414 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2415 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2417 /* Save current cursor co-ordinates. */
2418 save_y = curY (tty);
2419 save_x = curX (tty);
2420 cursor_to (f, pos_y, pos_x);
2422 if (draw == DRAW_MOUSE_FACE)
2423 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2424 nglyphs, face_id);
2425 else if (draw == DRAW_NORMAL_TEXT)
2426 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2428 cursor_to (f, save_y, save_x);
2431 static bool
2432 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2434 /* Has the mouse moved off the glyph it was on at the last sighting? */
2435 if (event->x != last_mouse_x || event->y != last_mouse_y)
2437 frame->mouse_moved = 1;
2438 note_mouse_highlight (frame, event->x, event->y);
2439 /* Remember which glyph we're now on. */
2440 last_mouse_x = event->x;
2441 last_mouse_y = event->y;
2442 return 1;
2444 return 0;
2447 /* Return the Time that corresponds to T. Wrap around on overflow. */
2448 static Time
2449 timeval_to_Time (struct timeval const *t)
2451 Time s_1000, ms;
2453 s_1000 = t->tv_sec;
2454 s_1000 *= 1000;
2455 ms = t->tv_usec / 1000;
2456 return s_1000 + ms;
2459 /* Return the current position of the mouse.
2461 Set *f to the frame the mouse is in, or zero if the mouse is in no
2462 Emacs frame. If it is set to zero, all the other arguments are
2463 garbage.
2465 Set *bar_window to Qnil, and *x and *y to the column and
2466 row of the character cell the mouse is over.
2468 Set *timeptr to the time the mouse was at the returned position.
2470 This clears mouse_moved until the next motion
2471 event arrives. */
2472 static void
2473 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2474 enum scroll_bar_part *part, Lisp_Object *x,
2475 Lisp_Object *y, Time *timeptr)
2477 struct timeval now;
2479 *fp = SELECTED_FRAME ();
2480 (*fp)->mouse_moved = 0;
2482 *bar_window = Qnil;
2483 *part = scroll_bar_above_handle;
2485 XSETINT (*x, last_mouse_x);
2486 XSETINT (*y, last_mouse_y);
2487 gettimeofday(&now, 0);
2488 *timeptr = timeval_to_Time (&now);
2491 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2493 If the event is a button press, then note that we have grabbed
2494 the mouse. */
2496 static Lisp_Object
2497 term_mouse_click (struct input_event *result, Gpm_Event *event,
2498 struct frame *f)
2500 struct timeval now;
2501 int i, j;
2503 result->kind = GPM_CLICK_EVENT;
2504 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2506 if (event->buttons & j) {
2507 result->code = i; /* button number */
2508 break;
2511 gettimeofday(&now, 0);
2512 result->timestamp = timeval_to_Time (&now);
2514 if (event->type & GPM_UP)
2515 result->modifiers = up_modifier;
2516 else if (event->type & GPM_DOWN)
2517 result->modifiers = down_modifier;
2518 else
2519 result->modifiers = 0;
2521 if (event->type & GPM_SINGLE)
2522 result->modifiers |= click_modifier;
2524 if (event->type & GPM_DOUBLE)
2525 result->modifiers |= double_modifier;
2527 if (event->type & GPM_TRIPLE)
2528 result->modifiers |= triple_modifier;
2530 if (event->type & GPM_DRAG)
2531 result->modifiers |= drag_modifier;
2533 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2535 /* 1 << KG_SHIFT */
2536 if (event->modifiers & (1 << 0))
2537 result->modifiers |= shift_modifier;
2539 /* 1 << KG_CTRL */
2540 if (event->modifiers & (1 << 2))
2541 result->modifiers |= ctrl_modifier;
2543 /* 1 << KG_ALT || KG_ALTGR */
2544 if (event->modifiers & (1 << 3)
2545 || event->modifiers & (1 << 1))
2546 result->modifiers |= meta_modifier;
2549 XSETINT (result->x, event->x);
2550 XSETINT (result->y, event->y);
2551 XSETFRAME (result->frame_or_window, f);
2552 result->arg = Qnil;
2553 return Qnil;
2557 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2559 struct frame *f = XFRAME (tty->top_frame);
2560 struct input_event ie;
2561 bool do_help = 0;
2562 int count = 0;
2564 EVENT_INIT (ie);
2565 ie.kind = NO_EVENT;
2566 ie.arg = Qnil;
2568 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2569 previous_help_echo_string = help_echo_string;
2570 help_echo_string = Qnil;
2572 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2574 if (!term_mouse_movement (f, event))
2575 help_echo_string = previous_help_echo_string;
2577 /* If the contents of the global variable help_echo_string
2578 has changed, generate a HELP_EVENT. */
2579 if (!NILP (help_echo_string)
2580 || !NILP (previous_help_echo_string))
2581 do_help = 1;
2583 goto done;
2585 else {
2586 f->mouse_moved = 0;
2587 term_mouse_click (&ie, event, f);
2590 done:
2591 if (ie.kind != NO_EVENT)
2593 kbd_buffer_store_event_hold (&ie, hold_quit);
2594 count++;
2597 if (do_help
2598 && !(hold_quit && hold_quit->kind != NO_EVENT))
2600 Lisp_Object frame;
2602 if (f)
2603 XSETFRAME (frame, f);
2604 else
2605 frame = Qnil;
2607 gen_help_event (help_echo_string, frame, help_echo_window,
2608 help_echo_object, help_echo_pos);
2609 count++;
2612 return count;
2615 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2616 0, 0, 0,
2617 doc: /* Open a connection to Gpm.
2618 Gpm-mouse can only be activated for one tty at a time. */)
2619 (void)
2621 struct frame *f = SELECTED_FRAME ();
2622 struct tty_display_info *tty
2623 = ((f)->output_method == output_termcap
2624 ? (f)->terminal->display_info.tty : NULL);
2625 Gpm_Connect connection;
2627 if (!tty)
2628 error ("Gpm-mouse only works in the GNU/Linux console");
2629 if (gpm_tty == tty)
2630 return Qnil; /* Already activated, nothing to do. */
2631 if (gpm_tty)
2632 error ("Gpm-mouse can only be activated for one tty at a time");
2634 connection.eventMask = ~0;
2635 connection.defaultMask = ~GPM_HARD;
2636 connection.maxMod = ~0;
2637 connection.minMod = 0;
2638 gpm_zerobased = 1;
2640 if (Gpm_Open (&connection, 0) < 0)
2641 error ("Gpm-mouse failed to connect to the gpm daemon");
2642 else
2644 gpm_tty = tty;
2645 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2646 to generate SIGIOs. Apparently we need to call reset_sys_modes
2647 before calling init_sys_modes. */
2648 reset_sys_modes (tty);
2649 init_sys_modes (tty);
2650 add_gpm_wait_descriptor (gpm_fd);
2651 return Qnil;
2655 void
2656 close_gpm (int fd)
2658 if (fd >= 0)
2659 delete_gpm_wait_descriptor (fd);
2660 while (Gpm_Close()); /* close all the stack */
2661 gpm_tty = NULL;
2664 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2665 0, 0, 0,
2666 doc: /* Close a connection to Gpm. */)
2667 (void)
2669 struct frame *f = SELECTED_FRAME ();
2670 struct tty_display_info *tty
2671 = ((f)->output_method == output_termcap
2672 ? (f)->terminal->display_info.tty : NULL);
2674 if (!tty || gpm_tty != tty)
2675 return Qnil; /* Not activated on this terminal, nothing to do. */
2677 close_gpm (gpm_fd);
2678 return Qnil;
2680 #endif /* HAVE_GPM */
2683 /***********************************************************************
2684 Menus
2685 ***********************************************************************/
2687 #if !defined (MSDOS)
2689 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2691 However, unlike on MSDOS, where the menu text is drawn directly to
2692 the display video memory, on a TTY we use display_string (see
2693 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2694 the menu items into the frame's 'desired_matrix' glyph matrix, and
2695 then call update_frame_with_menu to deliver the results to the
2696 glass. The previous contents of the screen, in the form of the
2697 current_matrix, is stashed away, and used to restore screen
2698 contents when the menu selection changes or when the final
2699 selection is made and the menu should be popped down.
2701 The idea of this implementation was suggested by Gerd Moellmann. */
2703 #define TTYM_FAILURE -1
2704 #define TTYM_SUCCESS 1
2705 #define TTYM_NO_SELECT 2
2706 #define TTYM_IA_SELECT 3
2707 #define TTYM_NEXT 4
2708 #define TTYM_PREV 5
2710 /* These hold text of the current and the previous menu help messages. */
2711 static const char *menu_help_message, *prev_menu_help_message;
2712 /* Pane number and item number of the menu item which generated the
2713 last menu help message. */
2714 static int menu_help_paneno, menu_help_itemno;
2716 static Lisp_Object Qtty_menu_navigation_map, Qtty_menu_exit;
2717 static Lisp_Object Qtty_menu_prev_item, Qtty_menu_next_item;
2718 static Lisp_Object Qtty_menu_next_menu, Qtty_menu_prev_menu;
2719 static Lisp_Object Qtty_menu_select, Qtty_menu_ignore;
2720 static Lisp_Object Qtty_menu_mouse_movement;
2722 typedef struct tty_menu_struct
2724 int count;
2725 char **text;
2726 struct tty_menu_struct **submenu;
2727 int *panenumber; /* Also used as enabled flag. */
2728 ptrdiff_t allocated;
2729 int panecount;
2730 int width;
2731 const char **help_text;
2732 } tty_menu;
2734 /* Create a brand new menu structure. */
2736 static tty_menu *
2737 tty_menu_create (void)
2739 return xzalloc (sizeof *tty_menu_create ());
2742 /* Allocate some (more) memory for MENU ensuring that there is room for one
2743 more item. */
2745 static void
2746 tty_menu_make_room (tty_menu *menu)
2748 if (menu->allocated == menu->count)
2750 ptrdiff_t allocated = menu->allocated;
2751 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2752 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2753 menu->submenu = xrealloc (menu->submenu,
2754 allocated * sizeof *menu->submenu);
2755 menu->panenumber = xrealloc (menu->panenumber,
2756 allocated * sizeof *menu->panenumber);
2757 menu->help_text = xrealloc (menu->help_text,
2758 allocated * sizeof *menu->help_text);
2759 menu->allocated = allocated;
2763 /* Search the given menu structure for a given pane number. */
2765 static tty_menu *
2766 tty_menu_search_pane (tty_menu *menu, int pane)
2768 int i;
2769 tty_menu *try;
2771 for (i = 0; i < menu->count; i++)
2772 if (menu->submenu[i])
2774 if (pane == menu->panenumber[i])
2775 return menu->submenu[i];
2776 try = tty_menu_search_pane (menu->submenu[i], pane);
2777 if (try)
2778 return try;
2780 return (tty_menu *) 0;
2783 /* Determine how much screen space a given menu needs. */
2785 static void
2786 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2788 int i, h2, w2, maxsubwidth, maxheight;
2790 maxsubwidth = menu->width;
2791 maxheight = menu->count;
2792 for (i = 0; i < menu->count; i++)
2794 if (menu->submenu[i])
2796 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2797 if (w2 > maxsubwidth) maxsubwidth = w2;
2798 if (i + h2 > maxheight) maxheight = i + h2;
2801 *width = maxsubwidth;
2802 *height = maxheight;
2805 static void
2806 mouse_get_xy (int *x, int *y)
2808 struct frame *sf = SELECTED_FRAME ();
2809 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2810 enum scroll_bar_part part_dummy;
2811 Time time_dummy;
2813 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2814 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2815 &lisp_dummy, &part_dummy,
2816 &lmx, &lmy,
2817 &time_dummy);
2818 if (!NILP (lmx))
2820 *x = XINT (lmx);
2821 *y = XINT (lmy);
2825 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2826 (zero-based). */
2828 static void
2829 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2830 int mx, int my, int first_item, bool disp_help)
2832 int i, face, width, enabled, mousehere, row, col;
2833 struct frame *sf = SELECTED_FRAME ();
2834 struct tty_display_info *tty = FRAME_TTY (sf);
2835 /* Don't try to display more menu items than the console can display
2836 using the available screen lines. Exclude the echo area line, as
2837 it will be overwritten by the help-echo anyway. */
2838 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2840 menu_help_message = NULL;
2842 width = menu->width;
2843 col = cursorX (tty);
2844 row = cursorY (tty);
2845 for (i = 0; i < max_items; i++)
2847 int max_width = width + 2; /* +2 for padding blanks on each side */
2848 int j = i + first_item;
2850 if (menu->submenu[j])
2851 max_width += 2; /* for displaying " >" after the item */
2852 enabled
2853 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2854 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2855 face = faces[enabled + mousehere * 2];
2856 /* Display the menu help string for the i-th menu item even if
2857 the menu item is currently disabled. That's what the GUI
2858 code does. */
2859 if (disp_help && enabled + mousehere * 2 >= 2)
2861 menu_help_message = menu->help_text[j];
2862 menu_help_paneno = pn - 1;
2863 menu_help_itemno = j;
2865 /* Take note of the coordinates of the active menu item, to
2866 display the cursor there. */
2867 if (mousehere)
2869 row = y + i;
2870 col = x;
2872 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2873 menu->submenu[j] != NULL);
2875 update_frame_with_menu (sf, row, col);
2878 /* --------------------------- X Menu emulation ---------------------- */
2880 /* Create a new pane and place it on the outer-most level. */
2882 static int
2883 tty_menu_add_pane (tty_menu *menu, const char *txt)
2885 int len;
2887 tty_menu_make_room (menu);
2888 menu->submenu[menu->count] = tty_menu_create ();
2889 menu->text[menu->count] = (char *)txt;
2890 menu->panenumber[menu->count] = ++menu->panecount;
2891 menu->help_text[menu->count] = NULL;
2892 menu->count++;
2894 /* Update the menu width, if necessary. */
2895 len = menu_item_width ((const unsigned char *) txt);
2896 if (len > menu->width)
2897 menu->width = len;
2899 return menu->panecount;
2902 /* Create a new item in a menu pane. */
2904 static bool
2905 tty_menu_add_selection (tty_menu *menu, int pane,
2906 char *txt, bool enable, char const *help_text)
2908 int len;
2910 if (pane)
2912 menu = tty_menu_search_pane (menu, pane);
2913 if (! menu)
2914 return 0;
2916 tty_menu_make_room (menu);
2917 menu->submenu[menu->count] = (tty_menu *) 0;
2918 menu->text[menu->count] = txt;
2919 menu->panenumber[menu->count] = enable;
2920 menu->help_text[menu->count] = help_text;
2921 menu->count++;
2923 /* Update the menu width, if necessary. */
2924 len = menu_item_width ((const unsigned char *) txt);
2925 if (len > menu->width)
2926 menu->width = len;
2928 return 1;
2931 /* Decide where the menu would be placed if requested at (X,Y). */
2933 static void
2934 tty_menu_locate (tty_menu *menu, int x, int y,
2935 int *ulx, int *uly, int *width, int *height)
2937 tty_menu_calc_size (menu, width, height);
2938 *ulx = x + 1;
2939 *uly = y;
2940 *width += 2;
2943 struct tty_menu_state
2945 struct glyph_matrix *screen_behind;
2946 tty_menu *menu;
2947 int pane;
2948 int x, y;
2951 /* Save away the contents of frame F's current frame matrix, and
2952 enable all its rows. Value is a glyph matrix holding the contents
2953 of F's current frame matrix with all its glyph rows enabled. */
2955 static struct glyph_matrix *
2956 save_and_enable_current_matrix (struct frame *f)
2958 int i;
2959 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2960 saved->nrows = f->current_matrix->nrows;
2961 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2963 for (i = 0; i < saved->nrows; ++i)
2965 struct glyph_row *from = f->current_matrix->rows + i;
2966 struct glyph_row *to = saved->rows + i;
2967 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2969 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2970 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2971 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2972 /* Make sure every row is enabled, or else update_frame will not
2973 redraw them. (Rows that are identical to what is already on
2974 screen will not be redrawn anyway.) */
2975 to->enabled_p = true;
2976 to->hash = from->hash;
2979 return saved;
2982 /* Restore the contents of frame F's desired frame matrix from SAVED,
2983 and free memory associated with SAVED. */
2985 static void
2986 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2988 int i;
2990 for (i = 0; i < saved->nrows; ++i)
2992 struct glyph_row *from = saved->rows + i;
2993 struct glyph_row *to = f->desired_matrix->rows + i;
2994 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2996 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2997 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2998 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2999 to->enabled_p = from->enabled_p;
3000 to->hash = from->hash;
3004 static void
3005 free_saved_screen (struct glyph_matrix *saved)
3007 int i;
3009 if (!saved)
3010 return; /* Already freed! */
3012 for (i = 0; i < saved->nrows; ++i)
3014 struct glyph_row *from = saved->rows + i;
3016 xfree (from->glyphs[TEXT_AREA]);
3019 xfree (saved->rows);
3020 xfree (saved);
3023 /* Update the display of frame F from its saved contents. */
3024 static void
3025 screen_update (struct frame *f, struct glyph_matrix *mtx)
3027 restore_desired_matrix (f, mtx);
3028 update_frame_with_menu (f, -1, -1);
3031 typedef enum {
3032 MI_QUIT_MENU = -1,
3033 MI_CONTINUE = 0,
3034 MI_ITEM_SELECTED = 1,
3035 MI_NEXT_ITEM = 2,
3036 MI_PREV_ITEM = 3,
3037 MI_SCROLL_FORWARD = 4,
3038 MI_SCROLL_BACK = 5
3039 } mi_result;
3041 /* Read user input and return X and Y coordinates where that input
3042 puts us. We only consider mouse movement and click events, and
3043 keyboard movement commands; the rest are ignored. */
3044 static mi_result
3045 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3046 bool *first_time)
3048 if (*first_time)
3050 *first_time = false;
3051 sf->mouse_moved = 1;
3053 else
3055 Lisp_Object cmd;
3056 bool usable_input = 1;
3057 mi_result st = MI_CONTINUE;
3058 struct tty_display_info *tty = FRAME_TTY (sf);
3059 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3061 /* Signal the keyboard reading routines we are displaying a menu
3062 on this terminal. */
3063 tty->showing_menu = 1;
3064 /* We want mouse movements be reported by read_menu_command. */
3065 do_mouse_tracking = Qt;
3066 do {
3067 cmd = read_menu_command ();
3068 } while (NILP (cmd));
3069 tty->showing_menu = 0;
3070 do_mouse_tracking = saved_mouse_tracking;
3072 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3073 /* If some input switched frames under our feet, exit the
3074 menu, since the menu faces are no longer valid, and the
3075 menu is no longer relevant anyway. */
3076 || sf != SELECTED_FRAME ())
3077 return MI_QUIT_MENU;
3078 if (EQ (cmd, Qtty_menu_mouse_movement))
3079 mouse_get_xy (x, y);
3080 else if (EQ (cmd, Qtty_menu_next_menu))
3082 usable_input = 0;
3083 st = MI_NEXT_ITEM;
3085 else if (EQ (cmd, Qtty_menu_prev_menu))
3087 usable_input = 0;
3088 st = MI_PREV_ITEM;
3090 else if (EQ (cmd, Qtty_menu_next_item))
3092 if (*y < max_y)
3093 *y += 1;
3094 else
3095 st = MI_SCROLL_FORWARD;
3097 else if (EQ (cmd, Qtty_menu_prev_item))
3099 if (*y > min_y)
3100 *y -= 1;
3101 else
3102 st = MI_SCROLL_BACK;
3104 else if (EQ (cmd, Qtty_menu_select))
3105 st = MI_ITEM_SELECTED;
3106 else if (!EQ (cmd, Qtty_menu_ignore))
3107 usable_input = 0;
3108 if (usable_input)
3109 sf->mouse_moved = 1;
3110 return st;
3112 return MI_CONTINUE;
3115 /* Display menu, wait for user's response, and return that response. */
3116 static int
3117 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3118 int x0, int y0, char **txt,
3119 void (*help_callback)(char const *, int, int),
3120 bool kbd_navigation)
3122 struct tty_menu_state *state;
3123 int statecount, x, y, i;
3124 bool leave, onepane;
3125 int result IF_LINT (= 0);
3126 int title_faces[4]; /* Face to display the menu title. */
3127 int faces[4], buffers_num_deleted = 0;
3128 struct frame *sf = SELECTED_FRAME ();
3129 struct tty_display_info *tty = FRAME_TTY (sf);
3130 bool first_time;
3131 Lisp_Object selectface;
3132 int first_item = 0;
3133 int col, row;
3134 USE_SAFE_ALLOCA;
3136 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3137 around the display. */
3138 if (x0 <= 0)
3139 x0 = 1;
3140 if (y0 <= 0)
3141 y0 = 1;
3143 SAFE_NALLOCA (state, 1, menu->panecount);
3144 memset (state, 0, sizeof (*state));
3145 faces[0]
3146 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3147 DEFAULT_FACE_ID, 1);
3148 faces[1]
3149 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3150 DEFAULT_FACE_ID, 1);
3151 selectface = intern ("tty-menu-selected-face");
3152 faces[2] = lookup_derived_face (sf, selectface,
3153 faces[0], 1);
3154 faces[3] = lookup_derived_face (sf, selectface,
3155 faces[1], 1);
3157 /* Make sure the menu title is always displayed with
3158 `tty-menu-selected-face', no matter where the mouse pointer is. */
3159 for (i = 0; i < 4; i++)
3160 title_faces[i] = faces[3];
3162 statecount = 1;
3164 /* Don't let the title for the "Buffers" popup menu include a
3165 digit (which is ugly).
3167 This is a terrible kludge, but I think the "Buffers" case is
3168 the only one where the title includes a number, so it doesn't
3169 seem to be necessary to make this more general. */
3170 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3172 menu->text[0][7] = '\0';
3173 buffers_num_deleted = 1;
3176 /* Force update of the current frame, so that the desired and the
3177 current matrices are identical. */
3178 update_frame_with_menu (sf, -1, -1);
3179 state[0].menu = menu;
3180 state[0].screen_behind = save_and_enable_current_matrix (sf);
3182 /* Display the menu title. We subtract 1 from x0 and y0 because we
3183 want to interpret them as zero-based column and row coordinates,
3184 and also because we want the first item of the menu, not its
3185 title, to appear at x0,y0. */
3186 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3188 /* Turn off the cursor. Otherwise it shows through the menu
3189 panes, which is ugly. */
3190 col = cursorX (tty);
3191 row = cursorY (tty);
3192 tty_hide_cursor (tty);
3194 if (buffers_num_deleted)
3195 menu->text[0][7] = ' ';
3196 onepane = menu->count == 1 && menu->submenu[0];
3197 if (onepane)
3199 menu->width = menu->submenu[0]->width;
3200 state[0].menu = menu->submenu[0];
3202 else
3204 state[0].menu = menu;
3206 state[0].x = x0 - 1;
3207 state[0].y = y0;
3208 state[0].pane = onepane;
3210 x = state[0].x;
3211 y = state[0].y;
3212 first_time = true;
3214 leave = 0;
3215 while (!leave)
3217 mi_result input_status;
3218 int min_y = state[0].y;
3219 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3221 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3222 if (input_status)
3224 leave = 1;
3225 switch (input_status)
3227 case MI_QUIT_MENU:
3228 /* Remove the last help-echo, so that it doesn't
3229 re-appear after "Quit". */
3230 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3231 result = TTYM_NO_SELECT;
3232 break;
3233 case MI_NEXT_ITEM:
3234 if (kbd_navigation)
3235 result = TTYM_NEXT;
3236 else
3237 leave = 0;
3238 break;
3239 case MI_PREV_ITEM:
3240 if (kbd_navigation)
3241 result = TTYM_PREV;
3242 else
3243 leave = 0;
3244 break;
3245 case MI_SCROLL_FORWARD:
3246 if (y - min_y == state[0].menu->count - 1 - first_item)
3248 y = min_y;
3249 first_item = 0;
3251 else
3252 first_item++;
3253 leave = 0;
3254 break;
3255 case MI_SCROLL_BACK:
3256 if (first_item == 0)
3258 y = max_y;
3259 first_item = state[0].menu->count - 1 - (y - min_y);
3261 else
3262 first_item--;
3263 leave = 0;
3264 break;
3265 default:
3266 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3267 break;
3270 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3272 sf->mouse_moved = 0;
3273 result = TTYM_IA_SELECT;
3274 for (i = 0; i < statecount; i++)
3275 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3277 int dy = y - state[i].y + first_item;
3278 if (0 <= dy && dy < state[i].menu->count)
3280 if (!state[i].menu->submenu[dy])
3282 if (state[i].menu->panenumber[dy])
3283 result = TTYM_SUCCESS;
3284 else
3285 result = TTYM_IA_SELECT;
3287 *pane = state[i].pane - 1;
3288 *selidx = dy;
3289 /* We hit some part of a menu, so drop extra menus that
3290 have been opened. That does not include an open and
3291 active submenu. */
3292 if (i != statecount - 2
3293 || state[i].menu->submenu[dy] != state[i + 1].menu)
3294 while (i != statecount - 1)
3296 statecount--;
3297 screen_update (sf, state[statecount].screen_behind);
3298 state[statecount].screen_behind = NULL;
3300 if (i == statecount - 1 && state[i].menu->submenu[dy])
3302 tty_menu_display (state[i].menu,
3303 state[i].x,
3304 state[i].y,
3305 state[i].pane,
3306 faces, x, y, first_item, 1);
3307 state[statecount].menu = state[i].menu->submenu[dy];
3308 state[statecount].pane = state[i].menu->panenumber[dy];
3309 state[statecount].screen_behind
3310 = save_and_enable_current_matrix (sf);
3311 state[statecount].x
3312 = state[i].x + state[i].menu->width + 2;
3313 state[statecount].y = y;
3314 statecount++;
3318 tty_menu_display (state[statecount - 1].menu,
3319 state[statecount - 1].x,
3320 state[statecount - 1].y,
3321 state[statecount - 1].pane,
3322 faces, x, y, first_item, 1);
3323 /* The call to display help-echo below will move the cursor,
3324 so remember its current position as computed by
3325 tty_menu_display. */
3326 col = cursorX (tty);
3327 row = cursorY (tty);
3330 /* Display the help-echo message for the currently-selected menu
3331 item. */
3332 if ((menu_help_message || prev_menu_help_message)
3333 && menu_help_message != prev_menu_help_message)
3335 help_callback (menu_help_message,
3336 menu_help_paneno, menu_help_itemno);
3337 /* Move the cursor to the beginning of the current menu
3338 item, so that screen readers and other accessibility aids
3339 know where the active region is. */
3340 cursor_to (sf, row, col);
3341 prev_menu_help_message = menu_help_message;
3343 /* Both tty_menu_display and help_callback invoke update_end,
3344 which calls tty_show_cursor. Re-hide it, so it doesn't show
3345 through the menus. */
3346 tty_hide_cursor (tty);
3347 fflush (tty->output);
3350 sf->mouse_moved = 0;
3351 screen_update (sf, state[0].screen_behind);
3352 while (statecount--)
3353 free_saved_screen (state[statecount].screen_behind);
3354 tty_show_cursor (tty); /* Turn cursor back on. */
3355 fflush (tty->output);
3357 /* Clean up any mouse events that are waiting inside Emacs event queue.
3358 These events are likely to be generated before the menu was even
3359 displayed, probably because the user pressed and released the button
3360 (which invoked the menu) too quickly. If we don't remove these events,
3361 Emacs will process them after we return and surprise the user. */
3362 discard_mouse_events ();
3363 if (!kbd_buffer_events_waiting ())
3364 clear_input_pending ();
3365 SAFE_FREE ();
3366 return result;
3369 /* Dispose of a menu. */
3371 static void
3372 tty_menu_destroy (tty_menu *menu)
3374 int i;
3375 if (menu->allocated)
3377 for (i = 0; i < menu->count; i++)
3378 if (menu->submenu[i])
3379 tty_menu_destroy (menu->submenu[i]);
3380 xfree (menu->text);
3381 xfree (menu->submenu);
3382 xfree (menu->panenumber);
3383 xfree (menu->help_text);
3385 xfree (menu);
3386 menu_help_message = prev_menu_help_message = NULL;
3389 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3391 PANE is the pane number, and ITEM is the menu item number in
3392 the menu (currently not used). */
3394 static void
3395 tty_menu_help_callback (char const *help_string, int pane, int item)
3397 Lisp_Object *first_item;
3398 Lisp_Object pane_name;
3399 Lisp_Object menu_object;
3401 first_item = XVECTOR (menu_items)->contents;
3402 if (EQ (first_item[0], Qt))
3403 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3404 else if (EQ (first_item[0], Qquote))
3405 /* This shouldn't happen, see xmenu_show. */
3406 pane_name = empty_unibyte_string;
3407 else
3408 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3410 /* (menu-item MENU-NAME PANE-NUMBER) */
3411 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3412 show_help_echo (help_string ? build_string (help_string) : Qnil,
3413 Qnil, menu_object, make_number (item));
3416 static void
3417 tty_pop_down_menu (Lisp_Object arg)
3419 tty_menu *menu = XSAVE_POINTER (arg, 0);
3421 block_input ();
3422 tty_menu_destroy (menu);
3423 unblock_input ();
3426 /* Return the zero-based index of the last menu-bar item on frame F. */
3427 static int
3428 tty_menu_last_menubar_item (struct frame *f)
3430 int i = 0;
3432 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3433 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3435 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3437 while (i < ASIZE (items))
3439 Lisp_Object str;
3441 str = AREF (items, i + 1);
3442 if (NILP (str))
3443 break;
3444 i += 4;
3446 i -= 4; /* Went one too far! */
3448 return i;
3451 /* Find in frame F's menu bar the menu item that is next or previous
3452 to the item at X/Y, and return that item's position in X/Y. WHICH
3453 says which one--next or previous--item to look for. X and Y are
3454 measured in character cells. This should only be called on TTY
3455 frames. */
3456 static void
3457 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3459 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3460 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3462 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3463 int last_i = tty_menu_last_menubar_item (f);
3464 int i, prev_x;
3466 /* This loop assumes a single menu-bar line, and will fail to
3467 find an item if it is not in the first line. Note that
3468 make_lispy_event in keyboard.c makes the same assumption. */
3469 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3471 Lisp_Object pos, str;
3472 int ix;
3474 str = AREF (items, i + 1);
3475 pos = AREF (items, i + 3);
3476 if (NILP (str))
3477 return;
3478 ix = XINT (pos);
3479 if (ix <= *x
3480 /* We use <= so the blank between 2 items on a TTY is
3481 considered part of the previous item. */
3482 && *x <= ix + menu_item_width (SDATA (str)))
3484 /* Found current item. Now compute the X coordinate of
3485 the previous or next item. */
3486 if (which == TTYM_NEXT)
3488 if (i < last_i)
3489 *x = XINT (AREF (items, i + 4 + 3));
3490 else
3491 *x = 0; /* Wrap around to the first item. */
3493 else if (prev_x < 0)
3495 /* Wrap around to the last item. */
3496 *x = XINT (AREF (items, last_i + 3));
3498 else
3499 *x = prev_x;
3500 return;
3502 prev_x = ix;
3507 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3508 Lisp_Object
3509 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3510 Lisp_Object title, const char **error_name)
3512 tty_menu *menu;
3513 int pane, selidx, lpane, status;
3514 Lisp_Object entry, pane_prefix;
3515 char *datap;
3516 int ulx, uly, width, height;
3517 int item_x, item_y;
3518 int dispwidth, dispheight;
3519 int i, j, lines, maxlines;
3520 int maxwidth;
3521 ptrdiff_t specpdl_count;
3523 eassert (FRAME_TERMCAP_P (f));
3525 *error_name = 0;
3526 if (menu_items_n_panes == 0)
3527 return Qnil;
3529 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3531 *error_name = "Empty menu";
3532 return Qnil;
3535 /* Make the menu on that window. */
3536 menu = tty_menu_create ();
3538 /* Don't GC while we prepare and show the menu, because we give the
3539 menu functions pointers to the contents of strings. */
3540 specpdl_count = inhibit_garbage_collection ();
3542 /* Avoid crashes if, e.g., another client will connect while we
3543 are in a menu. */
3544 temporarily_switch_to_single_kboard (f);
3546 /* Adjust coordinates to be root-window-relative. */
3547 item_x = x += f->left_pos;
3548 item_y = y += f->top_pos;
3550 /* Create all the necessary panes and their items. */
3551 USE_SAFE_ALLOCA;
3552 maxwidth = maxlines = lines = i = 0;
3553 lpane = TTYM_FAILURE;
3554 while (i < menu_items_used)
3556 if (EQ (AREF (menu_items, i), Qt))
3558 /* Create a new pane. */
3559 Lisp_Object pane_name, prefix;
3560 const char *pane_string;
3562 maxlines = max (maxlines, lines);
3563 lines = 0;
3564 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3565 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3566 pane_string = (NILP (pane_name)
3567 ? "" : SSDATA (pane_name));
3568 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3569 pane_string++;
3571 lpane = tty_menu_add_pane (menu, pane_string);
3572 if (lpane == TTYM_FAILURE)
3574 tty_menu_destroy (menu);
3575 *error_name = "Can't create pane";
3576 entry = Qnil;
3577 goto tty_menu_end;
3579 i += MENU_ITEMS_PANE_LENGTH;
3581 /* Find the width of the widest item in this pane. */
3582 j = i;
3583 while (j < menu_items_used)
3585 Lisp_Object item;
3586 item = AREF (menu_items, j);
3587 if (EQ (item, Qt))
3588 break;
3589 if (NILP (item))
3591 j++;
3592 continue;
3594 width = SBYTES (item);
3595 if (width > maxwidth)
3596 maxwidth = width;
3598 j += MENU_ITEMS_ITEM_LENGTH;
3601 /* Ignore a nil in the item list.
3602 It's meaningful only for dialog boxes. */
3603 else if (EQ (AREF (menu_items, i), Qquote))
3604 i += 1;
3605 else
3607 /* Create a new item within current pane. */
3608 Lisp_Object item_name, enable, descrip, help;
3609 char *item_data;
3610 char const *help_string;
3612 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3613 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3614 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3615 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3616 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3618 if (!NILP (descrip))
3620 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3621 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3622 for (j = SCHARS (item_name); j < maxwidth; j++)
3623 item_data[j] = ' ';
3624 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3625 item_data[j + SBYTES (descrip)] = 0;
3627 else
3628 item_data = SSDATA (item_name);
3630 if (lpane == TTYM_FAILURE
3631 || (! tty_menu_add_selection (menu, lpane, item_data,
3632 !NILP (enable), help_string)))
3634 tty_menu_destroy (menu);
3635 *error_name = "Can't add selection to menu";
3636 entry = Qnil;
3637 goto tty_menu_end;
3639 i += MENU_ITEMS_ITEM_LENGTH;
3640 lines++;
3644 maxlines = max (maxlines, lines);
3646 /* All set and ready to fly. */
3647 dispwidth = f->text_cols;
3648 dispheight = f->text_lines;
3649 x = min (x, dispwidth);
3650 y = min (y, dispheight);
3651 x = max (x, 1);
3652 y = max (y, 1);
3653 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3654 if (ulx + width > dispwidth)
3656 x -= (ulx + width) - dispwidth;
3657 ulx = dispwidth - width;
3659 if (uly + height > dispheight)
3661 y -= (uly + height) - dispheight;
3662 uly = dispheight - height;
3665 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3667 /* Move the menu away of the echo area, to avoid overwriting the
3668 menu with help echo messages or vice versa. */
3669 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3671 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3672 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3674 else
3676 y -= 2;
3677 uly -= 2;
3681 if (ulx < 0) x -= ulx;
3682 if (uly < 0) y -= uly;
3684 #if 0
3685 /* This code doesn't make sense on a TTY, since it can easily annul
3686 the adjustments above that carefully avoid truncation of the menu
3687 items. I think it was written to fix some problem that only
3688 happens on X11. */
3689 if (! for_click)
3691 /* If position was not given by a mouse click, adjust so upper left
3692 corner of the menu as a whole ends up at given coordinates. This
3693 is what x-popup-menu says in its documentation. */
3694 x += width / 2;
3695 y += 1.5 * height / (maxlines + 2);
3697 #endif
3699 pane = selidx = 0;
3701 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3703 specbind (Qoverriding_terminal_local_map,
3704 Fsymbol_value (Qtty_menu_navigation_map));
3705 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3706 tty_menu_help_callback,
3707 menuflags & MENU_KBD_NAVIGATION);
3708 entry = pane_prefix = Qnil;
3710 switch (status)
3712 case TTYM_SUCCESS:
3713 /* Find the item number SELIDX in pane number PANE. */
3714 i = 0;
3715 while (i < menu_items_used)
3717 if (EQ (AREF (menu_items, i), Qt))
3719 if (pane == 0)
3720 pane_prefix
3721 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3722 pane--;
3723 i += MENU_ITEMS_PANE_LENGTH;
3725 else
3727 if (pane == -1)
3729 if (selidx == 0)
3731 entry
3732 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3733 if (menuflags & MENU_KEYMAPS)
3735 entry = Fcons (entry, Qnil);
3736 if (!NILP (pane_prefix))
3737 entry = Fcons (pane_prefix, entry);
3739 break;
3741 selidx--;
3743 i += MENU_ITEMS_ITEM_LENGTH;
3746 break;
3748 case TTYM_NEXT:
3749 case TTYM_PREV:
3750 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3751 entry = Fcons (make_number (item_x), make_number (item_y));
3752 break;
3754 case TTYM_FAILURE:
3755 *error_name = "Can't activate menu";
3756 case TTYM_IA_SELECT:
3757 break;
3758 case TTYM_NO_SELECT:
3759 /* If the selected frame was changed while we displayed a menu,
3760 throw to top level in order to undo any temporary settings
3761 made by TTY menu code. */
3762 if (f != SELECTED_FRAME ())
3763 Ftop_level ();
3764 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3765 the menu was invoked with a mouse event as POSITION). */
3766 if (!(menuflags & MENU_FOR_CLICK))
3767 Fsignal (Qquit, Qnil);
3768 break;
3771 tty_menu_end:
3773 SAFE_FREE ();
3774 unbind_to (specpdl_count, Qnil);
3775 return entry;
3778 #endif /* !MSDOS */
3781 #ifndef MSDOS
3782 /***********************************************************************
3783 Initialization
3784 ***********************************************************************/
3786 /* Initialize the tty-dependent part of frame F. The frame must
3787 already have its device initialized. */
3789 void
3790 create_tty_output (struct frame *f)
3792 struct tty_output *t = xzalloc (sizeof *t);
3794 eassert (FRAME_TERMCAP_P (f));
3796 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3798 f->output_data.tty = t;
3801 /* Delete frame F's face cache, and its tty-dependent part. */
3803 static void
3804 tty_free_frame_resources (struct frame *f)
3806 eassert (FRAME_TERMCAP_P (f));
3807 free_frame_faces (f);
3808 xfree (f->output_data.tty);
3811 #else /* MSDOS */
3813 /* Delete frame F's face cache. */
3815 static void
3816 tty_free_frame_resources (struct frame *f)
3818 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3819 free_frame_faces (f);
3821 #endif /* MSDOS */
3823 /* Reset the hooks in TERMINAL. */
3825 static void
3826 clear_tty_hooks (struct terminal *terminal)
3828 terminal->rif = 0;
3829 terminal->cursor_to_hook = 0;
3830 terminal->raw_cursor_to_hook = 0;
3831 terminal->clear_to_end_hook = 0;
3832 terminal->clear_frame_hook = 0;
3833 terminal->clear_end_of_line_hook = 0;
3834 terminal->ins_del_lines_hook = 0;
3835 terminal->insert_glyphs_hook = 0;
3836 terminal->write_glyphs_hook = 0;
3837 terminal->delete_glyphs_hook = 0;
3838 terminal->ring_bell_hook = 0;
3839 terminal->reset_terminal_modes_hook = 0;
3840 terminal->set_terminal_modes_hook = 0;
3841 terminal->update_begin_hook = 0;
3842 terminal->update_end_hook = 0;
3843 terminal->set_terminal_window_hook = 0;
3844 terminal->mouse_position_hook = 0;
3845 terminal->frame_rehighlight_hook = 0;
3846 terminal->frame_raise_lower_hook = 0;
3847 terminal->fullscreen_hook = 0;
3848 terminal->menu_show_hook = 0;
3849 terminal->set_vertical_scroll_bar_hook = 0;
3850 terminal->set_horizontal_scroll_bar_hook = 0;
3851 terminal->condemn_scroll_bars_hook = 0;
3852 terminal->redeem_scroll_bar_hook = 0;
3853 terminal->judge_scroll_bars_hook = 0;
3854 terminal->read_socket_hook = 0;
3855 terminal->frame_up_to_date_hook = 0;
3857 /* Leave these two set, or suspended frames are not deleted
3858 correctly. */
3859 terminal->delete_frame_hook = &tty_free_frame_resources;
3860 terminal->delete_terminal_hook = &delete_tty;
3863 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3865 static void
3866 set_tty_hooks (struct terminal *terminal)
3868 terminal->cursor_to_hook = &tty_cursor_to;
3869 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3870 terminal->clear_to_end_hook = &tty_clear_to_end;
3871 terminal->clear_frame_hook = &tty_clear_frame;
3872 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3873 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3874 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3875 terminal->write_glyphs_hook = &tty_write_glyphs;
3876 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3877 terminal->ring_bell_hook = &tty_ring_bell;
3878 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3879 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3880 terminal->update_end_hook = &tty_update_end;
3881 #ifdef MSDOS
3882 terminal->menu_show_hook = &x_menu_show;
3883 #else
3884 terminal->menu_show_hook = &tty_menu_show;
3885 #endif
3886 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3887 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3888 terminal->delete_frame_hook = &tty_free_frame_resources;
3889 terminal->delete_terminal_hook = &delete_tty;
3890 /* Other hooks are NULL by default. */
3893 /* If FD is the controlling terminal, drop it. */
3894 static void
3895 dissociate_if_controlling_tty (int fd)
3897 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3898 so dissociate it by invoking setsid. */
3899 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3901 #ifdef TIOCNOTTY
3902 /* setsid failed, presumably because Emacs is already a process
3903 group leader. Fall back on the obsolescent way to dissociate
3904 a controlling tty. */
3905 sigset_t oldset;
3906 block_tty_out_signal (&oldset);
3907 ioctl (fd, TIOCNOTTY, 0);
3908 unblock_tty_out_signal (&oldset);
3909 #endif
3913 /* Create a termcap display on the tty device with the given name and
3914 type.
3916 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3917 Otherwise NAME should be a path to the tty device file,
3918 e.g. "/dev/pts/7".
3920 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3922 If MUST_SUCCEED is true, then all errors are fatal. */
3924 struct terminal *
3925 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3927 char *area;
3928 char **address = &area;
3929 int status;
3930 struct tty_display_info *tty = NULL;
3931 struct terminal *terminal = NULL;
3932 sigset_t oldset;
3933 bool ctty = false; /* True if asked to open controlling tty. */
3935 if (!terminal_type)
3936 maybe_fatal (must_succeed, 0,
3937 "Unknown terminal type",
3938 "Unknown terminal type");
3940 if (name == NULL)
3941 name = DEV_TTY;
3942 if (!strcmp (name, DEV_TTY))
3943 ctty = 1;
3945 /* If we already have a terminal on the given device, use that. If
3946 all such terminals are suspended, create a new one instead. */
3947 /* XXX Perhaps this should be made explicit by having init_tty
3948 always create a new terminal and separating terminal and frame
3949 creation on Lisp level. */
3950 terminal = get_named_terminal (name);
3951 if (terminal)
3952 return terminal;
3954 terminal = create_terminal (output_termcap, NULL);
3955 #ifdef MSDOS
3956 if (been_here > 0)
3957 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3958 name, "");
3959 been_here = 1;
3960 tty = &the_only_display_info;
3961 #else
3962 tty = xzalloc (sizeof *tty);
3963 #endif
3964 tty->top_frame = Qnil;
3965 tty->next = tty_list;
3966 tty_list = tty;
3968 terminal->display_info.tty = tty;
3969 tty->terminal = terminal;
3971 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3972 Wcm_clear (tty);
3974 encode_terminal_src_size = 0;
3975 encode_terminal_dst_size = 0;
3978 #ifndef DOS_NT
3979 set_tty_hooks (terminal);
3982 /* Open the terminal device. */
3984 /* If !ctty, don't recognize it as our controlling terminal, and
3985 don't make it the controlling tty if we don't have one now.
3987 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3988 defined on Hurd. On other systems, we need to explicitly
3989 dissociate ourselves from the controlling tty when we want to
3990 open a frame on the same terminal. */
3991 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3992 int fd = emacs_open (name, flags, 0);
3993 tty->input = tty->output
3994 = ((fd < 0 || ! isatty (fd))
3995 ? NULL
3996 : fdopen (fd, "w+"));
3998 if (! tty->input)
4000 char const *diagnostic
4001 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
4002 emacs_close (fd);
4003 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4006 tty->name = xstrdup (name);
4007 terminal->name = xstrdup (name);
4009 if (!O_IGNORE_CTTY && !ctty)
4010 dissociate_if_controlling_tty (fd);
4013 tty->type = xstrdup (terminal_type);
4015 add_keyboard_wait_descriptor (fileno (tty->input));
4017 Wcm_clear (tty);
4019 /* On some systems, tgetent tries to access the controlling
4020 terminal. */
4021 block_tty_out_signal (&oldset);
4022 status = tgetent (tty->termcap_term_buffer, terminal_type);
4023 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4024 emacs_abort ();
4025 unblock_tty_out_signal (&oldset);
4027 if (status < 0)
4029 #ifdef TERMINFO
4030 maybe_fatal (must_succeed, terminal,
4031 "Cannot open terminfo database file",
4032 "Cannot open terminfo database file");
4033 #else
4034 maybe_fatal (must_succeed, terminal,
4035 "Cannot open termcap database file",
4036 "Cannot open termcap database file");
4037 #endif
4039 if (status == 0)
4041 maybe_fatal (must_succeed, terminal,
4042 "Terminal type %s is not defined",
4043 "Terminal type %s is not defined.\n\
4044 If that is not the actual type of terminal you have,\n\
4045 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4046 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4047 #ifdef TERMINFO
4048 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4049 #else
4050 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4051 #endif
4052 terminal_type);
4055 area = tty->termcap_strings_buffer;
4056 tty->TS_ins_line = tgetstr ("al", address);
4057 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4058 tty->TS_bell = tgetstr ("bl", address);
4059 BackTab (tty) = tgetstr ("bt", address);
4060 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4061 tty->TS_clr_line = tgetstr ("ce", address);
4062 tty->TS_clr_frame = tgetstr ("cl", address);
4063 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4064 AbsPosition (tty) = tgetstr ("cm", address);
4065 CR (tty) = tgetstr ("cr", address);
4066 tty->TS_set_scroll_region = tgetstr ("cs", address);
4067 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4068 RowPosition (tty) = tgetstr ("cv", address);
4069 tty->TS_del_char = tgetstr ("dc", address);
4070 tty->TS_del_multi_chars = tgetstr ("DC", address);
4071 tty->TS_del_line = tgetstr ("dl", address);
4072 tty->TS_del_multi_lines = tgetstr ("DL", address);
4073 tty->TS_delete_mode = tgetstr ("dm", address);
4074 tty->TS_end_delete_mode = tgetstr ("ed", address);
4075 tty->TS_end_insert_mode = tgetstr ("ei", address);
4076 Home (tty) = tgetstr ("ho", address);
4077 tty->TS_ins_char = tgetstr ("ic", address);
4078 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4079 tty->TS_insert_mode = tgetstr ("im", address);
4080 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4081 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4082 tty->TS_keypad_mode = tgetstr ("ks", address);
4083 LastLine (tty) = tgetstr ("ll", address);
4084 Right (tty) = tgetstr ("nd", address);
4085 Down (tty) = tgetstr ("do", address);
4086 if (!Down (tty))
4087 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4088 if (tgetflag ("bs"))
4089 Left (tty) = "\b"; /* Can't possibly be longer! */
4090 else /* (Actually, "bs" is obsolete...) */
4091 Left (tty) = tgetstr ("le", address);
4092 if (!Left (tty))
4093 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4094 tty->TS_pad_char = tgetstr ("pc", address);
4095 tty->TS_repeat = tgetstr ("rp", address);
4096 tty->TS_end_standout_mode = tgetstr ("se", address);
4097 tty->TS_fwd_scroll = tgetstr ("sf", address);
4098 tty->TS_standout_mode = tgetstr ("so", address);
4099 tty->TS_rev_scroll = tgetstr ("sr", address);
4100 tty->Wcm->cm_tab = tgetstr ("ta", address);
4101 tty->TS_end_termcap_modes = tgetstr ("te", address);
4102 tty->TS_termcap_modes = tgetstr ("ti", address);
4103 Up (tty) = tgetstr ("up", address);
4104 tty->TS_visible_bell = tgetstr ("vb", address);
4105 tty->TS_cursor_normal = tgetstr ("ve", address);
4106 tty->TS_cursor_visible = tgetstr ("vs", address);
4107 tty->TS_cursor_invisible = tgetstr ("vi", address);
4108 tty->TS_set_window = tgetstr ("wi", address);
4110 tty->TS_enter_underline_mode = tgetstr ("us", address);
4111 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4112 tty->TS_enter_bold_mode = tgetstr ("md", address);
4113 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4114 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4115 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4116 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4117 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4118 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4120 MultiUp (tty) = tgetstr ("UP", address);
4121 MultiDown (tty) = tgetstr ("DO", address);
4122 MultiLeft (tty) = tgetstr ("LE", address);
4123 MultiRight (tty) = tgetstr ("RI", address);
4125 /* SVr4/ANSI color support. If "op" isn't available, don't support
4126 color because we can't switch back to the default foreground and
4127 background. */
4128 tty->TS_orig_pair = tgetstr ("op", address);
4129 if (tty->TS_orig_pair)
4131 tty->TS_set_foreground = tgetstr ("AF", address);
4132 tty->TS_set_background = tgetstr ("AB", address);
4133 if (!tty->TS_set_foreground)
4135 /* SVr4. */
4136 tty->TS_set_foreground = tgetstr ("Sf", address);
4137 tty->TS_set_background = tgetstr ("Sb", address);
4140 tty->TN_max_colors = tgetnum ("Co");
4141 tty->TN_max_pairs = tgetnum ("pa");
4143 tty->TN_no_color_video = tgetnum ("NC");
4144 if (tty->TN_no_color_video == -1)
4145 tty->TN_no_color_video = 0;
4148 tty_default_color_capabilities (tty, 1);
4150 MagicWrap (tty) = tgetflag ("xn");
4151 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4152 the former flag imply the latter. */
4153 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4154 tty->memory_below_frame = tgetflag ("db");
4155 tty->TF_hazeltine = tgetflag ("hz");
4156 tty->must_write_spaces = tgetflag ("in");
4157 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4158 tty->TF_insmode_motion = tgetflag ("mi");
4159 tty->TF_standout_motion = tgetflag ("ms");
4160 tty->TF_underscore = tgetflag ("ul");
4161 tty->TF_teleray = tgetflag ("xt");
4163 #else /* DOS_NT */
4164 #ifdef WINDOWSNT
4166 struct frame *f = XFRAME (selected_frame);
4167 int height, width;
4169 initialize_w32_display (terminal, &width, &height);
4171 FrameRows (tty) = height;
4172 FrameCols (tty) = width;
4173 tty->specified_window = height;
4175 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4176 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4177 tty->char_ins_del_ok = 1;
4178 baud_rate = 19200;
4180 #else /* MSDOS */
4182 int height, width;
4183 if (strcmp (terminal_type, "internal") == 0)
4184 terminal->type = output_msdos_raw;
4185 initialize_msdos_display (terminal);
4187 get_tty_size (fileno (tty->input), &width, &height);
4188 FrameCols (tty) = width;
4189 FrameRows (tty) = height;
4190 tty->char_ins_del_ok = 0;
4191 init_baud_rate (fileno (tty->input));
4193 #endif /* MSDOS */
4194 tty->output = stdout;
4195 tty->input = stdin;
4196 /* The following two are inaccessible from w32console.c. */
4197 terminal->delete_frame_hook = &tty_free_frame_resources;
4198 terminal->delete_terminal_hook = &delete_tty;
4200 tty->name = xstrdup (name);
4201 terminal->name = xstrdup (name);
4202 tty->type = xstrdup (terminal_type);
4204 add_keyboard_wait_descriptor (0);
4206 tty->delete_in_insert_mode = 1;
4208 UseTabs (tty) = 0;
4209 tty->scroll_region_ok = 0;
4211 /* Seems to insert lines when it's not supposed to, messing up the
4212 display. In doing a trace, it didn't seem to be called much, so I
4213 don't think we're losing anything by turning it off. */
4214 tty->line_ins_del_ok = 0;
4216 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4217 #endif /* DOS_NT */
4219 #ifdef HAVE_GPM
4220 terminal->mouse_position_hook = term_mouse_position;
4221 tty->mouse_highlight.mouse_face_window = Qnil;
4222 #endif
4224 terminal->kboard = allocate_kboard (Qnil);
4225 terminal->kboard->reference_count++;
4226 /* Don't let the initial kboard remain current longer than necessary.
4227 That would cause problems if a file loaded on startup tries to
4228 prompt in the mini-buffer. */
4229 if (current_kboard == initial_kboard)
4230 current_kboard = terminal->kboard;
4231 #ifndef DOS_NT
4232 term_get_fkeys (address, terminal->kboard);
4234 /* Get frame size from system, or else from termcap. */
4236 int height, width;
4237 get_tty_size (fileno (tty->input), &width, &height);
4238 FrameCols (tty) = width;
4239 FrameRows (tty) = height;
4242 if (FrameCols (tty) <= 0)
4243 FrameCols (tty) = tgetnum ("co");
4244 if (FrameRows (tty) <= 0)
4245 FrameRows (tty) = tgetnum ("li");
4247 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4248 maybe_fatal (must_succeed, terminal,
4249 "Screen size %dx%d is too small",
4250 "Screen size %dx%d is too small",
4251 FrameCols (tty), FrameRows (tty));
4253 TabWidth (tty) = tgetnum ("tw");
4255 if (!tty->TS_bell)
4256 tty->TS_bell = "\07";
4258 if (!tty->TS_fwd_scroll)
4259 tty->TS_fwd_scroll = Down (tty);
4261 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4263 if (TabWidth (tty) < 0)
4264 TabWidth (tty) = 8;
4266 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4267 and newer termcap doc does not seem to say there is a default.
4268 if (!tty->Wcm->cm_tab)
4269 tty->Wcm->cm_tab = "\t";
4272 /* We don't support standout modes that use `magic cookies', so
4273 turn off any that do. */
4274 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4276 tty->TS_standout_mode = 0;
4277 tty->TS_end_standout_mode = 0;
4279 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4281 tty->TS_enter_underline_mode = 0;
4282 tty->TS_exit_underline_mode = 0;
4285 /* If there's no standout mode, try to use underlining instead. */
4286 if (tty->TS_standout_mode == 0)
4288 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4289 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4292 /* If no `se' string, try using a `me' string instead.
4293 If that fails, we can't use standout mode at all. */
4294 if (tty->TS_end_standout_mode == 0)
4296 char *s = tgetstr ("me", address);
4297 if (s != 0)
4298 tty->TS_end_standout_mode = s;
4299 else
4300 tty->TS_standout_mode = 0;
4303 if (tty->TF_teleray)
4305 tty->Wcm->cm_tab = 0;
4306 /* We can't support standout mode, because it uses magic cookies. */
4307 tty->TS_standout_mode = 0;
4308 /* But that means we cannot rely on ^M to go to column zero! */
4309 CR (tty) = 0;
4310 /* LF can't be trusted either -- can alter hpos. */
4311 /* If move at column 0 thru a line with TS_standout_mode. */
4312 Down (tty) = 0;
4315 tty->specified_window = FrameRows (tty);
4317 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4319 maybe_fatal (must_succeed, terminal,
4320 "Terminal type \"%s\" is not powerful enough to run Emacs",
4321 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4322 It lacks the ability to position the cursor.\n\
4323 If that is not the actual type of terminal you have,\n\
4324 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4325 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4326 # ifdef TERMINFO
4327 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4328 # else /* TERMCAP */
4329 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4330 # endif /* TERMINFO */
4331 terminal_type);
4334 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4335 maybe_fatal (must_succeed, terminal,
4336 "Could not determine the frame size",
4337 "Could not determine the frame size");
4339 tty->delete_in_insert_mode
4340 = tty->TS_delete_mode && tty->TS_insert_mode
4341 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4343 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4345 tty->scroll_region_ok
4346 = (tty->Wcm->cm_abs
4347 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4349 tty->line_ins_del_ok
4350 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4351 && (tty->TS_del_line || tty->TS_del_multi_lines))
4352 || (tty->scroll_region_ok
4353 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4355 tty->char_ins_del_ok
4356 = ((tty->TS_ins_char || tty->TS_insert_mode
4357 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4358 && (tty->TS_del_char || tty->TS_del_multi_chars));
4360 init_baud_rate (fileno (tty->input));
4362 #endif /* not DOS_NT */
4364 /* Init system terminal modes (RAW or CBREAK, etc.). */
4365 init_sys_modes (tty);
4367 return terminal;
4371 static void
4372 vfatal (const char *str, va_list ap)
4374 fprintf (stderr, "emacs: ");
4375 vfprintf (stderr, str, ap);
4376 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4377 fprintf (stderr, "\n");
4378 fflush (stderr);
4379 exit (1);
4383 /* Auxiliary error-handling function for init_tty.
4384 Delete TERMINAL, then call error or fatal with str1 or str2,
4385 respectively, according to whether MUST_SUCCEED is true. */
4387 static void
4388 maybe_fatal (bool must_succeed, struct terminal *terminal,
4389 const char *str1, const char *str2, ...)
4391 va_list ap;
4392 va_start (ap, str2);
4393 if (terminal)
4394 delete_tty (terminal);
4396 if (must_succeed)
4397 vfatal (str2, ap);
4398 else
4399 verror (str1, ap);
4402 void
4403 fatal (const char *str, ...)
4405 va_list ap;
4406 va_start (ap, str);
4407 vfatal (str, ap);
4412 /* Delete the given tty terminal, closing all frames on it. */
4414 static void
4415 delete_tty (struct terminal *terminal)
4417 struct tty_display_info *tty;
4419 /* Protect against recursive calls. delete_frame in
4420 delete_terminal calls us back when it deletes our last frame. */
4421 if (!terminal->name)
4422 return;
4424 eassert (terminal->type == output_termcap);
4426 tty = terminal->display_info.tty;
4428 if (tty == tty_list)
4429 tty_list = tty->next;
4430 else
4432 struct tty_display_info *p;
4433 for (p = tty_list; p && p->next != tty; p = p->next)
4436 if (! p)
4437 /* This should not happen. */
4438 emacs_abort ();
4440 p->next = tty->next;
4441 tty->next = 0;
4444 /* reset_sys_modes needs a valid device, so this call needs to be
4445 before delete_terminal. */
4446 reset_sys_modes (tty);
4448 delete_terminal (terminal);
4450 xfree (tty->name);
4451 xfree (tty->type);
4453 if (tty->input)
4455 delete_keyboard_wait_descriptor (fileno (tty->input));
4456 if (tty->input != stdin)
4457 fclose (tty->input);
4459 if (tty->output && tty->output != stdout && tty->output != tty->input)
4460 fclose (tty->output);
4461 if (tty->termscript)
4462 fclose (tty->termscript);
4464 xfree (tty->old_tty);
4465 xfree (tty->Wcm);
4466 xfree (tty);
4469 void
4470 syms_of_term (void)
4472 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4473 doc: /* Non-nil means the system uses terminfo rather than termcap.
4474 This variable can be used by terminal emulator packages. */);
4475 #ifdef TERMINFO
4476 system_uses_terminfo = 1;
4477 #else
4478 system_uses_terminfo = 0;
4479 #endif
4481 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4482 doc: /* Functions run after suspending a tty.
4483 The functions are run with one argument, the terminal object to be suspended.
4484 See `suspend-tty'. */);
4485 Vsuspend_tty_functions = Qnil;
4488 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4489 doc: /* Functions run after resuming a tty.
4490 The functions are run with one argument, the terminal object that was revived.
4491 See `resume-tty'. */);
4492 Vresume_tty_functions = Qnil;
4494 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4495 doc: /* Non-nil means to make the cursor very visible.
4496 This only has an effect when running in a text terminal.
4497 What means \"very visible\" is up to your terminal. It may make the cursor
4498 bigger, or it may make it blink, or it may do nothing at all. */);
4499 visible_cursor = 1;
4501 defsubr (&Stty_display_color_p);
4502 defsubr (&Stty_display_color_cells);
4503 defsubr (&Stty_no_underline);
4504 defsubr (&Stty_type);
4505 defsubr (&Scontrolling_tty_p);
4506 defsubr (&Stty_top_frame);
4507 defsubr (&Ssuspend_tty);
4508 defsubr (&Sresume_tty);
4509 #ifdef HAVE_GPM
4510 defsubr (&Sgpm_mouse_start);
4511 defsubr (&Sgpm_mouse_stop);
4512 #endif /* HAVE_GPM */
4514 #ifndef DOS_NT
4515 default_orig_pair = NULL;
4516 default_set_foreground = NULL;
4517 default_set_background = NULL;
4518 #endif /* !DOS_NT */
4520 encode_terminal_src = NULL;
4521 encode_terminal_dst = NULL;
4523 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4524 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4526 #ifndef MSDOS
4527 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4528 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4529 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4530 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4531 DEFSYM (Qtty_menu_select, "tty-menu-select");
4532 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4533 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4534 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4535 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4536 #endif