Port to ISO/IEC TS 18661-1:2014
[emacs.git] / src / term.c
blob426674f44708f8f2d1bf86d7e4404351cdef18af
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2016 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #ifdef MSDOS
48 #include "msdos.h"
49 static int been_here = -1;
50 #endif
52 #ifdef USE_X_TOOLKIT
53 #include "../lwlib/lwlib.h"
54 #endif
56 #include "cm.h"
57 #include "menu.h"
59 /* The name of the default console device. */
60 #ifdef WINDOWSNT
61 #include "w32term.h"
62 #endif
64 static void tty_set_scroll_region (struct frame *f, int start, int stop);
65 static void turn_on_face (struct frame *, int face_id);
66 static void turn_off_face (struct frame *, int face_id);
67 static void tty_turn_off_highlight (struct tty_display_info *);
68 static void tty_show_cursor (struct tty_display_info *);
69 static void tty_hide_cursor (struct tty_display_info *);
70 static void tty_background_highlight (struct tty_display_info *tty);
71 static void clear_tty_hooks (struct terminal *terminal);
72 static void set_tty_hooks (struct terminal *terminal);
73 static void dissociate_if_controlling_tty (int fd);
74 static void delete_tty (struct terminal *);
75 static _Noreturn void maybe_fatal (bool, struct terminal *,
76 const char *, const char *, ...)
77 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
78 static _Noreturn void vfatal (const char *str, va_list ap)
79 ATTRIBUTE_FORMAT_PRINTF (1, 0);
82 #define OUTPUT(tty, a) \
83 emacs_tputs ((tty), a, \
84 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
85 cmputc)
87 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
88 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
90 #define OUTPUT_IF(tty, a) \
91 do { \
92 if (a) \
93 OUTPUT (tty, a); \
94 } while (0)
96 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
98 /* Display space properties. */
100 /* Chain of all tty device parameters. */
101 struct tty_display_info *tty_list;
103 /* Meaning of bits in no_color_video. Each bit set means that the
104 corresponding attribute cannot be combined with colors. */
106 enum no_color_bit
108 NC_STANDOUT = 1 << 0,
109 NC_UNDERLINE = 1 << 1,
110 NC_REVERSE = 1 << 2,
111 NC_ITALIC = 1 << 3,
112 NC_DIM = 1 << 4,
113 NC_BOLD = 1 << 5,
114 NC_INVIS = 1 << 6,
115 NC_PROTECT = 1 << 7
118 /* internal state */
120 /* The largest frame width in any call to calculate_costs. */
122 static int max_frame_cols;
126 #ifdef HAVE_GPM
127 #include <sys/fcntl.h>
129 /* The device for which we have enabled gpm support (or NULL). */
130 struct tty_display_info *gpm_tty = NULL;
132 /* Last recorded mouse coordinates. */
133 static int last_mouse_x, last_mouse_y;
134 #endif /* HAVE_GPM */
136 /* Ring the bell on a tty. */
138 static void
139 tty_ring_bell (struct frame *f)
141 struct tty_display_info *tty = FRAME_TTY (f);
143 if (tty->output)
145 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
146 ? tty->TS_visible_bell
147 : tty->TS_bell));
148 fflush (tty->output);
152 /* Set up termcap modes for Emacs. */
154 static void
155 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
157 Lisp_Object lisp_terminal;
158 Lisp_Object extra_codes;
159 struct tty_display_info *tty = terminal->display_info.tty;
161 XSETTERMINAL (lisp_terminal, terminal);
162 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
163 CONSP (extra_codes);
164 extra_codes = XCDR (extra_codes))
166 Lisp_Object string = XCAR (extra_codes);
167 if (STRINGP (string))
169 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
170 if (tty->termscript)
171 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
176 static void
177 tty_set_terminal_modes (struct terminal *terminal)
179 struct tty_display_info *tty = terminal->display_info.tty;
181 if (tty->output)
183 if (tty->TS_termcap_modes)
184 OUTPUT (tty, tty->TS_termcap_modes);
185 else
187 /* Output enough newlines to scroll all the old screen contents
188 off the screen, so it won't be overwritten and lost. */
189 int i;
190 current_tty = tty;
191 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
192 cmputc ('\n');
195 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
196 OUTPUT_IF (tty, tty->TS_keypad_mode);
197 losecursor (tty);
198 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
199 fflush (tty->output);
203 /* Reset termcap modes before exiting Emacs. */
205 static void
206 tty_reset_terminal_modes (struct terminal *terminal)
208 struct tty_display_info *tty = terminal->display_info.tty;
210 if (tty->output)
212 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
213 tty_turn_off_highlight (tty);
214 tty_turn_off_insert (tty);
215 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
216 OUTPUT_IF (tty, tty->TS_cursor_normal);
217 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
218 OUTPUT_IF (tty, tty->TS_orig_pair);
219 /* Output raw CR so kernel can track the cursor hpos. */
220 current_tty = tty;
221 cmputc ('\r');
222 fflush (tty->output);
226 /* Flag the end of a display update on a termcap terminal. */
228 static void
229 tty_update_end (struct frame *f)
231 struct tty_display_info *tty = FRAME_TTY (f);
233 if (!XWINDOW (selected_window)->cursor_off_p)
234 tty_show_cursor (tty);
235 tty_turn_off_insert (tty);
236 tty_background_highlight (tty);
237 fflush (tty->output);
240 /* The implementation of set_terminal_window for termcap frames. */
242 static void
243 tty_set_terminal_window (struct frame *f, int size)
245 struct tty_display_info *tty = FRAME_TTY (f);
247 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
248 if (FRAME_SCROLL_REGION_OK (f))
249 tty_set_scroll_region (f, 0, tty->specified_window);
252 static void
253 tty_set_scroll_region (struct frame *f, int start, int stop)
255 char *buf;
256 struct tty_display_info *tty = FRAME_TTY (f);
258 if (tty->TS_set_scroll_region)
259 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
260 else if (tty->TS_set_scroll_region_1)
261 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
262 FRAME_TOTAL_LINES (f), start,
263 FRAME_TOTAL_LINES (f) - stop,
264 FRAME_TOTAL_LINES (f));
265 else
266 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
268 OUTPUT (tty, buf);
269 xfree (buf);
270 losecursor (tty);
274 static void
275 tty_turn_on_insert (struct tty_display_info *tty)
277 if (!tty->insert_mode)
278 OUTPUT (tty, tty->TS_insert_mode);
279 tty->insert_mode = 1;
282 void
283 tty_turn_off_insert (struct tty_display_info *tty)
285 if (tty->insert_mode)
286 OUTPUT (tty, tty->TS_end_insert_mode);
287 tty->insert_mode = 0;
290 /* Handle highlighting. */
292 static void
293 tty_turn_off_highlight (struct tty_display_info *tty)
295 if (tty->standout_mode)
296 OUTPUT_IF (tty, tty->TS_end_standout_mode);
297 tty->standout_mode = 0;
300 static void
301 tty_turn_on_highlight (struct tty_display_info *tty)
303 if (!tty->standout_mode)
304 OUTPUT_IF (tty, tty->TS_standout_mode);
305 tty->standout_mode = 1;
308 static void
309 tty_toggle_highlight (struct tty_display_info *tty)
311 if (tty->standout_mode)
312 tty_turn_off_highlight (tty);
313 else
314 tty_turn_on_highlight (tty);
318 /* Make cursor invisible. */
320 static void
321 tty_hide_cursor (struct tty_display_info *tty)
323 if (tty->cursor_hidden == 0)
325 tty->cursor_hidden = 1;
326 #ifdef WINDOWSNT
327 w32con_hide_cursor ();
328 #else
329 OUTPUT_IF (tty, tty->TS_cursor_invisible);
330 #endif
335 /* Ensure that cursor is visible. */
337 static void
338 tty_show_cursor (struct tty_display_info *tty)
340 if (tty->cursor_hidden)
342 tty->cursor_hidden = 0;
343 #ifdef WINDOWSNT
344 w32con_show_cursor ();
345 #else
346 OUTPUT_IF (tty, tty->TS_cursor_normal);
347 if (visible_cursor)
348 OUTPUT_IF (tty, tty->TS_cursor_visible);
349 #endif
354 /* Set standout mode to the state it should be in for
355 empty space inside windows. What this is,
356 depends on the user option inverse-video. */
358 static void
359 tty_background_highlight (struct tty_display_info *tty)
361 if (inverse_video)
362 tty_turn_on_highlight (tty);
363 else
364 tty_turn_off_highlight (tty);
367 /* Set standout mode to the mode specified for the text to be output. */
369 static void
370 tty_highlight_if_desired (struct tty_display_info *tty)
372 if (inverse_video)
373 tty_turn_on_highlight (tty);
374 else
375 tty_turn_off_highlight (tty);
379 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
380 frame-relative coordinates. */
382 static void
383 tty_cursor_to (struct frame *f, int vpos, int hpos)
385 struct tty_display_info *tty = FRAME_TTY (f);
387 /* Detect the case where we are called from reset_sys_modes
388 and the costs have never been calculated. Do nothing. */
389 if (! tty->costs_set)
390 return;
392 if (curY (tty) == vpos
393 && curX (tty) == hpos)
394 return;
395 if (!tty->TF_standout_motion)
396 tty_background_highlight (tty);
397 if (!tty->TF_insmode_motion)
398 tty_turn_off_insert (tty);
399 cmgoto (tty, vpos, hpos);
402 /* Similar but don't take any account of the wasted characters. */
404 static void
405 tty_raw_cursor_to (struct frame *f, int row, int col)
407 struct tty_display_info *tty = FRAME_TTY (f);
409 if (curY (tty) == row
410 && curX (tty) == col)
411 return;
412 if (!tty->TF_standout_motion)
413 tty_background_highlight (tty);
414 if (!tty->TF_insmode_motion)
415 tty_turn_off_insert (tty);
416 cmgoto (tty, row, col);
419 /* Erase operations */
421 /* Clear from cursor to end of frame on a termcap device. */
423 static void
424 tty_clear_to_end (struct frame *f)
426 register int i;
427 struct tty_display_info *tty = FRAME_TTY (f);
429 if (tty->TS_clr_to_bottom)
431 tty_background_highlight (tty);
432 OUTPUT (tty, tty->TS_clr_to_bottom);
434 else
436 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
438 cursor_to (f, i, 0);
439 clear_end_of_line (f, FRAME_COLS (f));
444 /* Clear an entire termcap frame. */
446 static void
447 tty_clear_frame (struct frame *f)
449 struct tty_display_info *tty = FRAME_TTY (f);
451 if (tty->TS_clr_frame)
453 tty_background_highlight (tty);
454 OUTPUT (tty, tty->TS_clr_frame);
455 cmat (tty, 0, 0);
457 else
459 cursor_to (f, 0, 0);
460 clear_to_end (f);
464 /* An implementation of clear_end_of_line for termcap frames.
466 Note that the cursor may be moved, on terminals lacking a `ce' string. */
468 static void
469 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
471 register int i;
472 struct tty_display_info *tty = FRAME_TTY (f);
474 /* Detect the case where we are called from reset_sys_modes
475 and the costs have never been calculated. Do nothing. */
476 if (! tty->costs_set)
477 return;
479 if (curX (tty) >= first_unused_hpos)
480 return;
481 tty_background_highlight (tty);
482 if (tty->TS_clr_line)
484 OUTPUT1 (tty, tty->TS_clr_line);
486 else
487 { /* have to do it the hard way */
488 tty_turn_off_insert (tty);
490 /* Do not write in last row last col with Auto-wrap on. */
491 if (AutoWrap (tty)
492 && curY (tty) == FrameRows (tty) - 1
493 && first_unused_hpos == FrameCols (tty))
494 first_unused_hpos--;
496 for (i = curX (tty); i < first_unused_hpos; i++)
498 if (tty->termscript)
499 fputc (' ', tty->termscript);
500 fputc (' ', tty->output);
502 cmplus (tty, first_unused_hpos - curX (tty));
506 /* Buffers to store the source and result of code conversion for terminal. */
507 static unsigned char *encode_terminal_src;
508 static unsigned char *encode_terminal_dst;
509 /* Allocated sizes of the above buffers. */
510 static ptrdiff_t encode_terminal_src_size;
511 static ptrdiff_t encode_terminal_dst_size;
513 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
514 Set CODING->produced to the byte-length of the resulting byte
515 sequence, and return a pointer to that byte sequence. */
517 unsigned char *
518 encode_terminal_code (struct glyph *src, int src_len,
519 struct coding_system *coding)
521 struct glyph *src_end = src + src_len;
522 unsigned char *buf;
523 ptrdiff_t nchars, nbytes, required;
524 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
525 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
526 Lisp_Object charset_list;
528 /* Allocate sufficient size of buffer to store all characters in
529 multibyte-form. But, it may be enlarged on demand if
530 Vglyph_table contains a string or a composite glyph is
531 encountered. */
532 if (INT_MULTIPLY_WRAPV (src_len, MAX_MULTIBYTE_LENGTH, &required))
533 memory_full (SIZE_MAX);
534 if (encode_terminal_src_size < required)
535 encode_terminal_src = xpalloc (encode_terminal_src,
536 &encode_terminal_src_size,
537 required - encode_terminal_src_size,
538 -1, sizeof *encode_terminal_src);
540 charset_list = coding_charset_list (coding);
542 buf = encode_terminal_src;
543 nchars = 0;
544 while (src < src_end)
546 if (src->type == COMPOSITE_GLYPH)
548 struct composition *cmp UNINIT;
549 Lisp_Object gstring UNINIT;
550 int i;
552 nbytes = buf - encode_terminal_src;
553 if (src->u.cmp.automatic)
555 gstring = composition_gstring_from_id (src->u.cmp.id);
556 required = src->slice.cmp.to - src->slice.cmp.from + 1;
558 else
560 cmp = composition_table[src->u.cmp.id];
561 required = cmp->glyph_len;
562 required *= MAX_MULTIBYTE_LENGTH;
565 if (encode_terminal_src_size - nbytes < required)
567 encode_terminal_src =
568 xpalloc (encode_terminal_src, &encode_terminal_src_size,
569 required - (encode_terminal_src_size - nbytes),
570 -1, 1);
571 buf = encode_terminal_src + nbytes;
574 if (src->u.cmp.automatic)
575 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
577 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
578 int c = LGLYPH_CHAR (g);
580 if (! char_charset (c, charset_list, NULL))
581 c = '?';
582 buf += CHAR_STRING (c, buf);
583 nchars++;
585 else
586 for (i = 0; i < cmp->glyph_len; i++)
588 int c = COMPOSITION_GLYPH (cmp, i);
590 /* TAB in a composition means display glyphs with
591 padding space on the left or right. */
592 if (c == '\t')
593 continue;
594 if (char_charset (c, charset_list, NULL))
596 if (CHARACTER_WIDTH (c) == 0
597 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
598 /* Should be left-padded */
600 buf += CHAR_STRING (' ', buf);
601 nchars++;
604 else
605 c = '?';
606 buf += CHAR_STRING (c, buf);
607 nchars++;
610 /* We must skip glyphs to be padded for a wide character. */
611 else if (! CHAR_GLYPH_PADDING_P (*src))
613 GLYPH g;
614 int c UNINIT;
615 Lisp_Object string;
617 string = Qnil;
618 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
620 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
622 /* This glyph doesn't have an entry in Vglyph_table. */
623 c = src->u.ch;
625 else
627 /* This glyph has an entry in Vglyph_table,
628 so process any alias before testing for simpleness. */
629 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
631 if (GLYPH_SIMPLE_P (tbase, tlen, g))
632 /* We set the multi-byte form of a character in G
633 (that should be an ASCII character) at WORKBUF. */
634 c = GLYPH_CHAR (g);
635 else
636 /* We have a string in Vglyph_table. */
637 string = tbase[GLYPH_CHAR (g)];
640 if (NILP (string))
642 nbytes = buf - encode_terminal_src;
643 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
645 encode_terminal_src =
646 xpalloc (encode_terminal_src, &encode_terminal_src_size,
647 MAX_MULTIBYTE_LENGTH, -1, 1);
648 buf = encode_terminal_src + nbytes;
650 if (CHAR_BYTE8_P (c)
651 || char_charset (c, charset_list, NULL))
653 /* Store the multibyte form of C at BUF. */
654 buf += CHAR_STRING (c, buf);
655 nchars++;
657 else
659 /* C is not encodable. */
660 *buf++ = '?';
661 nchars++;
662 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
664 *buf++ = '?';
665 nchars++;
666 src++;
670 else
672 if (! STRING_MULTIBYTE (string))
673 string = string_to_multibyte (string);
674 nbytes = buf - encode_terminal_src;
675 if (encode_terminal_src_size - nbytes < SBYTES (string))
677 encode_terminal_src =
678 xpalloc (encode_terminal_src, &encode_terminal_src_size,
679 (SBYTES (string)
680 - (encode_terminal_src_size - nbytes)),
681 -1, 1);
682 buf = encode_terminal_src + nbytes;
684 memcpy (buf, SDATA (string), SBYTES (string));
685 buf += SBYTES (string);
686 nchars += SCHARS (string);
689 src++;
692 if (nchars == 0)
694 coding->produced = 0;
695 return NULL;
698 nbytes = buf - encode_terminal_src;
699 coding->source = encode_terminal_src;
700 if (encode_terminal_dst_size == 0)
702 encode_terminal_dst = xrealloc (encode_terminal_dst,
703 encode_terminal_src_size);
704 encode_terminal_dst_size = encode_terminal_src_size;
706 coding->destination = encode_terminal_dst;
707 coding->dst_bytes = encode_terminal_dst_size;
708 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
709 /* coding->destination may have been reallocated. */
710 encode_terminal_dst = coding->destination;
711 encode_terminal_dst_size = coding->dst_bytes;
713 return (encode_terminal_dst);
718 /* An implementation of write_glyphs for termcap frames. */
720 static void
721 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
723 unsigned char *conversion_buffer;
724 struct coding_system *coding;
725 int n, stringlen;
727 struct tty_display_info *tty = FRAME_TTY (f);
729 tty_turn_off_insert (tty);
730 tty_hide_cursor (tty);
732 /* Don't dare write in last column of bottom line, if Auto-Wrap,
733 since that would scroll the whole frame on some terminals. */
735 if (AutoWrap (tty)
736 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
737 && (curX (tty) + len) == FRAME_COLS (f))
738 len --;
739 if (len <= 0)
740 return;
742 cmplus (tty, len);
744 /* If terminal_coding does any conversion, use it, otherwise use
745 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
746 because it always return 1 if the member src_multibyte is 1. */
747 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
748 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
749 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
750 the tail. */
751 coding->mode &= ~CODING_MODE_LAST_BLOCK;
753 for (stringlen = len; stringlen != 0; stringlen -= n)
755 /* Identify a run of glyphs with the same face. */
756 int face_id = string->face_id;
758 for (n = 1; n < stringlen; ++n)
759 if (string[n].face_id != face_id)
760 break;
762 /* Turn appearance modes of the face of the run on. */
763 tty_highlight_if_desired (tty);
764 turn_on_face (f, face_id);
766 if (n == stringlen)
767 /* This is the last run. */
768 coding->mode |= CODING_MODE_LAST_BLOCK;
769 conversion_buffer = encode_terminal_code (string, n, coding);
770 if (coding->produced > 0)
772 block_input ();
773 fwrite (conversion_buffer, 1, coding->produced, tty->output);
774 if (ferror (tty->output))
775 clearerr (tty->output);
776 if (tty->termscript)
777 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
778 unblock_input ();
780 string += n;
782 /* Turn appearance modes off. */
783 turn_off_face (f, face_id);
784 tty_turn_off_highlight (tty);
787 cmcheckmagic (tty);
790 #ifdef HAVE_GPM /* Only used by GPM code. */
792 static void
793 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
794 register int len, register int face_id)
796 unsigned char *conversion_buffer;
797 struct coding_system *coding;
799 struct tty_display_info *tty = FRAME_TTY (f);
801 tty_turn_off_insert (tty);
802 tty_hide_cursor (tty);
804 /* Don't dare write in last column of bottom line, if Auto-Wrap,
805 since that would scroll the whole frame on some terminals. */
807 if (AutoWrap (tty)
808 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
809 && (curX (tty) + len) == FRAME_COLS (f))
810 len --;
811 if (len <= 0)
812 return;
814 cmplus (tty, len);
816 /* If terminal_coding does any conversion, use it, otherwise use
817 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
818 because it always return 1 if the member src_multibyte is 1. */
819 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
820 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
821 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
822 the tail. */
823 coding->mode &= ~CODING_MODE_LAST_BLOCK;
825 /* Turn appearance modes of the face. */
826 tty_highlight_if_desired (tty);
827 turn_on_face (f, face_id);
829 coding->mode |= CODING_MODE_LAST_BLOCK;
830 conversion_buffer = encode_terminal_code (string, len, coding);
831 if (coding->produced > 0)
833 block_input ();
834 fwrite (conversion_buffer, 1, coding->produced, tty->output);
835 if (ferror (tty->output))
836 clearerr (tty->output);
837 if (tty->termscript)
838 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
839 unblock_input ();
842 /* Turn appearance modes off. */
843 turn_off_face (f, face_id);
844 tty_turn_off_highlight (tty);
846 cmcheckmagic (tty);
848 #endif
850 /* An implementation of insert_glyphs for termcap frames. */
852 static void
853 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
855 char *buf;
856 struct glyph *glyph = NULL;
857 unsigned char *conversion_buffer;
858 unsigned char space[1];
859 struct coding_system *coding;
861 struct tty_display_info *tty = FRAME_TTY (f);
863 if (tty->TS_ins_multi_chars)
865 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
866 OUTPUT1 (tty, buf);
867 xfree (buf);
868 if (start)
869 write_glyphs (f, start, len);
870 return;
873 tty_turn_on_insert (tty);
874 cmplus (tty, len);
876 if (! start)
877 space[0] = SPACEGLYPH;
879 /* If terminal_coding does any conversion, use it, otherwise use
880 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
881 because it always return 1 if the member src_multibyte is 1. */
882 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
883 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
884 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
885 the tail. */
886 coding->mode &= ~CODING_MODE_LAST_BLOCK;
888 while (len-- > 0)
890 OUTPUT1_IF (tty, tty->TS_ins_char);
891 if (!start)
893 conversion_buffer = space;
894 coding->produced = 1;
896 else
898 tty_highlight_if_desired (tty);
899 turn_on_face (f, start->face_id);
900 glyph = start;
901 ++start;
902 /* We must open sufficient space for a character which
903 occupies more than one column. */
904 while (len && CHAR_GLYPH_PADDING_P (*start))
906 OUTPUT1_IF (tty, tty->TS_ins_char);
907 start++, len--;
910 if (len <= 0)
911 /* This is the last glyph. */
912 coding->mode |= CODING_MODE_LAST_BLOCK;
914 conversion_buffer = encode_terminal_code (glyph, 1, coding);
917 if (coding->produced > 0)
919 block_input ();
920 fwrite (conversion_buffer, 1, coding->produced, tty->output);
921 if (ferror (tty->output))
922 clearerr (tty->output);
923 if (tty->termscript)
924 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
925 unblock_input ();
928 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
929 if (start)
931 turn_off_face (f, glyph->face_id);
932 tty_turn_off_highlight (tty);
936 cmcheckmagic (tty);
939 /* An implementation of delete_glyphs for termcap frames. */
941 static void
942 tty_delete_glyphs (struct frame *f, int n)
944 char *buf;
945 register int i;
947 struct tty_display_info *tty = FRAME_TTY (f);
949 if (tty->delete_in_insert_mode)
951 tty_turn_on_insert (tty);
953 else
955 tty_turn_off_insert (tty);
956 OUTPUT_IF (tty, tty->TS_delete_mode);
959 if (tty->TS_del_multi_chars)
961 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
962 OUTPUT1 (tty, buf);
963 xfree (buf);
965 else
966 for (i = 0; i < n; i++)
967 OUTPUT1 (tty, tty->TS_del_char);
968 if (!tty->delete_in_insert_mode)
969 OUTPUT_IF (tty, tty->TS_end_delete_mode);
972 /* An implementation of ins_del_lines for termcap frames. */
974 static void
975 tty_ins_del_lines (struct frame *f, int vpos, int n)
977 struct tty_display_info *tty = FRAME_TTY (f);
978 const char *multi =
979 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
980 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
981 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
983 int i = eabs (n);
984 char *buf;
986 /* If the lines below the insertion are being pushed
987 into the end of the window, this is the same as clearing;
988 and we know the lines are already clear, since the matching
989 deletion has already been done. So can ignore this. */
990 /* If the lines below the deletion are blank lines coming
991 out of the end of the window, don't bother,
992 as there will be a matching inslines later that will flush them. */
993 if (FRAME_SCROLL_REGION_OK (f)
994 && vpos + i >= tty->specified_window)
995 return;
996 if (!FRAME_MEMORY_BELOW_FRAME (f)
997 && vpos + i >= FRAME_TOTAL_LINES (f))
998 return;
1000 if (multi)
1002 raw_cursor_to (f, vpos, 0);
1003 tty_background_highlight (tty);
1004 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1005 OUTPUT (tty, buf);
1006 xfree (buf);
1008 else if (single)
1010 raw_cursor_to (f, vpos, 0);
1011 tty_background_highlight (tty);
1012 while (--i >= 0)
1013 OUTPUT (tty, single);
1014 if (tty->TF_teleray)
1015 curX (tty) = 0;
1017 else
1019 tty_set_scroll_region (f, vpos, tty->specified_window);
1020 if (n < 0)
1021 raw_cursor_to (f, tty->specified_window - 1, 0);
1022 else
1023 raw_cursor_to (f, vpos, 0);
1024 tty_background_highlight (tty);
1025 while (--i >= 0)
1026 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1027 tty_set_scroll_region (f, 0, tty->specified_window);
1030 if (!FRAME_SCROLL_REGION_OK (f)
1031 && FRAME_MEMORY_BELOW_FRAME (f)
1032 && n < 0)
1034 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1035 clear_to_end (f);
1039 /* Compute cost of sending "str", in characters,
1040 not counting any line-dependent padding. */
1043 string_cost (const char *str)
1045 cost = 0;
1046 if (str)
1047 tputs (str, 0, evalcost);
1048 return cost;
1051 /* Compute cost of sending "str", in characters,
1052 counting any line-dependent padding at one line. */
1054 static int
1055 string_cost_one_line (const char *str)
1057 cost = 0;
1058 if (str)
1059 tputs (str, 1, evalcost);
1060 return cost;
1063 /* Compute per line amount of line-dependent padding,
1064 in tenths of characters. */
1067 per_line_cost (const char *str)
1069 cost = 0;
1070 if (str)
1071 tputs (str, 0, evalcost);
1072 cost = - cost;
1073 if (str)
1074 tputs (str, 10, evalcost);
1075 return cost;
1078 /* char_ins_del_cost[n] is cost of inserting N characters.
1079 char_ins_del_cost[-n] is cost of deleting N characters.
1080 The length of this vector is based on max_frame_cols. */
1082 int *char_ins_del_vector;
1084 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1086 /* ARGSUSED */
1087 static void
1088 calculate_ins_del_char_costs (struct frame *f)
1090 struct tty_display_info *tty = FRAME_TTY (f);
1091 int ins_startup_cost, del_startup_cost;
1092 int ins_cost_per_char, del_cost_per_char;
1093 register int i;
1094 register int *p;
1096 if (tty->TS_ins_multi_chars)
1098 ins_cost_per_char = 0;
1099 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1101 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1102 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1104 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1105 + string_cost (tty->TS_end_insert_mode))) / 100;
1106 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1107 + string_cost_one_line (tty->TS_pad_inserted_char));
1109 else
1111 ins_startup_cost = 9999;
1112 ins_cost_per_char = 0;
1115 if (tty->TS_del_multi_chars)
1117 del_cost_per_char = 0;
1118 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1120 else if (tty->TS_del_char)
1122 del_startup_cost = (string_cost (tty->TS_delete_mode)
1123 + string_cost (tty->TS_end_delete_mode));
1124 if (tty->delete_in_insert_mode)
1125 del_startup_cost /= 2;
1126 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1128 else
1130 del_startup_cost = 9999;
1131 del_cost_per_char = 0;
1134 /* Delete costs are at negative offsets */
1135 p = &char_ins_del_cost (f)[0];
1136 for (i = FRAME_COLS (f); --i >= 0;)
1137 *--p = (del_startup_cost += del_cost_per_char);
1139 /* Doing nothing is free */
1140 p = &char_ins_del_cost (f)[0];
1141 *p++ = 0;
1143 /* Insert costs are at positive offsets */
1144 for (i = FRAME_COLS (f); --i >= 0;)
1145 *p++ = (ins_startup_cost += ins_cost_per_char);
1148 void
1149 calculate_costs (struct frame *frame)
1151 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1153 if (FRAME_TERMCAP_P (frame))
1155 struct tty_display_info *tty = FRAME_TTY (frame);
1156 register const char *f = (tty->TS_set_scroll_region
1157 ? tty->TS_set_scroll_region
1158 : tty->TS_set_scroll_region_1);
1160 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1162 tty->costs_set = 1;
1164 /* These variables are only used for terminal stuff. They are
1165 allocated once for the terminal frame of X-windows emacs, but not
1166 used afterwards.
1168 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1169 X turns off char_ins_del_ok. */
1171 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1172 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1173 < max_frame_cols)
1174 memory_full (SIZE_MAX);
1176 char_ins_del_vector =
1177 xrealloc (char_ins_del_vector,
1178 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1180 memset (char_ins_del_vector, 0,
1181 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1184 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1185 do_line_insertion_deletion_costs (frame,
1186 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1187 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1188 f, f, 1);
1189 else
1190 do_line_insertion_deletion_costs (frame,
1191 tty->TS_ins_line, tty->TS_ins_multi_lines,
1192 tty->TS_del_line, tty->TS_del_multi_lines,
1193 0, 0, 1);
1195 calculate_ins_del_char_costs (frame);
1197 /* Don't use TS_repeat if its padding is worse than sending the chars */
1198 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1199 tty->RPov = string_cost (tty->TS_repeat);
1200 else
1201 tty->RPov = FRAME_COLS (frame) * 2;
1203 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1207 struct fkey_table {
1208 const char *cap, *name;
1211 /* Termcap capability names that correspond directly to X keysyms.
1212 Some of these (marked "terminfo") aren't supplied by old-style
1213 (Berkeley) termcap entries. They're listed in X keysym order;
1214 except we put the keypad keys first, so that if they clash with
1215 other keys (as on the IBM PC keyboard) they get overridden.
1218 static const struct fkey_table keys[] =
1220 {"kh", "home"}, /* termcap */
1221 {"kl", "left"}, /* termcap */
1222 {"ku", "up"}, /* termcap */
1223 {"kr", "right"}, /* termcap */
1224 {"kd", "down"}, /* termcap */
1225 {"%8", "prior"}, /* terminfo */
1226 {"%5", "next"}, /* terminfo */
1227 {"@7", "end"}, /* terminfo */
1228 {"@1", "begin"}, /* terminfo */
1229 {"*6", "select"}, /* terminfo */
1230 {"%9", "print"}, /* terminfo */
1231 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1233 * "insert" --- see below
1235 {"&8", "undo"}, /* terminfo */
1236 {"%0", "redo"}, /* terminfo */
1237 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1238 {"@0", "find"}, /* terminfo */
1239 {"@2", "cancel"}, /* terminfo */
1240 {"%1", "help"}, /* terminfo */
1242 * "break" goes here, but can't be reliably intercepted with termcap
1244 {"&4", "reset"}, /* terminfo --- actually `restart' */
1246 * "system" and "user" --- no termcaps
1248 {"kE", "clearline"}, /* terminfo */
1249 {"kA", "insertline"}, /* terminfo */
1250 {"kL", "deleteline"}, /* terminfo */
1251 {"kI", "insertchar"}, /* terminfo */
1252 {"kD", "deletechar"}, /* terminfo */
1253 {"kB", "backtab"}, /* terminfo */
1255 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1257 {"@8", "kp-enter"}, /* terminfo */
1259 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1260 * "kp-multiply", "kp-add", "kp-separator",
1261 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1262 * --- no termcaps for any of these.
1264 {"K4", "kp-1"}, /* terminfo */
1266 * "kp-2" --- no termcap
1268 {"K5", "kp-3"}, /* terminfo */
1270 * "kp-4" --- no termcap
1272 {"K2", "kp-5"}, /* terminfo */
1274 * "kp-6" --- no termcap
1276 {"K1", "kp-7"}, /* terminfo */
1278 * "kp-8" --- no termcap
1280 {"K3", "kp-9"}, /* terminfo */
1282 * "kp-equal" --- no termcap
1284 {"k1", "f1"},
1285 {"k2", "f2"},
1286 {"k3", "f3"},
1287 {"k4", "f4"},
1288 {"k5", "f5"},
1289 {"k6", "f6"},
1290 {"k7", "f7"},
1291 {"k8", "f8"},
1292 {"k9", "f9"},
1294 {"&0", "S-cancel"}, /*shifted cancel key*/
1295 {"&9", "S-begin"}, /*shifted begin key*/
1296 {"*0", "S-find"}, /*shifted find key*/
1297 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1298 {"*4", "S-delete"}, /*shifted delete-character key*/
1299 {"*7", "S-end"}, /*shifted end key*/
1300 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1301 {"#1", "S-help"}, /*shifted help key*/
1302 {"#2", "S-home"}, /*shifted home key*/
1303 {"#3", "S-insert"}, /*shifted insert-character key*/
1304 {"#4", "S-left"}, /*shifted left-arrow key*/
1305 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1306 {"%c", "S-next"}, /*shifted next key*/
1307 {"%e", "S-prior"}, /*shifted previous key*/
1308 {"%f", "S-print"}, /*shifted print key*/
1309 {"%g", "S-redo"}, /*shifted redo key*/
1310 {"%i", "S-right"}, /*shifted right-arrow key*/
1311 {"!3", "S-undo"} /*shifted undo key*/
1314 #ifndef DOS_NT
1315 static char **term_get_fkeys_address;
1316 static KBOARD *term_get_fkeys_kboard;
1317 static Lisp_Object term_get_fkeys_1 (void);
1319 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1320 This function scans the termcap function key sequence entries, and
1321 adds entries to Vinput_decode_map for each function key it finds. */
1323 static void
1324 term_get_fkeys (char **address, KBOARD *kboard)
1326 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1327 errors during the call. The only errors should be from Fdefine_key
1328 when given a key sequence containing an invalid prefix key. If the
1329 termcap defines function keys which use a prefix that is already bound
1330 to a command by the default bindings, we should silently ignore that
1331 function key specification, rather than giving the user an error and
1332 refusing to run at all on such a terminal. */
1334 term_get_fkeys_address = address;
1335 term_get_fkeys_kboard = kboard;
1336 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1339 static Lisp_Object
1340 term_get_fkeys_1 (void)
1342 int i;
1344 char **address = term_get_fkeys_address;
1345 KBOARD *kboard = term_get_fkeys_kboard;
1347 /* This can happen if CANNOT_DUMP or with strange options. */
1348 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1349 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1351 for (i = 0; i < ARRAYELTS (keys); i++)
1353 char *sequence = tgetstr (keys[i].cap, address);
1354 if (sequence)
1355 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1356 Fmake_vector (make_number (1),
1357 intern (keys[i].name)));
1360 /* The uses of the "k0" capability are inconsistent; sometimes it
1361 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1362 We will attempt to politely accommodate both systems by testing for
1363 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1366 const char *k_semi = tgetstr ("k;", address);
1367 const char *k0 = tgetstr ("k0", address);
1368 const char *k0_name = "f10";
1370 if (k_semi)
1372 if (k0)
1373 /* Define f0 first, so that f10 takes precedence in case the
1374 key sequences happens to be the same. */
1375 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1376 Fmake_vector (make_number (1), intern ("f0")));
1377 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1378 Fmake_vector (make_number (1), intern ("f10")));
1380 else if (k0)
1381 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1382 Fmake_vector (make_number (1), intern (k0_name)));
1385 /* Set up cookies for numbered function keys above f10. */
1387 char fcap[3], fkey[4];
1389 fcap[0] = 'F'; fcap[2] = '\0';
1390 for (i = 11; i < 64; i++)
1392 if (i <= 19)
1393 fcap[1] = '1' + i - 11;
1394 else if (i <= 45)
1395 fcap[1] = 'A' + i - 20;
1396 else
1397 fcap[1] = 'a' + i - 46;
1400 char *sequence = tgetstr (fcap, address);
1401 if (sequence)
1403 sprintf (fkey, "f%d", i);
1404 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1405 Fmake_vector (make_number (1),
1406 intern (fkey)));
1413 * Various mappings to try and get a better fit.
1416 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1417 if (!tgetstr (cap1, address)) \
1419 char *sequence = tgetstr (cap2, address); \
1420 if (sequence) \
1421 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1422 Fmake_vector (make_number (1), \
1423 intern (sym))); \
1426 /* if there's no key_next keycap, map key_npage to `next' keysym */
1427 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1428 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1429 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1430 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1431 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1432 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1433 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1434 #undef CONDITIONAL_REASSIGN
1437 return Qnil;
1439 #endif /* not DOS_NT */
1442 /***********************************************************************
1443 Character Display Information
1444 ***********************************************************************/
1445 static void append_glyph (struct it *);
1446 static void append_composite_glyph (struct it *);
1447 static void produce_composite_glyph (struct it *);
1448 static void append_glyphless_glyph (struct it *, int, const char *);
1449 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1451 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1452 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1453 the character for which to produce glyphs; IT->face_id contains the
1454 character's face. Padding glyphs are appended if IT->c has a
1455 IT->pixel_width > 1. */
1457 static void
1458 append_glyph (struct it *it)
1460 struct glyph *glyph, *end;
1461 int i;
1463 eassert (it->glyph_row);
1464 glyph = (it->glyph_row->glyphs[it->area]
1465 + it->glyph_row->used[it->area]);
1466 end = it->glyph_row->glyphs[1 + it->area];
1468 /* If the glyph row is reversed, we need to prepend the glyph rather
1469 than append it. */
1470 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1472 struct glyph *g;
1473 int move_by = it->pixel_width;
1475 /* Make room for the new glyphs. */
1476 if (move_by > end - glyph) /* don't overstep end of this area */
1477 move_by = end - glyph;
1478 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1479 g[move_by] = *g;
1480 glyph = it->glyph_row->glyphs[it->area];
1481 end = glyph + move_by;
1484 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1485 right, even in the REVERSED_P case, since (a) all of its u.ch are
1486 identical, and (b) the PADDING_P flag needs to be set for the
1487 leftmost one, because we write to the terminal left-to-right. */
1488 for (i = 0;
1489 i < it->pixel_width && glyph < end;
1490 ++i)
1492 glyph->type = CHAR_GLYPH;
1493 glyph->pixel_width = 1;
1494 glyph->u.ch = it->char_to_display;
1495 glyph->face_id = it->face_id;
1496 glyph->avoid_cursor_p = it->avoid_cursor_p;
1497 glyph->multibyte_p = it->multibyte_p;
1498 glyph->padding_p = i > 0;
1499 glyph->charpos = CHARPOS (it->position);
1500 glyph->object = it->object;
1501 if (it->bidi_p)
1503 glyph->resolved_level = it->bidi_it.resolved_level;
1504 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1505 glyph->bidi_type = it->bidi_it.type;
1507 else
1509 glyph->resolved_level = 0;
1510 glyph->bidi_type = UNKNOWN_BT;
1513 ++it->glyph_row->used[it->area];
1514 ++glyph;
1518 /* For external use. */
1519 void
1520 tty_append_glyph (struct it *it)
1522 append_glyph (it);
1526 /* Produce glyphs for the display element described by IT. *IT
1527 specifies what we want to produce a glyph for (character, image, ...),
1528 and where in the glyph matrix we currently are (glyph row and hpos).
1529 produce_glyphs fills in output fields of *IT with information such as the
1530 pixel width and height of a character, and maybe output actual glyphs at
1531 the same time if IT->glyph_row is non-null. For an overview, see
1532 the explanation in dispextern.h, before the definition of the
1533 display_element_type enumeration.
1535 produce_glyphs also stores the result of glyph width, ascent
1536 etc. computations in *IT.
1538 IT->glyph_row may be null, in which case produce_glyphs does not
1539 actually fill in the glyphs. This is used in the move_* functions
1540 in xdisp.c for text width and height computations.
1542 Callers usually don't call produce_glyphs directly;
1543 instead they use the macro PRODUCE_GLYPHS. */
1545 void
1546 produce_glyphs (struct it *it)
1548 /* If a hook is installed, let it do the work. */
1550 /* Nothing but characters are supported on terminal frames. */
1551 eassert (it->what == IT_CHARACTER
1552 || it->what == IT_COMPOSITION
1553 || it->what == IT_STRETCH
1554 || it->what == IT_GLYPHLESS);
1556 if (it->what == IT_STRETCH)
1558 produce_stretch_glyph (it);
1559 goto done;
1562 if (it->what == IT_COMPOSITION)
1564 produce_composite_glyph (it);
1565 goto done;
1568 if (it->what == IT_GLYPHLESS)
1570 produce_glyphless_glyph (it, Qnil);
1571 goto done;
1574 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1576 it->pixel_width = it->nglyphs = 1;
1577 if (it->glyph_row)
1578 append_glyph (it);
1580 else if (it->char_to_display == '\n')
1581 it->pixel_width = it->nglyphs = 0;
1582 else if (it->char_to_display == '\t')
1584 int absolute_x = (it->current_x
1585 + it->continuation_lines_width);
1586 int next_tab_x
1587 = (((1 + absolute_x + it->tab_width - 1)
1588 / it->tab_width)
1589 * it->tab_width);
1590 int nspaces;
1592 /* If part of the TAB has been displayed on the previous line
1593 which is continued now, continuation_lines_width will have
1594 been incremented already by the part that fitted on the
1595 continued line. So, we will get the right number of spaces
1596 here. */
1597 nspaces = next_tab_x - absolute_x;
1599 if (it->glyph_row)
1601 int n = nspaces;
1603 it->char_to_display = ' ';
1604 it->pixel_width = it->len = 1;
1606 while (n--)
1607 append_glyph (it);
1610 it->pixel_width = nspaces;
1611 it->nglyphs = nspaces;
1613 else if (CHAR_BYTE8_P (it->char_to_display))
1615 /* Coming here means that we must send the raw 8-bit byte as is
1616 to the terminal. Although there's no way to know how many
1617 columns it occupies on a screen, it is a good assumption that
1618 a single byte code has 1-column width. */
1619 it->pixel_width = it->nglyphs = 1;
1620 if (it->glyph_row)
1621 append_glyph (it);
1623 else
1625 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1627 if (char_charset (it->char_to_display, charset_list, NULL))
1629 it->pixel_width = CHARACTER_WIDTH (it->char_to_display);
1630 it->nglyphs = it->pixel_width;
1631 if (it->glyph_row)
1632 append_glyph (it);
1634 else
1636 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1638 eassert (it->what == IT_GLYPHLESS);
1639 produce_glyphless_glyph (it, acronym);
1643 done:
1644 /* Advance current_x by the pixel width as a convenience for
1645 the caller. */
1646 if (it->area == TEXT_AREA)
1647 it->current_x += it->pixel_width;
1648 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1649 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1652 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1653 Called from produce_composite_glyph for terminal frames if
1654 IT->glyph_row != NULL. IT->face_id contains the character's
1655 face. */
1657 static void
1658 append_composite_glyph (struct it *it)
1660 struct glyph *glyph;
1662 eassert (it->glyph_row);
1663 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1664 if (glyph < it->glyph_row->glyphs[1 + it->area])
1666 /* If the glyph row is reversed, we need to prepend the glyph
1667 rather than append it. */
1668 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1670 struct glyph *g;
1672 /* Make room for the new glyph. */
1673 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1674 g[1] = *g;
1675 glyph = it->glyph_row->glyphs[it->area];
1677 glyph->type = COMPOSITE_GLYPH;
1678 eassert (it->pixel_width <= SHRT_MAX);
1679 glyph->pixel_width = it->pixel_width;
1680 glyph->u.cmp.id = it->cmp_it.id;
1681 if (it->cmp_it.ch < 0)
1683 glyph->u.cmp.automatic = 0;
1684 glyph->u.cmp.id = it->cmp_it.id;
1686 else
1688 glyph->u.cmp.automatic = 1;
1689 glyph->u.cmp.id = it->cmp_it.id;
1690 glyph->slice.cmp.from = it->cmp_it.from;
1691 glyph->slice.cmp.to = it->cmp_it.to - 1;
1694 glyph->avoid_cursor_p = it->avoid_cursor_p;
1695 glyph->multibyte_p = it->multibyte_p;
1696 glyph->face_id = it->face_id;
1697 glyph->padding_p = false;
1698 glyph->charpos = CHARPOS (it->position);
1699 glyph->object = it->object;
1700 if (it->bidi_p)
1702 glyph->resolved_level = it->bidi_it.resolved_level;
1703 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1704 glyph->bidi_type = it->bidi_it.type;
1706 else
1708 glyph->resolved_level = 0;
1709 glyph->bidi_type = UNKNOWN_BT;
1712 ++it->glyph_row->used[it->area];
1713 ++glyph;
1718 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1719 the composition. We simply produces components of the composition
1720 assuming that the terminal has a capability to layout/render it
1721 correctly. */
1723 static void
1724 produce_composite_glyph (struct it *it)
1726 if (it->cmp_it.ch < 0)
1728 struct composition *cmp = composition_table[it->cmp_it.id];
1730 it->pixel_width = cmp->width;
1732 else
1734 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1736 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1737 it->cmp_it.to, NULL);
1739 it->nglyphs = 1;
1740 if (it->glyph_row)
1741 append_composite_glyph (it);
1745 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1746 is a face ID to be used for the glyph. What is actually appended
1747 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1748 comes from it->nglyphs bytes). */
1750 static void
1751 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1753 struct glyph *glyph, *end;
1754 int i;
1756 eassert (it->glyph_row);
1757 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1758 end = it->glyph_row->glyphs[1 + it->area];
1760 /* If the glyph row is reversed, we need to prepend the glyph rather
1761 than append it. */
1762 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1764 struct glyph *g;
1765 int move_by = it->pixel_width;
1767 /* Make room for the new glyphs. */
1768 if (move_by > end - glyph) /* don't overstep end of this area */
1769 move_by = end - glyph;
1770 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1771 g[move_by] = *g;
1772 glyph = it->glyph_row->glyphs[it->area];
1773 end = glyph + move_by;
1776 if (glyph >= end)
1777 return;
1778 glyph->type = CHAR_GLYPH;
1779 glyph->pixel_width = 1;
1780 glyph->avoid_cursor_p = it->avoid_cursor_p;
1781 glyph->multibyte_p = it->multibyte_p;
1782 glyph->face_id = face_id;
1783 glyph->padding_p = false;
1784 glyph->charpos = CHARPOS (it->position);
1785 glyph->object = it->object;
1786 if (it->bidi_p)
1788 glyph->resolved_level = it->bidi_it.resolved_level;
1789 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1790 glyph->bidi_type = it->bidi_it.type;
1792 else
1794 glyph->resolved_level = 0;
1795 glyph->bidi_type = UNKNOWN_BT;
1798 /* BIDI Note: we put the glyphs of characters left to right, even in
1799 the REVERSED_P case because we write to the terminal
1800 left-to-right. */
1801 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1803 if (i > 0)
1804 glyph[0] = glyph[-1];
1805 glyph->u.ch = str[i];
1806 ++it->glyph_row->used[it->area];
1807 ++glyph;
1811 /* Produce glyphs for a glyphless character for iterator IT.
1812 IT->glyphless_method specifies which method to use for displaying
1813 the character. See the description of enum
1814 glyphless_display_method in dispextern.h for the details.
1816 ACRONYM, if non-nil, is an acronym string for the character.
1818 The glyphs actually produced are of type CHAR_GLYPH. */
1820 static void
1821 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1823 int len, face_id = merge_glyphless_glyph_face (it);
1824 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1825 char const *str = " ";
1827 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1829 /* As there's no way to produce a thin space, we produce a space
1830 of canonical width. */
1831 len = 1;
1833 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1835 len = CHARACTER_WIDTH (it->c);
1836 if (len == 0)
1837 len = 1;
1838 else if (len > 4)
1839 len = 4;
1840 len = sprintf (buf, "[%.*s]", len, str);
1841 str = buf;
1843 else
1845 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1847 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1848 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1849 if (CONSP (acronym))
1850 acronym = XCDR (acronym);
1851 buf[0] = '[';
1852 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1853 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1854 buf[1 + len] = str[len];
1855 buf[1 + len] = ']';
1856 len += 2;
1858 else
1860 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1861 len = sprintf (buf,
1862 (it->c < 0x10000 ? "\\u%04X"
1863 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1864 : "\\x%06X"),
1865 it->c + 0u);
1867 str = buf;
1870 it->pixel_width = len;
1871 it->nglyphs = len;
1872 if (it->glyph_row)
1873 append_glyphless_glyph (it, face_id, str);
1877 /***********************************************************************
1878 Faces
1879 ***********************************************************************/
1881 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1882 one of the enumerators from enum no_color_bit, or a bit set built
1883 from them. Some display attributes may not be used together with
1884 color; the termcap capability `NC' specifies which ones. */
1886 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1887 (tty->TN_max_colors > 0 \
1888 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1889 : 1)
1891 /* Turn appearances of face FACE_ID on tty frame F on.
1892 FACE_ID is a realized face ID number, in the face cache. */
1894 static void
1895 turn_on_face (struct frame *f, int face_id)
1897 struct face *face = FACE_FROM_ID (f, face_id);
1898 unsigned long fg = face->foreground;
1899 unsigned long bg = face->background;
1900 struct tty_display_info *tty = FRAME_TTY (f);
1902 /* Use reverse video if the face specifies that.
1903 Do this first because TS_end_standout_mode may be the same
1904 as TS_exit_attribute_mode, which turns all appearances off. */
1905 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1906 && (inverse_video
1907 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1908 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1909 tty_toggle_highlight (tty);
1911 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1912 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1914 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1916 if (tty->TS_enter_italic_mode)
1917 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1918 else
1919 /* Italics mode is unavailable on many terminals. In that
1920 case, map slant to dimmed text; we want italic text to
1921 appear different and dimming is not otherwise used. */
1922 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1925 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1926 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1928 if (tty->TN_max_colors > 0)
1930 const char *ts;
1931 char *p;
1933 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1934 if (face_tty_specified_color (fg) && ts)
1936 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1937 OUTPUT (tty, p);
1938 xfree (p);
1941 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1942 if (face_tty_specified_color (bg) && ts)
1944 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1945 OUTPUT (tty, p);
1946 xfree (p);
1952 /* Turn off appearances of face FACE_ID on tty frame F. */
1954 static void
1955 turn_off_face (struct frame *f, int face_id)
1957 struct face *face = FACE_FROM_ID (f, face_id);
1958 struct tty_display_info *tty = FRAME_TTY (f);
1960 if (tty->TS_exit_attribute_mode)
1962 /* Capability "me" will turn off appearance modes double-bright,
1963 half-bright, reverse-video, standout, underline. It may or
1964 may not turn off alt-char-mode. */
1965 if (face->tty_bold_p
1966 || face->tty_italic_p
1967 || face->tty_reverse_p
1968 || face->tty_underline_p)
1970 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1971 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1972 tty->standout_mode = 0;
1975 else
1977 /* If we don't have "me" we can only have those appearances
1978 that have exit sequences defined. */
1979 if (face->tty_underline_p)
1980 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1983 /* Switch back to default colors. */
1984 if (tty->TN_max_colors > 0
1985 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1986 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1987 || (face->background != FACE_TTY_DEFAULT_COLOR
1988 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1989 OUTPUT1_IF (tty, tty->TS_orig_pair);
1993 /* Return true if the terminal on frame F supports all of the
1994 capabilities in CAPS simultaneously. */
1996 bool
1997 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
1999 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2000 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2001 return 0;
2003 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2004 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2005 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2006 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2009 /* We can do it! */
2010 return 1;
2013 /* Return non-zero if the terminal is capable to display colors. */
2015 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2016 0, 1, 0,
2017 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2019 TERMINAL can be a terminal object, a frame, or nil (meaning the
2020 selected frame's terminal). This function always returns nil if
2021 TERMINAL does not refer to a text terminal. */)
2022 (Lisp_Object terminal)
2024 struct terminal *t = decode_tty_terminal (terminal);
2026 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2029 /* Return the number of supported colors. */
2030 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2031 Stty_display_color_cells, 0, 1, 0,
2032 doc: /* Return the number of colors supported by the tty device TERMINAL.
2034 TERMINAL can be a terminal object, a frame, or nil (meaning the
2035 selected frame's terminal). This function always returns 0 if
2036 TERMINAL does not refer to a text terminal. */)
2037 (Lisp_Object terminal)
2039 struct terminal *t = decode_tty_terminal (terminal);
2041 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2044 #ifndef DOS_NT
2046 /* Declare here rather than in the function, as in the rest of Emacs,
2047 to work around an HPUX compiler bug (?). See
2048 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2049 static int default_max_colors;
2050 static int default_max_pairs;
2051 static int default_no_color_video;
2052 static char *default_orig_pair;
2053 static char *default_set_foreground;
2054 static char *default_set_background;
2056 /* Save or restore the default color-related capabilities of this
2057 terminal. */
2058 static void
2059 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2062 if (save)
2064 dupstring (&default_orig_pair, tty->TS_orig_pair);
2065 dupstring (&default_set_foreground, tty->TS_set_foreground);
2066 dupstring (&default_set_background, tty->TS_set_background);
2067 default_max_colors = tty->TN_max_colors;
2068 default_max_pairs = tty->TN_max_pairs;
2069 default_no_color_video = tty->TN_no_color_video;
2071 else
2073 tty->TS_orig_pair = default_orig_pair;
2074 tty->TS_set_foreground = default_set_foreground;
2075 tty->TS_set_background = default_set_background;
2076 tty->TN_max_colors = default_max_colors;
2077 tty->TN_max_pairs = default_max_pairs;
2078 tty->TN_no_color_video = default_no_color_video;
2082 /* Setup one of the standard tty color schemes according to MODE.
2083 MODE's value is generally the number of colors which we want to
2084 support; zero means set up for the default capabilities, the ones
2085 we saw at init_tty time; -1 means turn off color support. */
2086 static void
2087 tty_setup_colors (struct tty_display_info *tty, int mode)
2089 /* Canonicalize all negative values of MODE. */
2090 if (mode < -1)
2091 mode = -1;
2093 switch (mode)
2095 case -1: /* no colors at all */
2096 tty->TN_max_colors = 0;
2097 tty->TN_max_pairs = 0;
2098 tty->TN_no_color_video = 0;
2099 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2100 break;
2101 case 0: /* default colors, if any */
2102 default:
2103 tty_default_color_capabilities (tty, 0);
2104 break;
2105 case 8: /* 8 standard ANSI colors */
2106 tty->TS_orig_pair = "\033[0m";
2107 #ifdef TERMINFO
2108 tty->TS_set_foreground = "\033[3%p1%dm";
2109 tty->TS_set_background = "\033[4%p1%dm";
2110 #else
2111 tty->TS_set_foreground = "\033[3%dm";
2112 tty->TS_set_background = "\033[4%dm";
2113 #endif
2114 tty->TN_max_colors = 8;
2115 tty->TN_max_pairs = 64;
2116 tty->TN_no_color_video = 0;
2117 break;
2121 void
2122 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2124 Lisp_Object tem, val;
2125 Lisp_Object color_mode;
2126 int mode;
2127 Lisp_Object tty_color_mode_alist
2128 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2130 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2131 val = CONSP (tem) ? XCDR (tem) : Qnil;
2133 if (INTEGERP (val))
2134 color_mode = val;
2135 else if (SYMBOLP (tty_color_mode_alist))
2137 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2138 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2140 else
2141 color_mode = Qnil;
2143 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2145 if (mode != tty->previous_color_mode)
2147 tty->previous_color_mode = mode;
2148 tty_setup_colors (tty , mode);
2149 /* This recomputes all the faces given the new color definitions. */
2150 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2154 #endif /* !DOS_NT */
2156 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2157 doc: /* Return the type of the tty device that TERMINAL uses.
2158 Returns nil if TERMINAL is not on a tty device.
2160 TERMINAL can be a terminal object, a frame, or nil (meaning the
2161 selected frame's terminal). */)
2162 (Lisp_Object terminal)
2164 struct terminal *t = decode_tty_terminal (terminal);
2166 return (t && t->display_info.tty->type
2167 ? build_string (t->display_info.tty->type) : Qnil);
2170 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2171 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2173 TERMINAL can be a terminal object, a frame, or nil (meaning the
2174 selected frame's terminal). This function always returns nil if
2175 TERMINAL is not on a tty device. */)
2176 (Lisp_Object terminal)
2178 struct terminal *t = decode_tty_terminal (terminal);
2180 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2183 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2184 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2185 This is used to override the terminfo data, for certain terminals that
2186 do not really do underlining, but say that they do. This function has
2187 no effect if used on a non-tty terminal.
2189 TERMINAL can be a terminal object, a frame or nil (meaning the
2190 selected frame's terminal). This function always returns nil if
2191 TERMINAL does not refer to a text terminal. */)
2192 (Lisp_Object terminal)
2194 struct terminal *t = decode_live_terminal (terminal);
2196 if (t->type == output_termcap)
2197 t->display_info.tty->TS_enter_underline_mode = 0;
2198 return Qnil;
2201 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2202 doc: /* Return the topmost terminal frame on TERMINAL.
2203 TERMINAL can be a terminal object, a frame or nil (meaning the
2204 selected frame's terminal). This function returns nil if TERMINAL
2205 does not refer to a text terminal. Otherwise, it returns the
2206 top-most frame on the text terminal. */)
2207 (Lisp_Object terminal)
2209 struct terminal *t = decode_live_terminal (terminal);
2211 if (t->type == output_termcap)
2212 return t->display_info.tty->top_frame;
2213 return Qnil;
2218 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2219 doc: /* Suspend the terminal device TTY.
2221 The device is restored to its default state, and Emacs ceases all
2222 access to the tty device. Frames that use the device are not deleted,
2223 but input is not read from them and if they change, their display is
2224 not updated.
2226 TTY may be a terminal object, a frame, or nil for the terminal device
2227 of the currently selected frame.
2229 This function runs `suspend-tty-functions' after suspending the
2230 device. The functions are run with one arg, the id of the suspended
2231 terminal device.
2233 `suspend-tty' does nothing if it is called on a device that is already
2234 suspended.
2236 A suspended tty may be resumed by calling `resume-tty' on it. */)
2237 (Lisp_Object tty)
2239 struct terminal *t = decode_tty_terminal (tty);
2240 FILE *f;
2242 if (!t)
2243 error ("Attempt to suspend a non-text terminal device");
2245 f = t->display_info.tty->input;
2247 if (f)
2249 /* First run `suspend-tty-functions' and then clean up the tty
2250 state because `suspend-tty-functions' might need to change
2251 the tty state. */
2252 Lisp_Object term;
2253 XSETTERMINAL (term, t);
2254 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2256 reset_sys_modes (t->display_info.tty);
2257 delete_keyboard_wait_descriptor (fileno (f));
2259 #ifndef MSDOS
2260 fclose (f);
2261 if (f != t->display_info.tty->output)
2262 fclose (t->display_info.tty->output);
2263 #endif
2265 t->display_info.tty->input = 0;
2266 t->display_info.tty->output = 0;
2268 if (FRAMEP (t->display_info.tty->top_frame))
2269 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2273 /* Clear display hooks to prevent further output. */
2274 clear_tty_hooks (t);
2276 return Qnil;
2279 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2280 doc: /* Resume the previously suspended terminal device TTY.
2281 The terminal is opened and reinitialized. Frames that are on the
2282 suspended terminal are revived.
2284 It is an error to resume a terminal while another terminal is active
2285 on the same device.
2287 This function runs `resume-tty-functions' after resuming the terminal.
2288 The functions are run with one arg, the id of the resumed terminal
2289 device.
2291 `resume-tty' does nothing if it is called on a device that is not
2292 suspended.
2294 TTY may be a terminal object, a frame, or nil (meaning the selected
2295 frame's terminal). */)
2296 (Lisp_Object tty)
2298 struct terminal *t = decode_tty_terminal (tty);
2299 int fd;
2301 if (!t)
2302 error ("Attempt to resume a non-text terminal device");
2304 if (!t->display_info.tty->input)
2306 if (get_named_terminal (t->display_info.tty->name))
2307 error ("Cannot resume display while another display is active on the same device");
2309 #ifdef MSDOS
2310 t->display_info.tty->output = stdout;
2311 t->display_info.tty->input = stdin;
2312 #else /* !MSDOS */
2313 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2314 t->display_info.tty->input = t->display_info.tty->output
2315 = fd < 0 ? 0 : fdopen (fd, "w+");
2317 if (! t->display_info.tty->input)
2319 int open_errno = errno;
2320 emacs_close (fd);
2321 report_file_errno ("Cannot reopen tty device",
2322 build_string (t->display_info.tty->name),
2323 open_errno);
2326 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2327 dissociate_if_controlling_tty (fd);
2328 #endif
2330 add_keyboard_wait_descriptor (fd);
2332 if (FRAMEP (t->display_info.tty->top_frame))
2334 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2335 int width, height;
2336 int old_height = FRAME_COLS (f);
2337 int old_width = FRAME_TOTAL_LINES (f);
2339 /* Check if terminal/window size has changed while the frame
2340 was suspended. */
2341 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2342 if (width != old_width || height != old_height)
2343 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2344 0, 0, 0, 0);
2345 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2348 set_tty_hooks (t);
2349 init_sys_modes (t->display_info.tty);
2351 /* Run `resume-tty-functions'. */
2352 Lisp_Object term;
2353 XSETTERMINAL (term, t);
2354 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2357 set_tty_hooks (t);
2359 return Qnil;
2363 /***********************************************************************
2364 Mouse
2365 ***********************************************************************/
2367 #ifdef HAVE_GPM
2369 #ifndef HAVE_WINDOW_SYSTEM
2370 void
2371 term_mouse_moveto (int x, int y)
2373 /* TODO: how to set mouse position?
2374 const char *name;
2375 int fd;
2376 name = (const char *) ttyname (0);
2377 fd = emacs_open (name, O_WRONLY, 0);
2378 SOME_FUNCTION (x, y, fd);
2379 emacs_close (fd);
2380 last_mouse_x = x;
2381 last_mouse_y = y; */
2383 #endif /* HAVE_WINDOW_SYSTEM */
2385 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2386 void
2387 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2388 int start_hpos, int end_hpos,
2389 enum draw_glyphs_face draw)
2391 int nglyphs = end_hpos - start_hpos;
2392 struct frame *f = XFRAME (WINDOW_FRAME (w));
2393 struct tty_display_info *tty = FRAME_TTY (f);
2394 int face_id = tty->mouse_highlight.mouse_face_face_id;
2395 int save_x, save_y, pos_x, pos_y;
2397 if (end_hpos >= row->used[TEXT_AREA])
2398 nglyphs = row->used[TEXT_AREA] - start_hpos;
2400 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2401 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2403 /* Save current cursor co-ordinates. */
2404 save_y = curY (tty);
2405 save_x = curX (tty);
2406 cursor_to (f, pos_y, pos_x);
2408 if (draw == DRAW_MOUSE_FACE)
2409 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2410 nglyphs, face_id);
2411 else if (draw == DRAW_NORMAL_TEXT)
2412 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2414 cursor_to (f, save_y, save_x);
2417 static bool
2418 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2420 /* Has the mouse moved off the glyph it was on at the last sighting? */
2421 if (event->x != last_mouse_x || event->y != last_mouse_y)
2423 frame->mouse_moved = 1;
2424 note_mouse_highlight (frame, event->x, event->y);
2425 /* Remember which glyph we're now on. */
2426 last_mouse_x = event->x;
2427 last_mouse_y = event->y;
2428 return 1;
2430 return 0;
2433 /* Return the Time that corresponds to T. Wrap around on overflow. */
2434 static Time
2435 timeval_to_Time (struct timeval const *t)
2437 Time s_1000, ms;
2439 s_1000 = t->tv_sec;
2440 s_1000 *= 1000;
2441 ms = t->tv_usec / 1000;
2442 return s_1000 + ms;
2445 /* Return the current position of the mouse.
2447 Set *f to the frame the mouse is in, or zero if the mouse is in no
2448 Emacs frame. If it is set to zero, all the other arguments are
2449 garbage.
2451 Set *bar_window to Qnil, and *x and *y to the column and
2452 row of the character cell the mouse is over.
2454 Set *timeptr to the time the mouse was at the returned position.
2456 This clears mouse_moved until the next motion
2457 event arrives. */
2458 static void
2459 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2460 enum scroll_bar_part *part, Lisp_Object *x,
2461 Lisp_Object *y, Time *timeptr)
2463 struct timeval now;
2465 *fp = SELECTED_FRAME ();
2466 (*fp)->mouse_moved = 0;
2468 *bar_window = Qnil;
2469 *part = scroll_bar_above_handle;
2471 XSETINT (*x, last_mouse_x);
2472 XSETINT (*y, last_mouse_y);
2473 gettimeofday(&now, 0);
2474 *timeptr = timeval_to_Time (&now);
2477 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2479 If the event is a button press, then note that we have grabbed
2480 the mouse. */
2482 static Lisp_Object
2483 term_mouse_click (struct input_event *result, Gpm_Event *event,
2484 struct frame *f)
2486 struct timeval now;
2487 int i, j;
2489 result->kind = GPM_CLICK_EVENT;
2490 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2492 if (event->buttons & j) {
2493 result->code = i; /* button number */
2494 break;
2497 gettimeofday(&now, 0);
2498 result->timestamp = timeval_to_Time (&now);
2500 if (event->type & GPM_UP)
2501 result->modifiers = up_modifier;
2502 else if (event->type & GPM_DOWN)
2503 result->modifiers = down_modifier;
2504 else
2505 result->modifiers = 0;
2507 if (event->type & GPM_SINGLE)
2508 result->modifiers |= click_modifier;
2510 if (event->type & GPM_DOUBLE)
2511 result->modifiers |= double_modifier;
2513 if (event->type & GPM_TRIPLE)
2514 result->modifiers |= triple_modifier;
2516 if (event->type & GPM_DRAG)
2517 result->modifiers |= drag_modifier;
2519 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2521 /* 1 << KG_SHIFT */
2522 if (event->modifiers & (1 << 0))
2523 result->modifiers |= shift_modifier;
2525 /* 1 << KG_CTRL */
2526 if (event->modifiers & (1 << 2))
2527 result->modifiers |= ctrl_modifier;
2529 /* 1 << KG_ALT || KG_ALTGR */
2530 if (event->modifiers & (1 << 3)
2531 || event->modifiers & (1 << 1))
2532 result->modifiers |= meta_modifier;
2535 XSETINT (result->x, event->x);
2536 XSETINT (result->y, event->y);
2537 XSETFRAME (result->frame_or_window, f);
2538 result->arg = Qnil;
2539 return Qnil;
2543 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2545 struct frame *f = XFRAME (tty->top_frame);
2546 struct input_event ie;
2547 bool do_help = 0;
2548 int count = 0;
2550 EVENT_INIT (ie);
2551 ie.kind = NO_EVENT;
2552 ie.arg = Qnil;
2554 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2555 previous_help_echo_string = help_echo_string;
2556 help_echo_string = Qnil;
2558 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2560 if (!term_mouse_movement (f, event))
2561 help_echo_string = previous_help_echo_string;
2563 /* If the contents of the global variable help_echo_string
2564 has changed, generate a HELP_EVENT. */
2565 if (!NILP (help_echo_string)
2566 || !NILP (previous_help_echo_string))
2567 do_help = 1;
2569 goto done;
2571 else {
2572 f->mouse_moved = 0;
2573 term_mouse_click (&ie, event, f);
2576 done:
2577 if (ie.kind != NO_EVENT)
2579 kbd_buffer_store_event_hold (&ie, hold_quit);
2580 count++;
2583 if (do_help
2584 && !(hold_quit && hold_quit->kind != NO_EVENT))
2586 Lisp_Object frame;
2588 if (f)
2589 XSETFRAME (frame, f);
2590 else
2591 frame = Qnil;
2593 gen_help_event (help_echo_string, frame, help_echo_window,
2594 help_echo_object, help_echo_pos);
2595 count++;
2598 return count;
2601 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2602 0, 0, 0,
2603 doc: /* Open a connection to Gpm.
2604 Gpm-mouse can only be activated for one tty at a time. */)
2605 (void)
2607 struct frame *f = SELECTED_FRAME ();
2608 struct tty_display_info *tty
2609 = ((f)->output_method == output_termcap
2610 ? (f)->terminal->display_info.tty : NULL);
2611 Gpm_Connect connection;
2613 if (!tty)
2614 error ("Gpm-mouse only works in the GNU/Linux console");
2615 if (gpm_tty == tty)
2616 return Qnil; /* Already activated, nothing to do. */
2617 if (gpm_tty)
2618 error ("Gpm-mouse can only be activated for one tty at a time");
2620 connection.eventMask = ~0;
2621 connection.defaultMask = ~GPM_HARD;
2622 connection.maxMod = ~0;
2623 connection.minMod = 0;
2624 gpm_zerobased = 1;
2626 if (Gpm_Open (&connection, 0) < 0)
2627 error ("Gpm-mouse failed to connect to the gpm daemon");
2628 else
2630 gpm_tty = tty;
2631 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2632 to generate SIGIOs. Apparently we need to call reset_sys_modes
2633 before calling init_sys_modes. */
2634 reset_sys_modes (tty);
2635 init_sys_modes (tty);
2636 add_gpm_wait_descriptor (gpm_fd);
2637 return Qnil;
2641 void
2642 close_gpm (int fd)
2644 if (fd >= 0)
2645 delete_gpm_wait_descriptor (fd);
2646 while (Gpm_Close()); /* close all the stack */
2647 gpm_tty = NULL;
2650 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2651 0, 0, 0,
2652 doc: /* Close a connection to Gpm. */)
2653 (void)
2655 struct frame *f = SELECTED_FRAME ();
2656 struct tty_display_info *tty
2657 = ((f)->output_method == output_termcap
2658 ? (f)->terminal->display_info.tty : NULL);
2660 if (!tty || gpm_tty != tty)
2661 return Qnil; /* Not activated on this terminal, nothing to do. */
2663 close_gpm (gpm_fd);
2664 return Qnil;
2666 #endif /* HAVE_GPM */
2669 /***********************************************************************
2670 Menus
2671 ***********************************************************************/
2673 #if !defined (MSDOS)
2675 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2677 However, unlike on MSDOS, where the menu text is drawn directly to
2678 the display video memory, on a TTY we use display_string (see
2679 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2680 the menu items into the frame's 'desired_matrix' glyph matrix, and
2681 then call update_frame_with_menu to deliver the results to the
2682 glass. The previous contents of the screen, in the form of the
2683 current_matrix, is stashed away, and used to restore screen
2684 contents when the menu selection changes or when the final
2685 selection is made and the menu should be popped down.
2687 The idea of this implementation was suggested by Gerd Moellmann. */
2689 #define TTYM_FAILURE -1
2690 #define TTYM_SUCCESS 1
2691 #define TTYM_NO_SELECT 2
2692 #define TTYM_IA_SELECT 3
2693 #define TTYM_NEXT 4
2694 #define TTYM_PREV 5
2696 /* These hold text of the current and the previous menu help messages. */
2697 static const char *menu_help_message, *prev_menu_help_message;
2698 /* Pane number and item number of the menu item which generated the
2699 last menu help message. */
2700 static int menu_help_paneno, menu_help_itemno;
2702 typedef struct tty_menu_struct
2704 int count;
2705 char **text;
2706 struct tty_menu_struct **submenu;
2707 int *panenumber; /* Also used as enabled flag. */
2708 ptrdiff_t allocated;
2709 int panecount;
2710 int width;
2711 const char **help_text;
2712 } tty_menu;
2714 /* Create a brand new menu structure. */
2716 static tty_menu *
2717 tty_menu_create (void)
2719 return xzalloc (sizeof *tty_menu_create ());
2722 /* Allocate some (more) memory for MENU ensuring that there is room for one
2723 more item. */
2725 static void
2726 tty_menu_make_room (tty_menu *menu)
2728 if (menu->allocated == menu->count)
2730 ptrdiff_t allocated = menu->allocated;
2731 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2732 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2733 menu->submenu = xrealloc (menu->submenu,
2734 allocated * sizeof *menu->submenu);
2735 menu->panenumber = xrealloc (menu->panenumber,
2736 allocated * sizeof *menu->panenumber);
2737 menu->help_text = xrealloc (menu->help_text,
2738 allocated * sizeof *menu->help_text);
2739 menu->allocated = allocated;
2743 /* Search the given menu structure for a given pane number. */
2745 static tty_menu *
2746 tty_menu_search_pane (tty_menu *menu, int pane)
2748 int i;
2749 tty_menu *try;
2751 for (i = 0; i < menu->count; i++)
2752 if (menu->submenu[i])
2754 if (pane == menu->panenumber[i])
2755 return menu->submenu[i];
2756 try = tty_menu_search_pane (menu->submenu[i], pane);
2757 if (try)
2758 return try;
2760 return (tty_menu *) 0;
2763 /* Determine how much screen space a given menu needs. */
2765 static void
2766 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2768 int i, h2, w2, maxsubwidth, maxheight;
2770 maxsubwidth = menu->width;
2771 maxheight = menu->count;
2772 for (i = 0; i < menu->count; i++)
2774 if (menu->submenu[i])
2776 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2777 if (w2 > maxsubwidth) maxsubwidth = w2;
2778 if (i + h2 > maxheight) maxheight = i + h2;
2781 *width = maxsubwidth;
2782 *height = maxheight;
2785 static void
2786 mouse_get_xy (int *x, int *y)
2788 struct frame *sf = SELECTED_FRAME ();
2789 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2790 enum scroll_bar_part part_dummy;
2791 Time time_dummy;
2793 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2794 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2795 &lisp_dummy, &part_dummy,
2796 &lmx, &lmy,
2797 &time_dummy);
2798 if (!NILP (lmx))
2800 *x = XINT (lmx);
2801 *y = XINT (lmy);
2805 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2806 (zero-based). */
2808 static void
2809 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2810 int mx, int my, int first_item, bool disp_help)
2812 int i, face, width, enabled, mousehere, row, col;
2813 struct frame *sf = SELECTED_FRAME ();
2814 struct tty_display_info *tty = FRAME_TTY (sf);
2815 /* Don't try to display more menu items than the console can display
2816 using the available screen lines. Exclude the echo area line, as
2817 it will be overwritten by the help-echo anyway. */
2818 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2820 menu_help_message = NULL;
2822 width = menu->width;
2823 col = cursorX (tty);
2824 row = cursorY (tty);
2825 for (i = 0; i < max_items; i++)
2827 int max_width = width + 2; /* +2 for padding blanks on each side */
2828 int j = i + first_item;
2830 if (menu->submenu[j])
2831 max_width += 2; /* for displaying " >" after the item */
2832 enabled
2833 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2834 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2835 face = faces[enabled + mousehere * 2];
2836 /* Display the menu help string for the i-th menu item even if
2837 the menu item is currently disabled. That's what the GUI
2838 code does. */
2839 if (disp_help && enabled + mousehere * 2 >= 2)
2841 menu_help_message = menu->help_text[j];
2842 menu_help_paneno = pn - 1;
2843 menu_help_itemno = j;
2845 /* Take note of the coordinates of the active menu item, to
2846 display the cursor there. */
2847 if (mousehere)
2849 row = y + i;
2850 col = x;
2852 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2853 menu->submenu[j] != NULL);
2855 update_frame_with_menu (sf, row, col);
2858 /* --------------------------- X Menu emulation ---------------------- */
2860 /* Create a new pane and place it on the outer-most level. */
2862 static int
2863 tty_menu_add_pane (tty_menu *menu, const char *txt)
2865 int len;
2867 tty_menu_make_room (menu);
2868 menu->submenu[menu->count] = tty_menu_create ();
2869 menu->text[menu->count] = (char *)txt;
2870 menu->panenumber[menu->count] = ++menu->panecount;
2871 menu->help_text[menu->count] = NULL;
2872 menu->count++;
2874 /* Update the menu width, if necessary. */
2875 len = menu_item_width ((const unsigned char *) txt);
2876 if (len > menu->width)
2877 menu->width = len;
2879 return menu->panecount;
2882 /* Create a new item in a menu pane. */
2884 static bool
2885 tty_menu_add_selection (tty_menu *menu, int pane,
2886 char *txt, bool enable, char const *help_text)
2888 int len;
2890 if (pane)
2892 menu = tty_menu_search_pane (menu, pane);
2893 if (! menu)
2894 return 0;
2896 tty_menu_make_room (menu);
2897 menu->submenu[menu->count] = (tty_menu *) 0;
2898 menu->text[menu->count] = txt;
2899 menu->panenumber[menu->count] = enable;
2900 menu->help_text[menu->count] = help_text;
2901 menu->count++;
2903 /* Update the menu width, if necessary. */
2904 len = menu_item_width ((const unsigned char *) txt);
2905 if (len > menu->width)
2906 menu->width = len;
2908 return 1;
2911 /* Decide where the menu would be placed if requested at (X,Y). */
2913 static void
2914 tty_menu_locate (tty_menu *menu, int x, int y,
2915 int *ulx, int *uly, int *width, int *height)
2917 tty_menu_calc_size (menu, width, height);
2918 *ulx = x + 1;
2919 *uly = y;
2920 *width += 2;
2923 struct tty_menu_state
2925 struct glyph_matrix *screen_behind;
2926 tty_menu *menu;
2927 int pane;
2928 int x, y;
2931 /* Save away the contents of frame F's current frame matrix, and
2932 enable all its rows. Value is a glyph matrix holding the contents
2933 of F's current frame matrix with all its glyph rows enabled. */
2935 static struct glyph_matrix *
2936 save_and_enable_current_matrix (struct frame *f)
2938 int i;
2939 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2940 saved->nrows = f->current_matrix->nrows;
2941 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2943 for (i = 0; i < saved->nrows; ++i)
2945 struct glyph_row *from = f->current_matrix->rows + i;
2946 struct glyph_row *to = saved->rows + i;
2947 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2949 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2950 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2951 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2952 /* Make sure every row is enabled, or else update_frame will not
2953 redraw them. (Rows that are identical to what is already on
2954 screen will not be redrawn anyway.) */
2955 to->enabled_p = true;
2956 to->hash = from->hash;
2959 return saved;
2962 /* Restore the contents of frame F's desired frame matrix from SAVED,
2963 and free memory associated with SAVED. */
2965 static void
2966 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2968 int i;
2970 for (i = 0; i < saved->nrows; ++i)
2972 struct glyph_row *from = saved->rows + i;
2973 struct glyph_row *to = f->desired_matrix->rows + i;
2974 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2976 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2977 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2978 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2979 to->enabled_p = from->enabled_p;
2980 to->hash = from->hash;
2984 static void
2985 free_saved_screen (struct glyph_matrix *saved)
2987 int i;
2989 if (!saved)
2990 return; /* Already freed! */
2992 for (i = 0; i < saved->nrows; ++i)
2994 struct glyph_row *from = saved->rows + i;
2996 xfree (from->glyphs[TEXT_AREA]);
2999 xfree (saved->rows);
3000 xfree (saved);
3003 /* Update the display of frame F from its saved contents. */
3004 static void
3005 screen_update (struct frame *f, struct glyph_matrix *mtx)
3007 restore_desired_matrix (f, mtx);
3008 update_frame_with_menu (f, -1, -1);
3011 typedef enum {
3012 MI_QUIT_MENU = -1,
3013 MI_CONTINUE = 0,
3014 MI_ITEM_SELECTED = 1,
3015 MI_NEXT_ITEM = 2,
3016 MI_PREV_ITEM = 3,
3017 MI_SCROLL_FORWARD = 4,
3018 MI_SCROLL_BACK = 5
3019 } mi_result;
3021 /* Read user input and return X and Y coordinates where that input
3022 puts us. We only consider mouse movement and click events, and
3023 keyboard movement commands; the rest are ignored. */
3024 static mi_result
3025 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3026 bool *first_time)
3028 if (*first_time)
3030 *first_time = false;
3031 sf->mouse_moved = 1;
3033 else
3035 Lisp_Object cmd;
3036 bool usable_input = 1;
3037 mi_result st = MI_CONTINUE;
3038 struct tty_display_info *tty = FRAME_TTY (sf);
3039 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3041 /* Signal the keyboard reading routines we are displaying a menu
3042 on this terminal. */
3043 tty->showing_menu = 1;
3044 /* We want mouse movements be reported by read_menu_command. */
3045 do_mouse_tracking = Qt;
3046 do {
3047 cmd = read_menu_command ();
3048 } while (NILP (cmd));
3049 tty->showing_menu = 0;
3050 do_mouse_tracking = saved_mouse_tracking;
3052 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3053 /* If some input switched frames under our feet, exit the
3054 menu, since the menu faces are no longer valid, and the
3055 menu is no longer relevant anyway. */
3056 || sf != SELECTED_FRAME ())
3057 return MI_QUIT_MENU;
3058 if (EQ (cmd, Qtty_menu_mouse_movement))
3059 mouse_get_xy (x, y);
3060 else if (EQ (cmd, Qtty_menu_next_menu))
3062 usable_input = 0;
3063 st = MI_NEXT_ITEM;
3065 else if (EQ (cmd, Qtty_menu_prev_menu))
3067 usable_input = 0;
3068 st = MI_PREV_ITEM;
3070 else if (EQ (cmd, Qtty_menu_next_item))
3072 if (*y < max_y)
3073 *y += 1;
3074 else
3075 st = MI_SCROLL_FORWARD;
3077 else if (EQ (cmd, Qtty_menu_prev_item))
3079 if (*y > min_y)
3080 *y -= 1;
3081 else
3082 st = MI_SCROLL_BACK;
3084 else if (EQ (cmd, Qtty_menu_select))
3085 st = MI_ITEM_SELECTED;
3086 else if (!EQ (cmd, Qtty_menu_ignore))
3087 usable_input = 0;
3088 if (usable_input)
3089 sf->mouse_moved = 1;
3090 return st;
3092 return MI_CONTINUE;
3095 /* Display menu, wait for user's response, and return that response. */
3096 static int
3097 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3098 int x0, int y0, char **txt,
3099 void (*help_callback)(char const *, int, int),
3100 bool kbd_navigation)
3102 struct tty_menu_state *state;
3103 int statecount, x, y, i;
3104 bool leave, onepane;
3105 int result UNINIT;
3106 int title_faces[4]; /* Face to display the menu title. */
3107 int faces[4], buffers_num_deleted = 0;
3108 struct frame *sf = SELECTED_FRAME ();
3109 struct tty_display_info *tty = FRAME_TTY (sf);
3110 bool first_time;
3111 Lisp_Object selectface;
3112 int first_item = 0;
3113 int col, row;
3114 Lisp_Object prev_inhibit_redisplay = Vinhibit_redisplay;
3115 USE_SAFE_ALLOCA;
3117 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3118 around the display. */
3119 if (x0 <= 0)
3120 x0 = 1;
3121 if (y0 <= 0)
3122 y0 = 1;
3124 SAFE_NALLOCA (state, 1, menu->panecount);
3125 memset (state, 0, sizeof (*state));
3126 faces[0]
3127 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3128 DEFAULT_FACE_ID, 1);
3129 faces[1]
3130 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3131 DEFAULT_FACE_ID, 1);
3132 selectface = intern ("tty-menu-selected-face");
3133 faces[2] = lookup_derived_face (sf, selectface,
3134 faces[0], 1);
3135 faces[3] = lookup_derived_face (sf, selectface,
3136 faces[1], 1);
3138 /* Make sure the menu title is always displayed with
3139 `tty-menu-selected-face', no matter where the mouse pointer is. */
3140 for (i = 0; i < 4; i++)
3141 title_faces[i] = faces[3];
3143 statecount = 1;
3145 /* Don't let the title for the "Buffers" popup menu include a
3146 digit (which is ugly).
3148 This is a terrible kludge, but I think the "Buffers" case is
3149 the only one where the title includes a number, so it doesn't
3150 seem to be necessary to make this more general. */
3151 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3153 menu->text[0][7] = '\0';
3154 buffers_num_deleted = 1;
3157 /* Inhibit redisplay for as long as the menu is active, to avoid
3158 messing the screen if some timer calls sit-for or a similar
3159 function. */
3160 Vinhibit_redisplay = Qt;
3162 /* Force update of the current frame, so that the desired and the
3163 current matrices are identical. */
3164 update_frame_with_menu (sf, -1, -1);
3165 state[0].menu = menu;
3166 state[0].screen_behind = save_and_enable_current_matrix (sf);
3168 /* Display the menu title. We subtract 1 from x0 and y0 because we
3169 want to interpret them as zero-based column and row coordinates,
3170 and also because we want the first item of the menu, not its
3171 title, to appear at x0,y0. */
3172 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3174 /* Turn off the cursor. Otherwise it shows through the menu
3175 panes, which is ugly. */
3176 col = cursorX (tty);
3177 row = cursorY (tty);
3178 tty_hide_cursor (tty);
3180 if (buffers_num_deleted)
3181 menu->text[0][7] = ' ';
3182 onepane = menu->count == 1 && menu->submenu[0];
3183 if (onepane)
3185 menu->width = menu->submenu[0]->width;
3186 state[0].menu = menu->submenu[0];
3188 else
3190 state[0].menu = menu;
3192 state[0].x = x0 - 1;
3193 state[0].y = y0;
3194 state[0].pane = onepane;
3196 x = state[0].x;
3197 y = state[0].y;
3198 first_time = true;
3200 leave = 0;
3201 while (!leave)
3203 mi_result input_status;
3204 int min_y = state[0].y;
3205 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3207 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3208 if (input_status)
3210 leave = 1;
3211 switch (input_status)
3213 case MI_QUIT_MENU:
3214 /* Remove the last help-echo, so that it doesn't
3215 re-appear after "Quit". */
3216 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3217 result = TTYM_NO_SELECT;
3218 break;
3219 case MI_NEXT_ITEM:
3220 if (kbd_navigation)
3221 result = TTYM_NEXT;
3222 else
3223 leave = 0;
3224 break;
3225 case MI_PREV_ITEM:
3226 if (kbd_navigation)
3227 result = TTYM_PREV;
3228 else
3229 leave = 0;
3230 break;
3231 case MI_SCROLL_FORWARD:
3232 if (y - min_y == state[0].menu->count - 1 - first_item)
3234 y = min_y;
3235 first_item = 0;
3237 else
3238 first_item++;
3239 leave = 0;
3240 break;
3241 case MI_SCROLL_BACK:
3242 if (first_item == 0)
3244 y = max_y;
3245 first_item = state[0].menu->count - 1 - (y - min_y);
3247 else
3248 first_item--;
3249 leave = 0;
3250 break;
3251 default:
3252 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3253 break;
3256 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3258 sf->mouse_moved = 0;
3259 result = TTYM_IA_SELECT;
3260 for (i = 0; i < statecount; i++)
3261 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3263 int dy = y - state[i].y + first_item;
3264 if (0 <= dy && dy < state[i].menu->count)
3266 if (!state[i].menu->submenu[dy])
3268 if (state[i].menu->panenumber[dy])
3269 result = TTYM_SUCCESS;
3270 else
3271 result = TTYM_IA_SELECT;
3273 *pane = state[i].pane - 1;
3274 *selidx = dy;
3275 /* We hit some part of a menu, so drop extra menus that
3276 have been opened. That does not include an open and
3277 active submenu. */
3278 if (i != statecount - 2
3279 || state[i].menu->submenu[dy] != state[i + 1].menu)
3280 while (i != statecount - 1)
3282 statecount--;
3283 screen_update (sf, state[statecount].screen_behind);
3284 state[statecount].screen_behind = NULL;
3286 if (i == statecount - 1 && state[i].menu->submenu[dy])
3288 tty_menu_display (state[i].menu,
3289 state[i].x,
3290 state[i].y,
3291 state[i].pane,
3292 faces, x, y, first_item, 1);
3293 state[statecount].menu = state[i].menu->submenu[dy];
3294 state[statecount].pane = state[i].menu->panenumber[dy];
3295 state[statecount].screen_behind
3296 = save_and_enable_current_matrix (sf);
3297 state[statecount].x
3298 = state[i].x + state[i].menu->width + 2;
3299 state[statecount].y = y;
3300 statecount++;
3304 tty_menu_display (state[statecount - 1].menu,
3305 state[statecount - 1].x,
3306 state[statecount - 1].y,
3307 state[statecount - 1].pane,
3308 faces, x, y, first_item, 1);
3309 /* The call to display help-echo below will move the cursor,
3310 so remember its current position as computed by
3311 tty_menu_display. */
3312 col = cursorX (tty);
3313 row = cursorY (tty);
3316 /* Display the help-echo message for the currently-selected menu
3317 item. */
3318 if ((menu_help_message || prev_menu_help_message)
3319 && menu_help_message != prev_menu_help_message)
3321 help_callback (menu_help_message,
3322 menu_help_paneno, menu_help_itemno);
3323 /* Move the cursor to the beginning of the current menu
3324 item, so that screen readers and other accessibility aids
3325 know where the active region is. */
3326 cursor_to (sf, row, col);
3327 prev_menu_help_message = menu_help_message;
3329 /* Both tty_menu_display and help_callback invoke update_end,
3330 which calls tty_show_cursor. Re-hide it, so it doesn't show
3331 through the menus. */
3332 tty_hide_cursor (tty);
3333 fflush (tty->output);
3336 sf->mouse_moved = 0;
3337 screen_update (sf, state[0].screen_behind);
3338 while (statecount--)
3339 free_saved_screen (state[statecount].screen_behind);
3340 tty_show_cursor (tty); /* Turn cursor back on. */
3341 fflush (tty->output);
3343 /* Clean up any mouse events that are waiting inside Emacs event queue.
3344 These events are likely to be generated before the menu was even
3345 displayed, probably because the user pressed and released the button
3346 (which invoked the menu) too quickly. If we don't remove these events,
3347 Emacs will process them after we return and surprise the user. */
3348 discard_mouse_events ();
3349 if (!kbd_buffer_events_waiting ())
3350 clear_input_pending ();
3351 SAFE_FREE ();
3352 Vinhibit_redisplay = prev_inhibit_redisplay;
3353 return result;
3356 /* Dispose of a menu. */
3358 static void
3359 tty_menu_destroy (tty_menu *menu)
3361 int i;
3362 if (menu->allocated)
3364 for (i = 0; i < menu->count; i++)
3365 if (menu->submenu[i])
3366 tty_menu_destroy (menu->submenu[i]);
3367 xfree (menu->text);
3368 xfree (menu->submenu);
3369 xfree (menu->panenumber);
3370 xfree (menu->help_text);
3372 xfree (menu);
3373 menu_help_message = prev_menu_help_message = NULL;
3376 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3378 PANE is the pane number, and ITEM is the menu item number in
3379 the menu (currently not used). */
3381 static void
3382 tty_menu_help_callback (char const *help_string, int pane, int item)
3384 Lisp_Object *first_item;
3385 Lisp_Object pane_name;
3386 Lisp_Object menu_object;
3388 first_item = XVECTOR (menu_items)->contents;
3389 if (EQ (first_item[0], Qt))
3390 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3391 else if (EQ (first_item[0], Qquote))
3392 /* This shouldn't happen, see xmenu_show. */
3393 pane_name = empty_unibyte_string;
3394 else
3395 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3397 /* (menu-item MENU-NAME PANE-NUMBER) */
3398 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3399 show_help_echo (help_string ? build_string (help_string) : Qnil,
3400 Qnil, menu_object, make_number (item));
3403 static void
3404 tty_pop_down_menu (Lisp_Object arg)
3406 tty_menu *menu = XSAVE_POINTER (arg, 0);
3407 struct buffer *orig_buffer = XSAVE_POINTER (arg, 1);
3409 block_input ();
3410 tty_menu_destroy (menu);
3411 set_buffer_internal (orig_buffer);
3412 unblock_input ();
3415 /* Return the zero-based index of the last menu-bar item on frame F. */
3416 static int
3417 tty_menu_last_menubar_item (struct frame *f)
3419 int i = 0;
3421 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3422 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3424 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3426 while (i < ASIZE (items))
3428 Lisp_Object str;
3430 str = AREF (items, i + 1);
3431 if (NILP (str))
3432 break;
3433 i += 4;
3435 i -= 4; /* Went one too far! */
3437 return i;
3440 /* Find in frame F's menu bar the menu item that is next or previous
3441 to the item at X/Y, and return that item's position in X/Y. WHICH
3442 says which one--next or previous--item to look for. X and Y are
3443 measured in character cells. This should only be called on TTY
3444 frames. */
3445 static void
3446 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3448 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3449 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3451 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3452 int last_i = tty_menu_last_menubar_item (f);
3453 int i, prev_x;
3455 /* This loop assumes a single menu-bar line, and will fail to
3456 find an item if it is not in the first line. Note that
3457 make_lispy_event in keyboard.c makes the same assumption. */
3458 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3460 Lisp_Object pos, str;
3461 int ix;
3463 str = AREF (items, i + 1);
3464 pos = AREF (items, i + 3);
3465 if (NILP (str))
3466 return;
3467 ix = XINT (pos);
3468 if (ix <= *x
3469 /* We use <= so the blank between 2 items on a TTY is
3470 considered part of the previous item. */
3471 && *x <= ix + menu_item_width (SDATA (str)))
3473 /* Found current item. Now compute the X coordinate of
3474 the previous or next item. */
3475 if (which == TTYM_NEXT)
3477 if (i < last_i)
3478 *x = XINT (AREF (items, i + 4 + 3));
3479 else
3480 *x = 0; /* Wrap around to the first item. */
3482 else if (prev_x < 0)
3484 /* Wrap around to the last item. */
3485 *x = XINT (AREF (items, last_i + 3));
3487 else
3488 *x = prev_x;
3489 return;
3491 prev_x = ix;
3496 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3497 Lisp_Object
3498 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3499 Lisp_Object title, const char **error_name)
3501 tty_menu *menu;
3502 int pane, selidx, lpane, status;
3503 Lisp_Object entry, pane_prefix;
3504 char *datap;
3505 int ulx, uly, width, height;
3506 int item_x, item_y;
3507 int dispwidth, dispheight;
3508 int i, j, lines, maxlines;
3509 int maxwidth;
3510 ptrdiff_t specpdl_count;
3512 eassert (FRAME_TERMCAP_P (f));
3514 *error_name = 0;
3515 if (menu_items_n_panes == 0)
3516 return Qnil;
3518 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3520 *error_name = "Empty menu";
3521 return Qnil;
3524 /* Make the menu on that window. */
3525 menu = tty_menu_create ();
3527 /* Don't GC while we prepare and show the menu, because we give the
3528 menu functions pointers to the contents of strings. */
3529 specpdl_count = inhibit_garbage_collection ();
3531 /* Avoid crashes if, e.g., another client will connect while we
3532 are in a menu. */
3533 temporarily_switch_to_single_kboard (f);
3535 /* Adjust coordinates to be root-window-relative. */
3536 item_x = x += f->left_pos;
3537 item_y = y += f->top_pos;
3539 /* Create all the necessary panes and their items. */
3540 USE_SAFE_ALLOCA;
3541 maxwidth = maxlines = lines = i = 0;
3542 lpane = TTYM_FAILURE;
3543 while (i < menu_items_used)
3545 if (EQ (AREF (menu_items, i), Qt))
3547 /* Create a new pane. */
3548 Lisp_Object pane_name, prefix;
3549 const char *pane_string;
3551 maxlines = max (maxlines, lines);
3552 lines = 0;
3553 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3554 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3555 pane_string = (NILP (pane_name)
3556 ? "" : SSDATA (pane_name));
3557 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3558 pane_string++;
3560 lpane = tty_menu_add_pane (menu, pane_string);
3561 if (lpane == TTYM_FAILURE)
3563 tty_menu_destroy (menu);
3564 *error_name = "Can't create pane";
3565 entry = Qnil;
3566 goto tty_menu_end;
3568 i += MENU_ITEMS_PANE_LENGTH;
3570 /* Find the width of the widest item in this pane. */
3571 j = i;
3572 while (j < menu_items_used)
3574 Lisp_Object item;
3575 item = AREF (menu_items, j);
3576 if (EQ (item, Qt))
3577 break;
3578 if (NILP (item))
3580 j++;
3581 continue;
3583 width = SBYTES (item);
3584 if (width > maxwidth)
3585 maxwidth = width;
3587 j += MENU_ITEMS_ITEM_LENGTH;
3590 /* Ignore a nil in the item list.
3591 It's meaningful only for dialog boxes. */
3592 else if (EQ (AREF (menu_items, i), Qquote))
3593 i += 1;
3594 else
3596 /* Create a new item within current pane. */
3597 Lisp_Object item_name, enable, descrip, help;
3598 char *item_data;
3599 char const *help_string;
3601 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3602 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3603 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3604 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3605 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3607 if (!NILP (descrip))
3609 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3610 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3611 for (j = SCHARS (item_name); j < maxwidth; j++)
3612 item_data[j] = ' ';
3613 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3614 item_data[j + SBYTES (descrip)] = 0;
3616 else
3617 item_data = SSDATA (item_name);
3619 if (lpane == TTYM_FAILURE
3620 || (! tty_menu_add_selection (menu, lpane, item_data,
3621 !NILP (enable), help_string)))
3623 tty_menu_destroy (menu);
3624 *error_name = "Can't add selection to menu";
3625 entry = Qnil;
3626 goto tty_menu_end;
3628 i += MENU_ITEMS_ITEM_LENGTH;
3629 lines++;
3633 maxlines = max (maxlines, lines);
3635 /* All set and ready to fly. */
3636 dispwidth = f->text_cols;
3637 dispheight = f->text_lines;
3638 x = min (x, dispwidth);
3639 y = min (y, dispheight);
3640 x = max (x, 1);
3641 y = max (y, 1);
3642 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3643 if (ulx + width > dispwidth)
3645 x -= (ulx + width) - dispwidth;
3646 ulx = dispwidth - width;
3648 if (uly + height > dispheight)
3650 y -= (uly + height) - dispheight;
3651 uly = dispheight - height;
3654 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3656 /* Move the menu away of the echo area, to avoid overwriting the
3657 menu with help echo messages or vice versa. */
3658 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3660 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3661 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3663 else
3665 y -= 2;
3666 uly -= 2;
3670 if (ulx < 0) x -= ulx;
3671 if (uly < 0) y -= uly;
3673 #if 0
3674 /* This code doesn't make sense on a TTY, since it can easily annul
3675 the adjustments above that carefully avoid truncation of the menu
3676 items. I think it was written to fix some problem that only
3677 happens on X11. */
3678 if (! for_click)
3680 /* If position was not given by a mouse click, adjust so upper left
3681 corner of the menu as a whole ends up at given coordinates. This
3682 is what x-popup-menu says in its documentation. */
3683 x += width / 2;
3684 y += 1.5 * height / (maxlines + 2);
3686 #endif
3688 pane = selidx = 0;
3690 /* We save and restore the current buffer because tty_menu_activate
3691 triggers redisplay, which switches buffers at will. */
3692 record_unwind_protect (tty_pop_down_menu,
3693 make_save_ptr_ptr (menu, current_buffer));
3695 specbind (Qoverriding_terminal_local_map,
3696 Fsymbol_value (Qtty_menu_navigation_map));
3697 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3698 tty_menu_help_callback,
3699 menuflags & MENU_KBD_NAVIGATION);
3700 entry = pane_prefix = Qnil;
3702 switch (status)
3704 case TTYM_SUCCESS:
3705 /* Find the item number SELIDX in pane number PANE. */
3706 i = 0;
3707 while (i < menu_items_used)
3709 if (EQ (AREF (menu_items, i), Qt))
3711 if (pane == 0)
3712 pane_prefix
3713 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3714 pane--;
3715 i += MENU_ITEMS_PANE_LENGTH;
3717 else
3719 if (pane == -1)
3721 if (selidx == 0)
3723 entry
3724 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3725 if (menuflags & MENU_KEYMAPS)
3727 entry = Fcons (entry, Qnil);
3728 if (!NILP (pane_prefix))
3729 entry = Fcons (pane_prefix, entry);
3731 break;
3733 selidx--;
3735 i += MENU_ITEMS_ITEM_LENGTH;
3738 break;
3740 case TTYM_NEXT:
3741 case TTYM_PREV:
3742 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3743 entry = Fcons (make_number (item_x), make_number (item_y));
3744 break;
3746 case TTYM_FAILURE:
3747 *error_name = "Can't activate menu";
3748 case TTYM_IA_SELECT:
3749 break;
3750 case TTYM_NO_SELECT:
3751 /* If the selected frame was changed while we displayed a menu,
3752 throw to top level in order to undo any temporary settings
3753 made by TTY menu code. */
3754 if (f != SELECTED_FRAME ())
3755 Ftop_level ();
3756 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3757 the menu was invoked with a mouse event as POSITION). */
3758 if (!(menuflags & MENU_FOR_CLICK))
3759 quit ();
3760 break;
3763 tty_menu_end:
3765 SAFE_FREE ();
3766 unbind_to (specpdl_count, Qnil);
3767 return entry;
3770 #endif /* !MSDOS */
3773 #ifndef MSDOS
3774 /***********************************************************************
3775 Initialization
3776 ***********************************************************************/
3778 /* Initialize the tty-dependent part of frame F. The frame must
3779 already have its device initialized. */
3781 void
3782 create_tty_output (struct frame *f)
3784 struct tty_output *t = xzalloc (sizeof *t);
3786 eassert (FRAME_TERMCAP_P (f));
3788 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3790 f->output_data.tty = t;
3793 /* Delete frame F's face cache, and its tty-dependent part. */
3795 static void
3796 tty_free_frame_resources (struct frame *f)
3798 eassert (FRAME_TERMCAP_P (f));
3799 free_frame_faces (f);
3800 xfree (f->output_data.tty);
3803 #else /* MSDOS */
3805 /* Delete frame F's face cache. */
3807 static void
3808 tty_free_frame_resources (struct frame *f)
3810 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3811 free_frame_faces (f);
3813 #endif /* MSDOS */
3815 /* Reset the hooks in TERMINAL. */
3817 static void
3818 clear_tty_hooks (struct terminal *terminal)
3820 terminal->rif = 0;
3821 terminal->cursor_to_hook = 0;
3822 terminal->raw_cursor_to_hook = 0;
3823 terminal->clear_to_end_hook = 0;
3824 terminal->clear_frame_hook = 0;
3825 terminal->clear_end_of_line_hook = 0;
3826 terminal->ins_del_lines_hook = 0;
3827 terminal->insert_glyphs_hook = 0;
3828 terminal->write_glyphs_hook = 0;
3829 terminal->delete_glyphs_hook = 0;
3830 terminal->ring_bell_hook = 0;
3831 terminal->reset_terminal_modes_hook = 0;
3832 terminal->set_terminal_modes_hook = 0;
3833 terminal->update_begin_hook = 0;
3834 terminal->update_end_hook = 0;
3835 terminal->set_terminal_window_hook = 0;
3836 terminal->mouse_position_hook = 0;
3837 terminal->frame_rehighlight_hook = 0;
3838 terminal->frame_raise_lower_hook = 0;
3839 terminal->fullscreen_hook = 0;
3840 terminal->menu_show_hook = 0;
3841 terminal->set_vertical_scroll_bar_hook = 0;
3842 terminal->set_horizontal_scroll_bar_hook = 0;
3843 terminal->condemn_scroll_bars_hook = 0;
3844 terminal->redeem_scroll_bar_hook = 0;
3845 terminal->judge_scroll_bars_hook = 0;
3846 terminal->read_socket_hook = 0;
3847 terminal->frame_up_to_date_hook = 0;
3849 /* Leave these two set, or suspended frames are not deleted
3850 correctly. */
3851 terminal->delete_frame_hook = &tty_free_frame_resources;
3852 terminal->delete_terminal_hook = &delete_tty;
3855 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3857 static void
3858 set_tty_hooks (struct terminal *terminal)
3860 terminal->cursor_to_hook = &tty_cursor_to;
3861 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3862 terminal->clear_to_end_hook = &tty_clear_to_end;
3863 terminal->clear_frame_hook = &tty_clear_frame;
3864 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3865 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3866 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3867 terminal->write_glyphs_hook = &tty_write_glyphs;
3868 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3869 terminal->ring_bell_hook = &tty_ring_bell;
3870 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3871 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3872 terminal->update_end_hook = &tty_update_end;
3873 #ifdef MSDOS
3874 terminal->menu_show_hook = &x_menu_show;
3875 #else
3876 terminal->menu_show_hook = &tty_menu_show;
3877 #endif
3878 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3879 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3880 terminal->delete_frame_hook = &tty_free_frame_resources;
3881 terminal->delete_terminal_hook = &delete_tty;
3882 /* Other hooks are NULL by default. */
3885 /* If FD is the controlling terminal, drop it. */
3886 static void
3887 dissociate_if_controlling_tty (int fd)
3889 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3890 so dissociate it by invoking setsid. */
3891 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3893 #ifdef TIOCNOTTY
3894 /* setsid failed, presumably because Emacs is already a process
3895 group leader. Fall back on the obsolescent way to dissociate
3896 a controlling tty. */
3897 sigset_t oldset;
3898 block_tty_out_signal (&oldset);
3899 ioctl (fd, TIOCNOTTY, 0);
3900 unblock_tty_out_signal (&oldset);
3901 #endif
3905 /* Create a termcap display on the tty device with the given name and
3906 type.
3908 If NAME is NULL, then use the controlling tty, i.e., DEV_TTY.
3909 Otherwise NAME should be a path to the tty device file,
3910 e.g. "/dev/pts/7".
3912 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3914 If MUST_SUCCEED is true, then all errors are fatal. */
3916 struct terminal *
3917 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3919 struct tty_display_info *tty = NULL;
3920 struct terminal *terminal = NULL;
3921 #ifndef DOS_NT
3922 char *area;
3923 char **address = &area;
3924 int status;
3925 sigset_t oldset;
3926 bool ctty = false; /* True if asked to open controlling tty. */
3927 #endif
3929 if (!terminal_type)
3930 maybe_fatal (must_succeed, 0,
3931 "Unknown terminal type",
3932 "Unknown terminal type");
3934 if (name == NULL)
3935 name = DEV_TTY;
3936 #ifndef DOS_NT
3937 if (!strcmp (name, DEV_TTY))
3938 ctty = 1;
3939 #endif
3941 /* If we already have a terminal on the given device, use that. If
3942 all such terminals are suspended, create a new one instead. */
3943 /* XXX Perhaps this should be made explicit by having init_tty
3944 always create a new terminal and separating terminal and frame
3945 creation on Lisp level. */
3946 terminal = get_named_terminal (name);
3947 if (terminal)
3948 return terminal;
3950 terminal = create_terminal (output_termcap, NULL);
3951 #ifdef MSDOS
3952 if (been_here > 0)
3953 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3954 name, "");
3955 been_here = 1;
3956 tty = &the_only_display_info;
3957 #else
3958 tty = xzalloc (sizeof *tty);
3959 #endif
3960 tty->top_frame = Qnil;
3961 tty->next = tty_list;
3962 tty_list = tty;
3964 terminal->display_info.tty = tty;
3965 tty->terminal = terminal;
3967 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3968 Wcm_clear (tty);
3970 encode_terminal_src_size = 0;
3971 encode_terminal_dst_size = 0;
3974 #ifndef DOS_NT
3975 set_tty_hooks (terminal);
3978 /* Open the terminal device. */
3980 /* If !ctty, don't recognize it as our controlling terminal, and
3981 don't make it the controlling tty if we don't have one now.
3983 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3984 defined on Hurd. On other systems, we need to explicitly
3985 dissociate ourselves from the controlling tty when we want to
3986 open a frame on the same terminal. */
3987 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3988 int fd = emacs_open (name, flags, 0);
3989 tty->input = tty->output
3990 = ((fd < 0 || ! isatty (fd))
3991 ? NULL
3992 : fdopen (fd, "w+"));
3994 if (! tty->input)
3996 char const *diagnostic
3997 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3998 emacs_close (fd);
3999 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4002 tty->name = xstrdup (name);
4003 terminal->name = xstrdup (name);
4005 if (!O_IGNORE_CTTY && !ctty)
4006 dissociate_if_controlling_tty (fd);
4009 tty->type = xstrdup (terminal_type);
4011 add_keyboard_wait_descriptor (fileno (tty->input));
4013 Wcm_clear (tty);
4015 /* On some systems, tgetent tries to access the controlling
4016 terminal. */
4017 block_tty_out_signal (&oldset);
4018 status = tgetent (tty->termcap_term_buffer, terminal_type);
4019 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4020 emacs_abort ();
4021 unblock_tty_out_signal (&oldset);
4023 if (status < 0)
4025 #ifdef TERMINFO
4026 maybe_fatal (must_succeed, terminal,
4027 "Cannot open terminfo database file",
4028 "Cannot open terminfo database file");
4029 #else
4030 maybe_fatal (must_succeed, terminal,
4031 "Cannot open termcap database file",
4032 "Cannot open termcap database file");
4033 #endif
4035 if (status == 0)
4037 maybe_fatal (must_succeed, terminal,
4038 "Terminal type %s is not defined",
4039 "Terminal type %s is not defined.\n\
4040 If that is not the actual type of terminal you have,\n\
4041 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4042 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4043 #ifdef TERMINFO
4044 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4045 #else
4046 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4047 #endif
4048 terminal_type);
4051 area = tty->termcap_strings_buffer;
4052 tty->TS_ins_line = tgetstr ("al", address);
4053 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4054 tty->TS_bell = tgetstr ("bl", address);
4055 BackTab (tty) = tgetstr ("bt", address);
4056 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4057 tty->TS_clr_line = tgetstr ("ce", address);
4058 tty->TS_clr_frame = tgetstr ("cl", address);
4059 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4060 AbsPosition (tty) = tgetstr ("cm", address);
4061 CR (tty) = tgetstr ("cr", address);
4062 tty->TS_set_scroll_region = tgetstr ("cs", address);
4063 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4064 RowPosition (tty) = tgetstr ("cv", address);
4065 tty->TS_del_char = tgetstr ("dc", address);
4066 tty->TS_del_multi_chars = tgetstr ("DC", address);
4067 tty->TS_del_line = tgetstr ("dl", address);
4068 tty->TS_del_multi_lines = tgetstr ("DL", address);
4069 tty->TS_delete_mode = tgetstr ("dm", address);
4070 tty->TS_end_delete_mode = tgetstr ("ed", address);
4071 tty->TS_end_insert_mode = tgetstr ("ei", address);
4072 Home (tty) = tgetstr ("ho", address);
4073 tty->TS_ins_char = tgetstr ("ic", address);
4074 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4075 tty->TS_insert_mode = tgetstr ("im", address);
4076 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4077 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4078 tty->TS_keypad_mode = tgetstr ("ks", address);
4079 LastLine (tty) = tgetstr ("ll", address);
4080 Right (tty) = tgetstr ("nd", address);
4081 Down (tty) = tgetstr ("do", address);
4082 if (!Down (tty))
4083 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4084 if (tgetflag ("bs"))
4085 Left (tty) = "\b"; /* Can't possibly be longer! */
4086 else /* (Actually, "bs" is obsolete...) */
4087 Left (tty) = tgetstr ("le", address);
4088 if (!Left (tty))
4089 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4090 tty->TS_pad_char = tgetstr ("pc", address);
4091 tty->TS_repeat = tgetstr ("rp", address);
4092 tty->TS_end_standout_mode = tgetstr ("se", address);
4093 tty->TS_fwd_scroll = tgetstr ("sf", address);
4094 tty->TS_standout_mode = tgetstr ("so", address);
4095 tty->TS_rev_scroll = tgetstr ("sr", address);
4096 tty->Wcm->cm_tab = tgetstr ("ta", address);
4097 tty->TS_end_termcap_modes = tgetstr ("te", address);
4098 tty->TS_termcap_modes = tgetstr ("ti", address);
4099 Up (tty) = tgetstr ("up", address);
4100 tty->TS_visible_bell = tgetstr ("vb", address);
4101 tty->TS_cursor_normal = tgetstr ("ve", address);
4102 tty->TS_cursor_visible = tgetstr ("vs", address);
4103 tty->TS_cursor_invisible = tgetstr ("vi", address);
4104 tty->TS_set_window = tgetstr ("wi", address);
4106 tty->TS_enter_underline_mode = tgetstr ("us", address);
4107 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4108 tty->TS_enter_bold_mode = tgetstr ("md", address);
4109 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4110 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4111 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4112 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4113 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4114 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4116 MultiUp (tty) = tgetstr ("UP", address);
4117 MultiDown (tty) = tgetstr ("DO", address);
4118 MultiLeft (tty) = tgetstr ("LE", address);
4119 MultiRight (tty) = tgetstr ("RI", address);
4121 /* SVr4/ANSI color support. If "op" isn't available, don't support
4122 color because we can't switch back to the default foreground and
4123 background. */
4124 tty->TS_orig_pair = tgetstr ("op", address);
4125 if (tty->TS_orig_pair)
4127 tty->TS_set_foreground = tgetstr ("AF", address);
4128 tty->TS_set_background = tgetstr ("AB", address);
4129 if (!tty->TS_set_foreground)
4131 /* SVr4. */
4132 tty->TS_set_foreground = tgetstr ("Sf", address);
4133 tty->TS_set_background = tgetstr ("Sb", address);
4136 tty->TN_max_colors = tgetnum ("Co");
4137 tty->TN_max_pairs = tgetnum ("pa");
4139 tty->TN_no_color_video = tgetnum ("NC");
4140 if (tty->TN_no_color_video == -1)
4141 tty->TN_no_color_video = 0;
4144 tty_default_color_capabilities (tty, 1);
4146 MagicWrap (tty) = tgetflag ("xn");
4147 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4148 the former flag imply the latter. */
4149 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4150 tty->memory_below_frame = tgetflag ("db");
4151 tty->TF_hazeltine = tgetflag ("hz");
4152 tty->must_write_spaces = tgetflag ("in");
4153 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4154 tty->TF_insmode_motion = tgetflag ("mi");
4155 tty->TF_standout_motion = tgetflag ("ms");
4156 tty->TF_underscore = tgetflag ("ul");
4157 tty->TF_teleray = tgetflag ("xt");
4159 #else /* DOS_NT */
4160 #ifdef WINDOWSNT
4162 struct frame *f = XFRAME (selected_frame);
4163 int height, width;
4165 initialize_w32_display (terminal, &width, &height);
4167 FrameRows (tty) = height;
4168 FrameCols (tty) = width;
4169 tty->specified_window = height;
4171 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4172 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4173 tty->char_ins_del_ok = 1;
4174 baud_rate = 19200;
4176 #else /* MSDOS */
4178 int height, width;
4179 if (strcmp (terminal_type, "internal") == 0)
4180 terminal->type = output_msdos_raw;
4181 initialize_msdos_display (terminal);
4183 get_tty_size (fileno (tty->input), &width, &height);
4184 FrameCols (tty) = width;
4185 FrameRows (tty) = height;
4186 tty->char_ins_del_ok = 0;
4187 init_baud_rate (fileno (tty->input));
4189 #endif /* MSDOS */
4190 tty->output = stdout;
4191 tty->input = stdin;
4192 /* The following two are inaccessible from w32console.c. */
4193 terminal->delete_frame_hook = &tty_free_frame_resources;
4194 terminal->delete_terminal_hook = &delete_tty;
4196 tty->name = xstrdup (name);
4197 terminal->name = xstrdup (name);
4198 tty->type = xstrdup (terminal_type);
4200 add_keyboard_wait_descriptor (0);
4202 tty->delete_in_insert_mode = 1;
4204 UseTabs (tty) = 0;
4205 tty->scroll_region_ok = 0;
4207 /* Seems to insert lines when it's not supposed to, messing up the
4208 display. In doing a trace, it didn't seem to be called much, so I
4209 don't think we're losing anything by turning it off. */
4210 tty->line_ins_del_ok = 0;
4212 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4213 #endif /* DOS_NT */
4215 #ifdef HAVE_GPM
4216 terminal->mouse_position_hook = term_mouse_position;
4217 tty->mouse_highlight.mouse_face_window = Qnil;
4218 #endif
4220 terminal->kboard = allocate_kboard (Qnil);
4221 terminal->kboard->reference_count++;
4222 /* Don't let the initial kboard remain current longer than necessary.
4223 That would cause problems if a file loaded on startup tries to
4224 prompt in the mini-buffer. */
4225 if (current_kboard == initial_kboard)
4226 current_kboard = terminal->kboard;
4227 #ifndef DOS_NT
4228 term_get_fkeys (address, terminal->kboard);
4230 /* Get frame size from system, or else from termcap. */
4232 int height, width;
4233 get_tty_size (fileno (tty->input), &width, &height);
4234 FrameCols (tty) = width;
4235 FrameRows (tty) = height;
4238 if (FrameCols (tty) <= 0)
4239 FrameCols (tty) = tgetnum ("co");
4240 if (FrameRows (tty) <= 0)
4241 FrameRows (tty) = tgetnum ("li");
4243 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4244 maybe_fatal (must_succeed, terminal,
4245 "Screen size %dx%d is too small",
4246 "Screen size %dx%d is too small",
4247 FrameCols (tty), FrameRows (tty));
4249 TabWidth (tty) = tgetnum ("tw");
4251 if (!tty->TS_bell)
4252 tty->TS_bell = "\07";
4254 if (!tty->TS_fwd_scroll)
4255 tty->TS_fwd_scroll = Down (tty);
4257 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4259 if (TabWidth (tty) < 0)
4260 TabWidth (tty) = 8;
4262 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4263 and newer termcap doc does not seem to say there is a default.
4264 if (!tty->Wcm->cm_tab)
4265 tty->Wcm->cm_tab = "\t";
4268 /* We don't support standout modes that use `magic cookies', so
4269 turn off any that do. */
4270 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4272 tty->TS_standout_mode = 0;
4273 tty->TS_end_standout_mode = 0;
4275 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4277 tty->TS_enter_underline_mode = 0;
4278 tty->TS_exit_underline_mode = 0;
4281 /* If there's no standout mode, try to use underlining instead. */
4282 if (tty->TS_standout_mode == 0)
4284 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4285 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4288 /* If no `se' string, try using a `me' string instead.
4289 If that fails, we can't use standout mode at all. */
4290 if (tty->TS_end_standout_mode == 0)
4292 char *s = tgetstr ("me", address);
4293 if (s != 0)
4294 tty->TS_end_standout_mode = s;
4295 else
4296 tty->TS_standout_mode = 0;
4299 if (tty->TF_teleray)
4301 tty->Wcm->cm_tab = 0;
4302 /* We can't support standout mode, because it uses magic cookies. */
4303 tty->TS_standout_mode = 0;
4304 /* But that means we cannot rely on ^M to go to column zero! */
4305 CR (tty) = 0;
4306 /* LF can't be trusted either -- can alter hpos. */
4307 /* If move at column 0 thru a line with TS_standout_mode. */
4308 Down (tty) = 0;
4311 tty->specified_window = FrameRows (tty);
4313 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4315 maybe_fatal (must_succeed, terminal,
4316 "Terminal type \"%s\" is not powerful enough to run Emacs",
4317 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4318 It lacks the ability to position the cursor.\n\
4319 If that is not the actual type of terminal you have,\n\
4320 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4321 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4322 # ifdef TERMINFO
4323 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4324 # else /* TERMCAP */
4325 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4326 # endif /* TERMINFO */
4327 terminal_type);
4330 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4331 maybe_fatal (must_succeed, terminal,
4332 "Could not determine the frame size",
4333 "Could not determine the frame size");
4335 tty->delete_in_insert_mode
4336 = tty->TS_delete_mode && tty->TS_insert_mode
4337 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4339 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4341 tty->scroll_region_ok
4342 = (tty->Wcm->cm_abs
4343 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4345 tty->line_ins_del_ok
4346 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4347 && (tty->TS_del_line || tty->TS_del_multi_lines))
4348 || (tty->scroll_region_ok
4349 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4351 tty->char_ins_del_ok
4352 = ((tty->TS_ins_char || tty->TS_insert_mode
4353 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4354 && (tty->TS_del_char || tty->TS_del_multi_chars));
4356 init_baud_rate (fileno (tty->input));
4358 #endif /* not DOS_NT */
4360 /* Init system terminal modes (RAW or CBREAK, etc.). */
4361 init_sys_modes (tty);
4363 return terminal;
4367 static void
4368 vfatal (const char *str, va_list ap)
4370 fprintf (stderr, "emacs: ");
4371 vfprintf (stderr, str, ap);
4372 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4373 fprintf (stderr, "\n");
4374 fflush (stderr);
4375 exit (1);
4379 /* Auxiliary error-handling function for init_tty.
4380 Delete TERMINAL, then call error or fatal with str1 or str2,
4381 respectively, according to whether MUST_SUCCEED is true. */
4383 static void
4384 maybe_fatal (bool must_succeed, struct terminal *terminal,
4385 const char *str1, const char *str2, ...)
4387 va_list ap;
4388 va_start (ap, str2);
4389 if (terminal)
4390 delete_tty (terminal);
4392 if (must_succeed)
4393 vfatal (str2, ap);
4394 else
4395 verror (str1, ap);
4398 void
4399 fatal (const char *str, ...)
4401 va_list ap;
4402 va_start (ap, str);
4403 vfatal (str, ap);
4408 /* Delete the given tty terminal, closing all frames on it. */
4410 static void
4411 delete_tty (struct terminal *terminal)
4413 struct tty_display_info *tty;
4415 /* Protect against recursive calls. delete_frame in
4416 delete_terminal calls us back when it deletes our last frame. */
4417 if (!terminal->name)
4418 return;
4420 eassert (terminal->type == output_termcap);
4422 tty = terminal->display_info.tty;
4424 if (tty == tty_list)
4425 tty_list = tty->next;
4426 else
4428 struct tty_display_info *p;
4429 for (p = tty_list; p && p->next != tty; p = p->next)
4432 if (! p)
4433 /* This should not happen. */
4434 emacs_abort ();
4436 p->next = tty->next;
4437 tty->next = 0;
4440 /* reset_sys_modes needs a valid device, so this call needs to be
4441 before delete_terminal. */
4442 reset_sys_modes (tty);
4444 delete_terminal (terminal);
4446 xfree (tty->name);
4447 xfree (tty->type);
4449 if (tty->input)
4451 delete_keyboard_wait_descriptor (fileno (tty->input));
4452 if (tty->input != stdin)
4453 fclose (tty->input);
4455 if (tty->output && tty->output != stdout && tty->output != tty->input)
4456 fclose (tty->output);
4457 if (tty->termscript)
4458 fclose (tty->termscript);
4460 xfree (tty->old_tty);
4461 xfree (tty->Wcm);
4462 xfree (tty);
4465 void
4466 syms_of_term (void)
4468 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4469 doc: /* Non-nil means the system uses terminfo rather than termcap.
4470 This variable can be used by terminal emulator packages. */);
4471 #ifdef TERMINFO
4472 system_uses_terminfo = 1;
4473 #else
4474 system_uses_terminfo = 0;
4475 #endif
4477 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4478 doc: /* Functions run after suspending a tty.
4479 The functions are run with one argument, the terminal object to be suspended.
4480 See `suspend-tty'. */);
4481 Vsuspend_tty_functions = Qnil;
4484 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4485 doc: /* Functions run after resuming a tty.
4486 The functions are run with one argument, the terminal object that was revived.
4487 See `resume-tty'. */);
4488 Vresume_tty_functions = Qnil;
4490 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4491 doc: /* Non-nil means to make the cursor very visible.
4492 This only has an effect when running in a text terminal.
4493 What means \"very visible\" is up to your terminal. It may make the cursor
4494 bigger, or it may make it blink, or it may do nothing at all. */);
4495 visible_cursor = 1;
4497 defsubr (&Stty_display_color_p);
4498 defsubr (&Stty_display_color_cells);
4499 defsubr (&Stty_no_underline);
4500 defsubr (&Stty_type);
4501 defsubr (&Scontrolling_tty_p);
4502 defsubr (&Stty_top_frame);
4503 defsubr (&Ssuspend_tty);
4504 defsubr (&Sresume_tty);
4505 #ifdef HAVE_GPM
4506 defsubr (&Sgpm_mouse_start);
4507 defsubr (&Sgpm_mouse_stop);
4508 #endif /* HAVE_GPM */
4510 #ifndef DOS_NT
4511 default_orig_pair = NULL;
4512 default_set_foreground = NULL;
4513 default_set_background = NULL;
4514 #endif /* !DOS_NT */
4516 encode_terminal_src = NULL;
4517 encode_terminal_dst = NULL;
4519 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4520 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4522 #ifndef MSDOS
4523 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4524 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4525 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4526 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4527 DEFSYM (Qtty_menu_select, "tty-menu-select");
4528 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4529 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4530 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4531 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4532 #endif