Make CC Mode load cl-lib rather than cl in Emacs 26.
[emacs.git] / src / term.c
blob3d7f4ada0b9e5bbdefdccc4dfed107ca0d4e8e54
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2017 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 <stdlib.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #include "sysstdio.h"
48 #ifdef MSDOS
49 #include "msdos.h"
50 static int been_here = -1;
51 #endif
53 #ifdef USE_X_TOOLKIT
54 #include "../lwlib/lwlib.h"
55 #endif
57 #include "cm.h"
58 #include "menu.h"
60 /* The name of the default console device. */
61 #ifdef WINDOWSNT
62 #include "w32term.h"
63 #endif
65 static void tty_set_scroll_region (struct frame *f, int start, int stop);
66 static void turn_on_face (struct frame *, int face_id);
67 static void turn_off_face (struct frame *, int face_id);
68 static void tty_turn_off_highlight (struct tty_display_info *);
69 static void tty_show_cursor (struct tty_display_info *);
70 static void tty_hide_cursor (struct tty_display_info *);
71 static void tty_background_highlight (struct tty_display_info *tty);
72 static void clear_tty_hooks (struct terminal *terminal);
73 static void set_tty_hooks (struct terminal *terminal);
74 static void dissociate_if_controlling_tty (int fd);
75 static void delete_tty (struct terminal *);
76 static _Noreturn void maybe_fatal (bool, struct terminal *,
77 const char *, const char *, ...)
78 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
79 static _Noreturn void vfatal (const char *str, va_list ap)
80 ATTRIBUTE_FORMAT_PRINTF (1, 0);
83 #define OUTPUT(tty, a) \
84 emacs_tputs ((tty), a, \
85 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
86 cmputc)
88 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
89 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
91 #define OUTPUT_IF(tty, a) \
92 do { \
93 if (a) \
94 OUTPUT (tty, a); \
95 } while (0)
97 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
99 /* Display space properties. */
101 /* Chain of all tty device parameters. */
102 struct tty_display_info *tty_list;
104 /* Meaning of bits in no_color_video. Each bit set means that the
105 corresponding attribute cannot be combined with colors. */
107 enum no_color_bit
109 NC_STANDOUT = 1 << 0,
110 NC_UNDERLINE = 1 << 1,
111 NC_REVERSE = 1 << 2,
112 NC_ITALIC = 1 << 3,
113 NC_DIM = 1 << 4,
114 NC_BOLD = 1 << 5,
115 NC_INVIS = 1 << 6,
116 NC_PROTECT = 1 << 7
119 /* internal state */
121 /* The largest frame width in any call to calculate_costs. */
123 static int max_frame_cols;
127 #ifdef HAVE_GPM
128 #include <sys/fcntl.h>
130 /* The device for which we have enabled gpm support (or NULL). */
131 struct tty_display_info *gpm_tty = NULL;
133 /* Last recorded mouse coordinates. */
134 static int last_mouse_x, last_mouse_y;
135 #endif /* HAVE_GPM */
137 /* Ring the bell on a tty. */
139 static void
140 tty_ring_bell (struct frame *f)
142 struct tty_display_info *tty = FRAME_TTY (f);
144 if (tty->output)
146 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
147 ? tty->TS_visible_bell
148 : tty->TS_bell));
149 fflush_unlocked (tty->output);
153 /* Set up termcap modes for Emacs. */
155 static void
156 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
158 Lisp_Object lisp_terminal;
159 Lisp_Object extra_codes;
160 struct tty_display_info *tty = terminal->display_info.tty;
162 XSETTERMINAL (lisp_terminal, terminal);
163 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
164 CONSP (extra_codes);
165 extra_codes = XCDR (extra_codes))
167 Lisp_Object string = XCAR (extra_codes);
168 if (STRINGP (string))
170 fwrite_unlocked (SDATA (string), 1, SBYTES (string), tty->output);
171 if (tty->termscript)
172 fwrite_unlocked (SDATA (string), 1, SBYTES (string),
173 tty->termscript);
178 static void
179 tty_set_terminal_modes (struct terminal *terminal)
181 struct tty_display_info *tty = terminal->display_info.tty;
183 if (tty->output)
185 if (tty->TS_termcap_modes)
186 OUTPUT (tty, tty->TS_termcap_modes);
187 else
189 /* Output enough newlines to scroll all the old screen contents
190 off the screen, so it won't be overwritten and lost. */
191 int i;
192 current_tty = tty;
193 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
194 cmputc ('\n');
197 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
198 OUTPUT_IF (tty, tty->TS_keypad_mode);
199 losecursor (tty);
200 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
201 fflush_unlocked (tty->output);
205 /* Reset termcap modes before exiting Emacs. */
207 static void
208 tty_reset_terminal_modes (struct terminal *terminal)
210 struct tty_display_info *tty = terminal->display_info.tty;
212 if (tty->output)
214 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
215 tty_turn_off_highlight (tty);
216 tty_turn_off_insert (tty);
217 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
218 OUTPUT_IF (tty, tty->TS_cursor_normal);
219 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
220 OUTPUT_IF (tty, tty->TS_orig_pair);
221 /* Output raw CR so kernel can track the cursor hpos. */
222 current_tty = tty;
223 cmputc ('\r');
224 fflush_unlocked (tty->output);
228 /* Flag the end of a display update on a termcap terminal. */
230 static void
231 tty_update_end (struct frame *f)
233 struct tty_display_info *tty = FRAME_TTY (f);
235 if (!XWINDOW (selected_window)->cursor_off_p)
236 tty_show_cursor (tty);
237 tty_turn_off_insert (tty);
238 tty_background_highlight (tty);
239 fflush_unlocked (tty->output);
242 /* The implementation of set_terminal_window for termcap frames. */
244 static void
245 tty_set_terminal_window (struct frame *f, int size)
247 struct tty_display_info *tty = FRAME_TTY (f);
249 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
250 if (FRAME_SCROLL_REGION_OK (f))
251 tty_set_scroll_region (f, 0, tty->specified_window);
254 static void
255 tty_set_scroll_region (struct frame *f, int start, int stop)
257 char *buf;
258 struct tty_display_info *tty = FRAME_TTY (f);
260 if (tty->TS_set_scroll_region)
261 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
262 else if (tty->TS_set_scroll_region_1)
263 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
264 FRAME_TOTAL_LINES (f), start,
265 FRAME_TOTAL_LINES (f) - stop,
266 FRAME_TOTAL_LINES (f));
267 else
268 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
270 OUTPUT (tty, buf);
271 xfree (buf);
272 losecursor (tty);
276 static void
277 tty_turn_on_insert (struct tty_display_info *tty)
279 if (!tty->insert_mode)
280 OUTPUT (tty, tty->TS_insert_mode);
281 tty->insert_mode = 1;
284 void
285 tty_turn_off_insert (struct tty_display_info *tty)
287 if (tty->insert_mode)
288 OUTPUT (tty, tty->TS_end_insert_mode);
289 tty->insert_mode = 0;
292 /* Handle highlighting. */
294 static void
295 tty_turn_off_highlight (struct tty_display_info *tty)
297 if (tty->standout_mode)
298 OUTPUT_IF (tty, tty->TS_end_standout_mode);
299 tty->standout_mode = 0;
302 static void
303 tty_turn_on_highlight (struct tty_display_info *tty)
305 if (!tty->standout_mode)
306 OUTPUT_IF (tty, tty->TS_standout_mode);
307 tty->standout_mode = 1;
310 static void
311 tty_toggle_highlight (struct tty_display_info *tty)
313 if (tty->standout_mode)
314 tty_turn_off_highlight (tty);
315 else
316 tty_turn_on_highlight (tty);
320 /* Make cursor invisible. */
322 static void
323 tty_hide_cursor (struct tty_display_info *tty)
325 if (tty->cursor_hidden == 0)
327 tty->cursor_hidden = 1;
328 #ifdef WINDOWSNT
329 w32con_hide_cursor ();
330 #else
331 OUTPUT_IF (tty, tty->TS_cursor_invisible);
332 #endif
337 /* Ensure that cursor is visible. */
339 static void
340 tty_show_cursor (struct tty_display_info *tty)
342 if (tty->cursor_hidden)
344 tty->cursor_hidden = 0;
345 #ifdef WINDOWSNT
346 w32con_show_cursor ();
347 #else
348 OUTPUT_IF (tty, tty->TS_cursor_normal);
349 if (visible_cursor)
350 OUTPUT_IF (tty, tty->TS_cursor_visible);
351 #endif
356 /* Set standout mode to the state it should be in for
357 empty space inside windows. What this is,
358 depends on the user option inverse-video. */
360 static void
361 tty_background_highlight (struct tty_display_info *tty)
363 if (inverse_video)
364 tty_turn_on_highlight (tty);
365 else
366 tty_turn_off_highlight (tty);
369 /* Set standout mode to the mode specified for the text to be output. */
371 static void
372 tty_highlight_if_desired (struct tty_display_info *tty)
374 if (inverse_video)
375 tty_turn_on_highlight (tty);
376 else
377 tty_turn_off_highlight (tty);
381 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
382 frame-relative coordinates. */
384 static void
385 tty_cursor_to (struct frame *f, int vpos, int hpos)
387 struct tty_display_info *tty = FRAME_TTY (f);
389 /* Detect the case where we are called from reset_sys_modes
390 and the costs have never been calculated. Do nothing. */
391 if (! tty->costs_set)
392 return;
394 if (curY (tty) == vpos
395 && curX (tty) == hpos)
396 return;
397 if (!tty->TF_standout_motion)
398 tty_background_highlight (tty);
399 if (!tty->TF_insmode_motion)
400 tty_turn_off_insert (tty);
401 cmgoto (tty, vpos, hpos);
404 /* Similar but don't take any account of the wasted characters. */
406 static void
407 tty_raw_cursor_to (struct frame *f, int row, int col)
409 struct tty_display_info *tty = FRAME_TTY (f);
411 if (curY (tty) == row
412 && curX (tty) == col)
413 return;
414 if (!tty->TF_standout_motion)
415 tty_background_highlight (tty);
416 if (!tty->TF_insmode_motion)
417 tty_turn_off_insert (tty);
418 cmgoto (tty, row, col);
421 /* Erase operations */
423 /* Clear from cursor to end of frame on a termcap device. */
425 static void
426 tty_clear_to_end (struct frame *f)
428 register int i;
429 struct tty_display_info *tty = FRAME_TTY (f);
431 if (tty->TS_clr_to_bottom)
433 tty_background_highlight (tty);
434 OUTPUT (tty, tty->TS_clr_to_bottom);
436 else
438 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
440 cursor_to (f, i, 0);
441 clear_end_of_line (f, FRAME_COLS (f));
446 /* Clear an entire termcap frame. */
448 static void
449 tty_clear_frame (struct frame *f)
451 struct tty_display_info *tty = FRAME_TTY (f);
453 if (tty->TS_clr_frame)
455 tty_background_highlight (tty);
456 OUTPUT (tty, tty->TS_clr_frame);
457 cmat (tty, 0, 0);
459 else
461 cursor_to (f, 0, 0);
462 clear_to_end (f);
466 /* An implementation of clear_end_of_line for termcap frames.
468 Note that the cursor may be moved, on terminals lacking a `ce' string. */
470 static void
471 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
473 register int i;
474 struct tty_display_info *tty = FRAME_TTY (f);
476 /* Detect the case where we are called from reset_sys_modes
477 and the costs have never been calculated. Do nothing. */
478 if (! tty->costs_set)
479 return;
481 if (curX (tty) >= first_unused_hpos)
482 return;
483 tty_background_highlight (tty);
484 if (tty->TS_clr_line)
486 OUTPUT1 (tty, tty->TS_clr_line);
488 else
489 { /* have to do it the hard way */
490 tty_turn_off_insert (tty);
492 /* Do not write in last row last col with Auto-wrap on. */
493 if (AutoWrap (tty)
494 && curY (tty) == FrameRows (tty) - 1
495 && first_unused_hpos == FrameCols (tty))
496 first_unused_hpos--;
498 for (i = curX (tty); i < first_unused_hpos; i++)
500 if (tty->termscript)
501 fputc_unlocked (' ', tty->termscript);
502 fputc_unlocked (' ', tty->output);
504 cmplus (tty, first_unused_hpos - curX (tty));
508 /* Buffers to store the source and result of code conversion for terminal. */
509 static unsigned char *encode_terminal_src;
510 static unsigned char *encode_terminal_dst;
511 /* Allocated sizes of the above buffers. */
512 static ptrdiff_t encode_terminal_src_size;
513 static ptrdiff_t encode_terminal_dst_size;
515 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
516 Set CODING->produced to the byte-length of the resulting byte
517 sequence, and return a pointer to that byte sequence. */
519 unsigned char *
520 encode_terminal_code (struct glyph *src, int src_len,
521 struct coding_system *coding)
523 struct glyph *src_end = src + src_len;
524 unsigned char *buf;
525 ptrdiff_t nchars, nbytes, required;
526 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
527 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
528 Lisp_Object charset_list;
530 /* Allocate sufficient size of buffer to store all characters in
531 multibyte-form. But, it may be enlarged on demand if
532 Vglyph_table contains a string or a composite glyph is
533 encountered. */
534 if (INT_MULTIPLY_WRAPV (src_len, MAX_MULTIBYTE_LENGTH, &required))
535 memory_full (SIZE_MAX);
536 if (encode_terminal_src_size < required)
537 encode_terminal_src = xpalloc (encode_terminal_src,
538 &encode_terminal_src_size,
539 required - encode_terminal_src_size,
540 -1, sizeof *encode_terminal_src);
542 charset_list = coding_charset_list (coding);
544 buf = encode_terminal_src;
545 nchars = 0;
546 while (src < src_end)
548 if (src->type == COMPOSITE_GLYPH)
550 struct composition *cmp UNINIT;
551 Lisp_Object gstring UNINIT;
552 int i;
554 nbytes = buf - encode_terminal_src;
555 if (src->u.cmp.automatic)
557 gstring = composition_gstring_from_id (src->u.cmp.id);
558 required = src->slice.cmp.to - src->slice.cmp.from + 1;
560 else
562 cmp = composition_table[src->u.cmp.id];
563 required = cmp->glyph_len;
564 required *= MAX_MULTIBYTE_LENGTH;
567 if (encode_terminal_src_size - nbytes < required)
569 encode_terminal_src =
570 xpalloc (encode_terminal_src, &encode_terminal_src_size,
571 required - (encode_terminal_src_size - nbytes),
572 -1, 1);
573 buf = encode_terminal_src + nbytes;
576 if (src->u.cmp.automatic)
577 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
579 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
580 int c = LGLYPH_CHAR (g);
582 if (! char_charset (c, charset_list, NULL))
583 c = '?';
584 buf += CHAR_STRING (c, buf);
585 nchars++;
587 else
588 for (i = 0; i < cmp->glyph_len; i++)
590 int c = COMPOSITION_GLYPH (cmp, i);
592 /* TAB in a composition means display glyphs with
593 padding space on the left or right. */
594 if (c == '\t')
595 continue;
596 if (char_charset (c, charset_list, NULL))
598 if (CHARACTER_WIDTH (c) == 0
599 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
600 /* Should be left-padded */
602 buf += CHAR_STRING (' ', buf);
603 nchars++;
606 else
607 c = '?';
608 buf += CHAR_STRING (c, buf);
609 nchars++;
612 /* We must skip glyphs to be padded for a wide character. */
613 else if (! CHAR_GLYPH_PADDING_P (*src))
615 GLYPH g;
616 int c UNINIT;
617 Lisp_Object string;
619 string = Qnil;
620 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
622 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
624 /* This glyph doesn't have an entry in Vglyph_table. */
625 c = src->u.ch;
627 else
629 /* This glyph has an entry in Vglyph_table,
630 so process any alias before testing for simpleness. */
631 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
633 if (GLYPH_SIMPLE_P (tbase, tlen, g))
634 /* We set the multi-byte form of a character in G
635 (that should be an ASCII character) at WORKBUF. */
636 c = GLYPH_CHAR (g);
637 else
638 /* We have a string in Vglyph_table. */
639 string = tbase[GLYPH_CHAR (g)];
642 if (NILP (string))
644 nbytes = buf - encode_terminal_src;
645 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
647 encode_terminal_src =
648 xpalloc (encode_terminal_src, &encode_terminal_src_size,
649 MAX_MULTIBYTE_LENGTH, -1, 1);
650 buf = encode_terminal_src + nbytes;
652 if (CHAR_BYTE8_P (c)
653 || char_charset (c, charset_list, NULL))
655 /* Store the multibyte form of C at BUF. */
656 buf += CHAR_STRING (c, buf);
657 nchars++;
659 else
661 /* C is not encodable. */
662 *buf++ = '?';
663 nchars++;
664 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
666 *buf++ = '?';
667 nchars++;
668 src++;
672 else
674 if (! STRING_MULTIBYTE (string))
675 string = string_to_multibyte (string);
676 nbytes = buf - encode_terminal_src;
677 if (encode_terminal_src_size - nbytes < SBYTES (string))
679 encode_terminal_src =
680 xpalloc (encode_terminal_src, &encode_terminal_src_size,
681 (SBYTES (string)
682 - (encode_terminal_src_size - nbytes)),
683 -1, 1);
684 buf = encode_terminal_src + nbytes;
686 memcpy (buf, SDATA (string), SBYTES (string));
687 buf += SBYTES (string);
688 nchars += SCHARS (string);
691 src++;
694 if (nchars == 0)
696 coding->produced = 0;
697 return NULL;
700 nbytes = buf - encode_terminal_src;
701 coding->source = encode_terminal_src;
702 if (encode_terminal_dst_size == 0)
704 encode_terminal_dst = xrealloc (encode_terminal_dst,
705 encode_terminal_src_size);
706 encode_terminal_dst_size = encode_terminal_src_size;
708 coding->destination = encode_terminal_dst;
709 coding->dst_bytes = encode_terminal_dst_size;
710 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
711 /* coding->destination may have been reallocated. */
712 encode_terminal_dst = coding->destination;
713 encode_terminal_dst_size = coding->dst_bytes;
715 return (encode_terminal_dst);
720 /* An implementation of write_glyphs for termcap frames. */
722 static void
723 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
725 unsigned char *conversion_buffer;
726 struct coding_system *coding;
727 int n, stringlen;
729 struct tty_display_info *tty = FRAME_TTY (f);
731 tty_turn_off_insert (tty);
732 tty_hide_cursor (tty);
734 /* Don't dare write in last column of bottom line, if Auto-Wrap,
735 since that would scroll the whole frame on some terminals. */
737 if (AutoWrap (tty)
738 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
739 && (curX (tty) + len) == FRAME_COLS (f))
740 len --;
741 if (len <= 0)
742 return;
744 cmplus (tty, len);
746 /* If terminal_coding does any conversion, use it, otherwise use
747 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
748 because it always return 1 if the member src_multibyte is 1. */
749 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
750 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
751 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
752 the tail. */
753 coding->mode &= ~CODING_MODE_LAST_BLOCK;
755 for (stringlen = len; stringlen != 0; stringlen -= n)
757 /* Identify a run of glyphs with the same face. */
758 int face_id = string->face_id;
760 for (n = 1; n < stringlen; ++n)
761 if (string[n].face_id != face_id)
762 break;
764 /* Turn appearance modes of the face of the run on. */
765 tty_highlight_if_desired (tty);
766 turn_on_face (f, face_id);
768 if (n == stringlen)
769 /* This is the last run. */
770 coding->mode |= CODING_MODE_LAST_BLOCK;
771 conversion_buffer = encode_terminal_code (string, n, coding);
772 if (coding->produced > 0)
774 block_input ();
775 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
776 clearerr_unlocked (tty->output);
777 if (tty->termscript)
778 fwrite_unlocked (conversion_buffer, 1, coding->produced,
779 tty->termscript);
780 unblock_input ();
782 string += n;
784 /* Turn appearance modes off. */
785 turn_off_face (f, face_id);
786 tty_turn_off_highlight (tty);
789 cmcheckmagic (tty);
792 #ifdef HAVE_GPM /* Only used by GPM code. */
794 static void
795 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
796 register int len, register int face_id)
798 unsigned char *conversion_buffer;
799 struct coding_system *coding;
801 struct tty_display_info *tty = FRAME_TTY (f);
803 tty_turn_off_insert (tty);
804 tty_hide_cursor (tty);
806 /* Don't dare write in last column of bottom line, if Auto-Wrap,
807 since that would scroll the whole frame on some terminals. */
809 if (AutoWrap (tty)
810 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
811 && (curX (tty) + len) == FRAME_COLS (f))
812 len --;
813 if (len <= 0)
814 return;
816 cmplus (tty, len);
818 /* If terminal_coding does any conversion, use it, otherwise use
819 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
820 because it always return 1 if the member src_multibyte is 1. */
821 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
822 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
823 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
824 the tail. */
825 coding->mode &= ~CODING_MODE_LAST_BLOCK;
827 /* Turn appearance modes of the face. */
828 tty_highlight_if_desired (tty);
829 turn_on_face (f, face_id);
831 coding->mode |= CODING_MODE_LAST_BLOCK;
832 conversion_buffer = encode_terminal_code (string, len, coding);
833 if (coding->produced > 0)
835 block_input ();
836 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
837 clearerr_unlocked (tty->output);
838 if (tty->termscript)
839 fwrite_unlocked (conversion_buffer, 1, coding->produced,
840 tty->termscript);
841 unblock_input ();
844 /* Turn appearance modes off. */
845 turn_off_face (f, face_id);
846 tty_turn_off_highlight (tty);
848 cmcheckmagic (tty);
850 #endif
852 /* An implementation of insert_glyphs for termcap frames. */
854 static void
855 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
857 char *buf;
858 struct glyph *glyph = NULL;
859 unsigned char *conversion_buffer;
860 unsigned char space[1];
861 struct coding_system *coding;
863 struct tty_display_info *tty = FRAME_TTY (f);
865 if (tty->TS_ins_multi_chars)
867 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
868 OUTPUT1 (tty, buf);
869 xfree (buf);
870 if (start)
871 write_glyphs (f, start, len);
872 return;
875 tty_turn_on_insert (tty);
876 cmplus (tty, len);
878 if (! start)
879 space[0] = SPACEGLYPH;
881 /* If terminal_coding does any conversion, use it, otherwise use
882 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
883 because it always return 1 if the member src_multibyte is 1. */
884 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
885 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
886 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
887 the tail. */
888 coding->mode &= ~CODING_MODE_LAST_BLOCK;
890 while (len-- > 0)
892 OUTPUT1_IF (tty, tty->TS_ins_char);
893 if (!start)
895 conversion_buffer = space;
896 coding->produced = 1;
898 else
900 tty_highlight_if_desired (tty);
901 turn_on_face (f, start->face_id);
902 glyph = start;
903 ++start;
904 /* We must open sufficient space for a character which
905 occupies more than one column. */
906 while (len && CHAR_GLYPH_PADDING_P (*start))
908 OUTPUT1_IF (tty, tty->TS_ins_char);
909 start++, len--;
912 if (len <= 0)
913 /* This is the last glyph. */
914 coding->mode |= CODING_MODE_LAST_BLOCK;
916 conversion_buffer = encode_terminal_code (glyph, 1, coding);
919 if (coding->produced > 0)
921 block_input ();
922 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
923 clearerr_unlocked (tty->output);
924 if (tty->termscript)
925 fwrite_unlocked (conversion_buffer, 1, coding->produced,
926 tty->termscript);
927 unblock_input ();
930 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
931 if (start)
933 turn_off_face (f, glyph->face_id);
934 tty_turn_off_highlight (tty);
938 cmcheckmagic (tty);
941 /* An implementation of delete_glyphs for termcap frames. */
943 static void
944 tty_delete_glyphs (struct frame *f, int n)
946 char *buf;
947 register int i;
949 struct tty_display_info *tty = FRAME_TTY (f);
951 if (tty->delete_in_insert_mode)
953 tty_turn_on_insert (tty);
955 else
957 tty_turn_off_insert (tty);
958 OUTPUT_IF (tty, tty->TS_delete_mode);
961 if (tty->TS_del_multi_chars)
963 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
964 OUTPUT1 (tty, buf);
965 xfree (buf);
967 else
968 for (i = 0; i < n; i++)
969 OUTPUT1 (tty, tty->TS_del_char);
970 if (!tty->delete_in_insert_mode)
971 OUTPUT_IF (tty, tty->TS_end_delete_mode);
974 /* An implementation of ins_del_lines for termcap frames. */
976 static void
977 tty_ins_del_lines (struct frame *f, int vpos, int n)
979 struct tty_display_info *tty = FRAME_TTY (f);
980 const char *multi =
981 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
982 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
983 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
985 int i = eabs (n);
986 char *buf;
988 /* If the lines below the insertion are being pushed
989 into the end of the window, this is the same as clearing;
990 and we know the lines are already clear, since the matching
991 deletion has already been done. So can ignore this. */
992 /* If the lines below the deletion are blank lines coming
993 out of the end of the window, don't bother,
994 as there will be a matching inslines later that will flush them. */
995 if (FRAME_SCROLL_REGION_OK (f)
996 && vpos + i >= tty->specified_window)
997 return;
998 if (!FRAME_MEMORY_BELOW_FRAME (f)
999 && vpos + i >= FRAME_TOTAL_LINES (f))
1000 return;
1002 if (multi)
1004 raw_cursor_to (f, vpos, 0);
1005 tty_background_highlight (tty);
1006 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1007 OUTPUT (tty, buf);
1008 xfree (buf);
1010 else if (single)
1012 raw_cursor_to (f, vpos, 0);
1013 tty_background_highlight (tty);
1014 while (--i >= 0)
1015 OUTPUT (tty, single);
1016 if (tty->TF_teleray)
1017 curX (tty) = 0;
1019 else
1021 tty_set_scroll_region (f, vpos, tty->specified_window);
1022 if (n < 0)
1023 raw_cursor_to (f, tty->specified_window - 1, 0);
1024 else
1025 raw_cursor_to (f, vpos, 0);
1026 tty_background_highlight (tty);
1027 while (--i >= 0)
1028 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1029 tty_set_scroll_region (f, 0, tty->specified_window);
1032 if (!FRAME_SCROLL_REGION_OK (f)
1033 && FRAME_MEMORY_BELOW_FRAME (f)
1034 && n < 0)
1036 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1037 clear_to_end (f);
1041 /* Compute cost of sending "str", in characters,
1042 not counting any line-dependent padding. */
1045 string_cost (const char *str)
1047 cost = 0;
1048 if (str)
1049 tputs (str, 0, evalcost);
1050 return cost;
1053 /* Compute cost of sending "str", in characters,
1054 counting any line-dependent padding at one line. */
1056 static int
1057 string_cost_one_line (const char *str)
1059 cost = 0;
1060 if (str)
1061 tputs (str, 1, evalcost);
1062 return cost;
1065 /* Compute per line amount of line-dependent padding,
1066 in tenths of characters. */
1069 per_line_cost (const char *str)
1071 cost = 0;
1072 if (str)
1073 tputs (str, 0, evalcost);
1074 cost = - cost;
1075 if (str)
1076 tputs (str, 10, evalcost);
1077 return cost;
1080 /* char_ins_del_cost[n] is cost of inserting N characters.
1081 char_ins_del_cost[-n] is cost of deleting N characters.
1082 The length of this vector is based on max_frame_cols. */
1084 int *char_ins_del_vector;
1086 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1088 /* ARGSUSED */
1089 static void
1090 calculate_ins_del_char_costs (struct frame *f)
1092 struct tty_display_info *tty = FRAME_TTY (f);
1093 int ins_startup_cost, del_startup_cost;
1094 int ins_cost_per_char, del_cost_per_char;
1095 register int i;
1096 register int *p;
1098 if (tty->TS_ins_multi_chars)
1100 ins_cost_per_char = 0;
1101 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1103 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1104 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1106 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1107 + string_cost (tty->TS_end_insert_mode))) / 100;
1108 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1109 + string_cost_one_line (tty->TS_pad_inserted_char));
1111 else
1113 ins_startup_cost = 9999;
1114 ins_cost_per_char = 0;
1117 if (tty->TS_del_multi_chars)
1119 del_cost_per_char = 0;
1120 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1122 else if (tty->TS_del_char)
1124 del_startup_cost = (string_cost (tty->TS_delete_mode)
1125 + string_cost (tty->TS_end_delete_mode));
1126 if (tty->delete_in_insert_mode)
1127 del_startup_cost /= 2;
1128 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1130 else
1132 del_startup_cost = 9999;
1133 del_cost_per_char = 0;
1136 /* Delete costs are at negative offsets */
1137 p = &char_ins_del_cost (f)[0];
1138 for (i = FRAME_COLS (f); --i >= 0;)
1139 *--p = (del_startup_cost += del_cost_per_char);
1141 /* Doing nothing is free */
1142 p = &char_ins_del_cost (f)[0];
1143 *p++ = 0;
1145 /* Insert costs are at positive offsets */
1146 for (i = FRAME_COLS (f); --i >= 0;)
1147 *p++ = (ins_startup_cost += ins_cost_per_char);
1150 void
1151 calculate_costs (struct frame *frame)
1153 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1155 if (FRAME_TERMCAP_P (frame))
1157 struct tty_display_info *tty = FRAME_TTY (frame);
1158 register const char *f = (tty->TS_set_scroll_region
1159 ? tty->TS_set_scroll_region
1160 : tty->TS_set_scroll_region_1);
1162 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1164 tty->costs_set = 1;
1166 /* These variables are only used for terminal stuff. They are
1167 allocated once for the terminal frame of X-windows emacs, but not
1168 used afterwards.
1170 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1171 X turns off char_ins_del_ok. */
1173 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1174 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1175 < max_frame_cols)
1176 memory_full (SIZE_MAX);
1178 char_ins_del_vector =
1179 xrealloc (char_ins_del_vector,
1180 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1182 memset (char_ins_del_vector, 0,
1183 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1186 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1187 do_line_insertion_deletion_costs (frame,
1188 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1189 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1190 f, f, 1);
1191 else
1192 do_line_insertion_deletion_costs (frame,
1193 tty->TS_ins_line, tty->TS_ins_multi_lines,
1194 tty->TS_del_line, tty->TS_del_multi_lines,
1195 0, 0, 1);
1197 calculate_ins_del_char_costs (frame);
1199 /* Don't use TS_repeat if its padding is worse than sending the chars */
1200 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1201 tty->RPov = string_cost (tty->TS_repeat);
1202 else
1203 tty->RPov = FRAME_COLS (frame) * 2;
1205 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1209 struct fkey_table {
1210 const char *cap, *name;
1213 /* Termcap capability names that correspond directly to X keysyms.
1214 Some of these (marked "terminfo") aren't supplied by old-style
1215 (Berkeley) termcap entries. They're listed in X keysym order;
1216 except we put the keypad keys first, so that if they clash with
1217 other keys (as on the IBM PC keyboard) they get overridden.
1220 static const struct fkey_table keys[] =
1222 {"kh", "home"}, /* termcap */
1223 {"kl", "left"}, /* termcap */
1224 {"ku", "up"}, /* termcap */
1225 {"kr", "right"}, /* termcap */
1226 {"kd", "down"}, /* termcap */
1227 {"%8", "prior"}, /* terminfo */
1228 {"%5", "next"}, /* terminfo */
1229 {"@7", "end"}, /* terminfo */
1230 {"@1", "begin"}, /* terminfo */
1231 {"*6", "select"}, /* terminfo */
1232 {"%9", "print"}, /* terminfo */
1233 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1235 * "insert" --- see below
1237 {"&8", "undo"}, /* terminfo */
1238 {"%0", "redo"}, /* terminfo */
1239 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1240 {"@0", "find"}, /* terminfo */
1241 {"@2", "cancel"}, /* terminfo */
1242 {"%1", "help"}, /* terminfo */
1244 * "break" goes here, but can't be reliably intercepted with termcap
1246 {"&4", "reset"}, /* terminfo --- actually `restart' */
1248 * "system" and "user" --- no termcaps
1250 {"kE", "clearline"}, /* terminfo */
1251 {"kA", "insertline"}, /* terminfo */
1252 {"kL", "deleteline"}, /* terminfo */
1253 {"kI", "insertchar"}, /* terminfo */
1254 {"kD", "deletechar"}, /* terminfo */
1255 {"kB", "backtab"}, /* terminfo */
1257 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1259 {"@8", "kp-enter"}, /* terminfo */
1261 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1262 * "kp-multiply", "kp-add", "kp-separator",
1263 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1264 * --- no termcaps for any of these.
1266 {"K4", "kp-1"}, /* terminfo */
1268 * "kp-2" --- no termcap
1270 {"K5", "kp-3"}, /* terminfo */
1272 * "kp-4" --- no termcap
1274 {"K2", "kp-5"}, /* terminfo */
1276 * "kp-6" --- no termcap
1278 {"K1", "kp-7"}, /* terminfo */
1280 * "kp-8" --- no termcap
1282 {"K3", "kp-9"}, /* terminfo */
1284 * "kp-equal" --- no termcap
1286 {"k1", "f1"},
1287 {"k2", "f2"},
1288 {"k3", "f3"},
1289 {"k4", "f4"},
1290 {"k5", "f5"},
1291 {"k6", "f6"},
1292 {"k7", "f7"},
1293 {"k8", "f8"},
1294 {"k9", "f9"},
1296 {"&0", "S-cancel"}, /*shifted cancel key*/
1297 {"&9", "S-begin"}, /*shifted begin key*/
1298 {"*0", "S-find"}, /*shifted find key*/
1299 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1300 {"*4", "S-delete"}, /*shifted delete-character key*/
1301 {"*7", "S-end"}, /*shifted end key*/
1302 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1303 {"#1", "S-help"}, /*shifted help key*/
1304 {"#2", "S-home"}, /*shifted home key*/
1305 {"#3", "S-insert"}, /*shifted insert-character key*/
1306 {"#4", "S-left"}, /*shifted left-arrow key*/
1307 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1308 {"%c", "S-next"}, /*shifted next key*/
1309 {"%e", "S-prior"}, /*shifted previous key*/
1310 {"%f", "S-print"}, /*shifted print key*/
1311 {"%g", "S-redo"}, /*shifted redo key*/
1312 {"%i", "S-right"}, /*shifted right-arrow key*/
1313 {"!3", "S-undo"} /*shifted undo key*/
1316 #ifndef DOS_NT
1317 static char **term_get_fkeys_address;
1318 static KBOARD *term_get_fkeys_kboard;
1319 static Lisp_Object term_get_fkeys_1 (void);
1321 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1322 This function scans the termcap function key sequence entries, and
1323 adds entries to Vinput_decode_map for each function key it finds. */
1325 static void
1326 term_get_fkeys (char **address, KBOARD *kboard)
1328 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1329 errors during the call. The only errors should be from Fdefine_key
1330 when given a key sequence containing an invalid prefix key. If the
1331 termcap defines function keys which use a prefix that is already bound
1332 to a command by the default bindings, we should silently ignore that
1333 function key specification, rather than giving the user an error and
1334 refusing to run at all on such a terminal. */
1336 term_get_fkeys_address = address;
1337 term_get_fkeys_kboard = kboard;
1338 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1341 static Lisp_Object
1342 term_get_fkeys_1 (void)
1344 int i;
1346 char **address = term_get_fkeys_address;
1347 KBOARD *kboard = term_get_fkeys_kboard;
1349 /* This can happen if CANNOT_DUMP or with strange options. */
1350 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1351 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1353 for (i = 0; i < ARRAYELTS (keys); i++)
1355 char *sequence = tgetstr (keys[i].cap, address);
1356 if (sequence)
1357 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1358 Fmake_vector (make_number (1),
1359 intern (keys[i].name)));
1362 /* The uses of the "k0" capability are inconsistent; sometimes it
1363 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1364 We will attempt to politely accommodate both systems by testing for
1365 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1368 const char *k_semi = tgetstr ("k;", address);
1369 const char *k0 = tgetstr ("k0", address);
1370 const char *k0_name = "f10";
1372 if (k_semi)
1374 if (k0)
1375 /* Define f0 first, so that f10 takes precedence in case the
1376 key sequences happens to be the same. */
1377 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1378 Fmake_vector (make_number (1), intern ("f0")));
1379 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1380 Fmake_vector (make_number (1), intern ("f10")));
1382 else if (k0)
1383 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1384 Fmake_vector (make_number (1), intern (k0_name)));
1387 /* Set up cookies for numbered function keys above f10. */
1389 char fcap[3], fkey[4];
1391 fcap[0] = 'F'; fcap[2] = '\0';
1392 for (i = 11; i < 64; i++)
1394 if (i <= 19)
1395 fcap[1] = '1' + i - 11;
1396 else if (i <= 45)
1397 fcap[1] = 'A' + i - 20;
1398 else
1399 fcap[1] = 'a' + i - 46;
1402 char *sequence = tgetstr (fcap, address);
1403 if (sequence)
1405 sprintf (fkey, "f%d", i);
1406 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1407 Fmake_vector (make_number (1),
1408 intern (fkey)));
1415 * Various mappings to try and get a better fit.
1418 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1419 if (!tgetstr (cap1, address)) \
1421 char *sequence = tgetstr (cap2, address); \
1422 if (sequence) \
1423 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1424 Fmake_vector (make_number (1), \
1425 intern (sym))); \
1428 /* if there's no key_next keycap, map key_npage to `next' keysym */
1429 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1430 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1431 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1432 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1433 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1434 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1435 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1436 #undef CONDITIONAL_REASSIGN
1439 return Qnil;
1441 #endif /* not DOS_NT */
1444 /***********************************************************************
1445 Character Display Information
1446 ***********************************************************************/
1447 static void append_glyph (struct it *);
1448 static void append_composite_glyph (struct it *);
1449 static void produce_composite_glyph (struct it *);
1450 static void append_glyphless_glyph (struct it *, int, const char *);
1451 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1453 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1454 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1455 the character for which to produce glyphs; IT->face_id contains the
1456 character's face. Padding glyphs are appended if IT->c has a
1457 IT->pixel_width > 1. */
1459 static void
1460 append_glyph (struct it *it)
1462 struct glyph *glyph, *end;
1463 int i;
1465 eassert (it->glyph_row);
1466 glyph = (it->glyph_row->glyphs[it->area]
1467 + it->glyph_row->used[it->area]);
1468 end = it->glyph_row->glyphs[1 + it->area];
1470 /* If the glyph row is reversed, we need to prepend the glyph rather
1471 than append it. */
1472 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1474 struct glyph *g;
1475 int move_by = it->pixel_width;
1477 /* Make room for the new glyphs. */
1478 if (move_by > end - glyph) /* don't overstep end of this area */
1479 move_by = end - glyph;
1480 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1481 g[move_by] = *g;
1482 glyph = it->glyph_row->glyphs[it->area];
1483 end = glyph + move_by;
1486 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1487 right, even in the REVERSED_P case, since (a) all of its u.ch are
1488 identical, and (b) the PADDING_P flag needs to be set for the
1489 leftmost one, because we write to the terminal left-to-right. */
1490 for (i = 0;
1491 i < it->pixel_width && glyph < end;
1492 ++i)
1494 glyph->type = CHAR_GLYPH;
1495 glyph->pixel_width = 1;
1496 glyph->u.ch = it->char_to_display;
1497 glyph->face_id = it->face_id;
1498 glyph->avoid_cursor_p = it->avoid_cursor_p;
1499 glyph->multibyte_p = it->multibyte_p;
1500 glyph->padding_p = i > 0;
1501 glyph->charpos = CHARPOS (it->position);
1502 glyph->object = it->object;
1503 if (it->bidi_p)
1505 glyph->resolved_level = it->bidi_it.resolved_level;
1506 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1507 glyph->bidi_type = it->bidi_it.type;
1509 else
1511 glyph->resolved_level = 0;
1512 glyph->bidi_type = UNKNOWN_BT;
1515 ++it->glyph_row->used[it->area];
1516 ++glyph;
1520 /* For external use. */
1521 void
1522 tty_append_glyph (struct it *it)
1524 append_glyph (it);
1528 /* Produce glyphs for the display element described by IT. *IT
1529 specifies what we want to produce a glyph for (character, image, ...),
1530 and where in the glyph matrix we currently are (glyph row and hpos).
1531 produce_glyphs fills in output fields of *IT with information such as the
1532 pixel width and height of a character, and maybe output actual glyphs at
1533 the same time if IT->glyph_row is non-null. For an overview, see
1534 the explanation in dispextern.h, before the definition of the
1535 display_element_type enumeration.
1537 produce_glyphs also stores the result of glyph width, ascent
1538 etc. computations in *IT.
1540 IT->glyph_row may be null, in which case produce_glyphs does not
1541 actually fill in the glyphs. This is used in the move_* functions
1542 in xdisp.c for text width and height computations.
1544 Callers usually don't call produce_glyphs directly;
1545 instead they use the macro PRODUCE_GLYPHS. */
1547 void
1548 produce_glyphs (struct it *it)
1550 /* If a hook is installed, let it do the work. */
1552 /* Nothing but characters are supported on terminal frames. */
1553 eassert (it->what == IT_CHARACTER
1554 || it->what == IT_COMPOSITION
1555 || it->what == IT_STRETCH
1556 || it->what == IT_GLYPHLESS);
1558 if (it->what == IT_STRETCH)
1560 produce_stretch_glyph (it);
1561 goto done;
1564 if (it->what == IT_COMPOSITION)
1566 produce_composite_glyph (it);
1567 goto done;
1570 if (it->what == IT_GLYPHLESS)
1572 produce_glyphless_glyph (it, Qnil);
1573 goto done;
1576 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1578 it->pixel_width = it->nglyphs = 1;
1579 if (it->glyph_row)
1580 append_glyph (it);
1582 else if (it->char_to_display == '\n')
1583 it->pixel_width = it->nglyphs = 0;
1584 else if (it->char_to_display == '\t')
1586 int absolute_x = (it->current_x
1587 + it->continuation_lines_width);
1588 int next_tab_x
1589 = (((1 + absolute_x + it->tab_width - 1)
1590 / it->tab_width)
1591 * it->tab_width);
1592 int nspaces;
1594 /* If part of the TAB has been displayed on the previous line
1595 which is continued now, continuation_lines_width will have
1596 been incremented already by the part that fitted on the
1597 continued line. So, we will get the right number of spaces
1598 here. */
1599 nspaces = next_tab_x - absolute_x;
1601 if (it->glyph_row)
1603 int n = nspaces;
1605 it->char_to_display = ' ';
1606 it->pixel_width = it->len = 1;
1608 while (n--)
1609 append_glyph (it);
1612 it->pixel_width = nspaces;
1613 it->nglyphs = nspaces;
1615 else if (CHAR_BYTE8_P (it->char_to_display))
1617 /* Coming here means that we must send the raw 8-bit byte as is
1618 to the terminal. Although there's no way to know how many
1619 columns it occupies on a screen, it is a good assumption that
1620 a single byte code has 1-column width. */
1621 it->pixel_width = it->nglyphs = 1;
1622 if (it->glyph_row)
1623 append_glyph (it);
1625 else
1627 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1629 if (char_charset (it->char_to_display, charset_list, NULL))
1631 it->pixel_width = CHARACTER_WIDTH (it->char_to_display);
1632 it->nglyphs = it->pixel_width;
1633 if (it->glyph_row)
1634 append_glyph (it);
1636 else
1638 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1640 eassert (it->what == IT_GLYPHLESS);
1641 produce_glyphless_glyph (it, acronym);
1645 done:
1646 /* Advance current_x by the pixel width as a convenience for
1647 the caller. */
1648 if (it->area == TEXT_AREA)
1649 it->current_x += it->pixel_width;
1650 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1651 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1654 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1655 Called from produce_composite_glyph for terminal frames if
1656 IT->glyph_row != NULL. IT->face_id contains the character's
1657 face. */
1659 static void
1660 append_composite_glyph (struct it *it)
1662 struct glyph *glyph;
1664 eassert (it->glyph_row);
1665 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1666 if (glyph < it->glyph_row->glyphs[1 + it->area])
1668 /* If the glyph row is reversed, we need to prepend the glyph
1669 rather than append it. */
1670 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1672 struct glyph *g;
1674 /* Make room for the new glyph. */
1675 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1676 g[1] = *g;
1677 glyph = it->glyph_row->glyphs[it->area];
1679 glyph->type = COMPOSITE_GLYPH;
1680 eassert (it->pixel_width <= SHRT_MAX);
1681 glyph->pixel_width = it->pixel_width;
1682 glyph->u.cmp.id = it->cmp_it.id;
1683 if (it->cmp_it.ch < 0)
1685 glyph->u.cmp.automatic = 0;
1686 glyph->u.cmp.id = it->cmp_it.id;
1688 else
1690 glyph->u.cmp.automatic = 1;
1691 glyph->u.cmp.id = it->cmp_it.id;
1692 glyph->slice.cmp.from = it->cmp_it.from;
1693 glyph->slice.cmp.to = it->cmp_it.to - 1;
1696 glyph->avoid_cursor_p = it->avoid_cursor_p;
1697 glyph->multibyte_p = it->multibyte_p;
1698 glyph->face_id = it->face_id;
1699 glyph->padding_p = false;
1700 glyph->charpos = CHARPOS (it->position);
1701 glyph->object = it->object;
1702 if (it->bidi_p)
1704 glyph->resolved_level = it->bidi_it.resolved_level;
1705 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1706 glyph->bidi_type = it->bidi_it.type;
1708 else
1710 glyph->resolved_level = 0;
1711 glyph->bidi_type = UNKNOWN_BT;
1714 ++it->glyph_row->used[it->area];
1715 ++glyph;
1720 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1721 the composition. We simply produces components of the composition
1722 assuming that the terminal has a capability to layout/render it
1723 correctly. */
1725 static void
1726 produce_composite_glyph (struct it *it)
1728 if (it->cmp_it.ch < 0)
1730 struct composition *cmp = composition_table[it->cmp_it.id];
1732 it->pixel_width = cmp->width;
1734 else
1736 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1738 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1739 it->cmp_it.to, NULL);
1741 it->nglyphs = 1;
1742 if (it->glyph_row)
1743 append_composite_glyph (it);
1747 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1748 is a face ID to be used for the glyph. What is actually appended
1749 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1750 comes from it->nglyphs bytes). */
1752 static void
1753 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1755 struct glyph *glyph, *end;
1756 int i;
1758 eassert (it->glyph_row);
1759 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1760 end = it->glyph_row->glyphs[1 + it->area];
1762 /* If the glyph row is reversed, we need to prepend the glyph rather
1763 than append it. */
1764 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1766 struct glyph *g;
1767 int move_by = it->pixel_width;
1769 /* Make room for the new glyphs. */
1770 if (move_by > end - glyph) /* don't overstep end of this area */
1771 move_by = end - glyph;
1772 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1773 g[move_by] = *g;
1774 glyph = it->glyph_row->glyphs[it->area];
1775 end = glyph + move_by;
1778 if (glyph >= end)
1779 return;
1780 glyph->type = CHAR_GLYPH;
1781 glyph->pixel_width = 1;
1782 glyph->avoid_cursor_p = it->avoid_cursor_p;
1783 glyph->multibyte_p = it->multibyte_p;
1784 glyph->face_id = face_id;
1785 glyph->padding_p = false;
1786 glyph->charpos = CHARPOS (it->position);
1787 glyph->object = it->object;
1788 if (it->bidi_p)
1790 glyph->resolved_level = it->bidi_it.resolved_level;
1791 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1792 glyph->bidi_type = it->bidi_it.type;
1794 else
1796 glyph->resolved_level = 0;
1797 glyph->bidi_type = UNKNOWN_BT;
1800 /* BIDI Note: we put the glyphs of characters left to right, even in
1801 the REVERSED_P case because we write to the terminal
1802 left-to-right. */
1803 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1805 if (i > 0)
1806 glyph[0] = glyph[-1];
1807 glyph->u.ch = str[i];
1808 ++it->glyph_row->used[it->area];
1809 ++glyph;
1813 /* Produce glyphs for a glyphless character for iterator IT.
1814 IT->glyphless_method specifies which method to use for displaying
1815 the character. See the description of enum
1816 glyphless_display_method in dispextern.h for the details.
1818 ACRONYM, if non-nil, is an acronym string for the character.
1820 The glyphs actually produced are of type CHAR_GLYPH. */
1822 static void
1823 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1825 int len, face_id = merge_glyphless_glyph_face (it);
1826 char buf[sizeof "\\x" + max (6, (INT_WIDTH + 3) / 4)];
1827 char const *str = " ";
1829 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1831 /* As there's no way to produce a thin space, we produce a space
1832 of canonical width. */
1833 len = 1;
1835 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1837 len = CHARACTER_WIDTH (it->c);
1838 if (len == 0)
1839 len = 1;
1840 else if (len > 4)
1841 len = 4;
1842 len = sprintf (buf, "[%.*s]", len, str);
1843 str = buf;
1845 else
1847 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1849 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1850 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1851 if (CONSP (acronym))
1852 acronym = XCDR (acronym);
1853 buf[0] = '[';
1854 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1855 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1856 buf[1 + len] = str[len];
1857 buf[1 + len] = ']';
1858 len += 2;
1860 else
1862 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1863 len = sprintf (buf,
1864 (it->c < 0x10000 ? "\\u%04X"
1865 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1866 : "\\x%06X"),
1867 it->c + 0u);
1869 str = buf;
1872 it->pixel_width = len;
1873 it->nglyphs = len;
1874 if (it->glyph_row)
1875 append_glyphless_glyph (it, face_id, str);
1879 /***********************************************************************
1880 Faces
1881 ***********************************************************************/
1883 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1884 one of the enumerators from enum no_color_bit, or a bit set built
1885 from them. Some display attributes may not be used together with
1886 color; the termcap capability `NC' specifies which ones. */
1888 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1889 (tty->TN_max_colors > 0 \
1890 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1891 : 1)
1893 /* Turn appearances of face FACE_ID on tty frame F on.
1894 FACE_ID is a realized face ID number, in the face cache. */
1896 static void
1897 turn_on_face (struct frame *f, int face_id)
1899 struct face *face = FACE_FROM_ID (f, face_id);
1900 unsigned long fg = face->foreground;
1901 unsigned long bg = face->background;
1902 struct tty_display_info *tty = FRAME_TTY (f);
1904 /* Use reverse video if the face specifies that.
1905 Do this first because TS_end_standout_mode may be the same
1906 as TS_exit_attribute_mode, which turns all appearances off. */
1907 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1908 && (inverse_video
1909 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1910 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1911 tty_toggle_highlight (tty);
1913 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1914 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1916 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1918 if (tty->TS_enter_italic_mode)
1919 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1920 else
1921 /* Italics mode is unavailable on many terminals. In that
1922 case, map slant to dimmed text; we want italic text to
1923 appear different and dimming is not otherwise used. */
1924 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1927 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1928 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1930 if (tty->TN_max_colors > 0)
1932 const char *ts;
1933 char *p;
1935 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1936 if (face_tty_specified_color (fg) && ts)
1938 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1939 OUTPUT (tty, p);
1940 xfree (p);
1943 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1944 if (face_tty_specified_color (bg) && ts)
1946 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1947 OUTPUT (tty, p);
1948 xfree (p);
1954 /* Turn off appearances of face FACE_ID on tty frame F. */
1956 static void
1957 turn_off_face (struct frame *f, int face_id)
1959 struct face *face = FACE_FROM_ID (f, face_id);
1960 struct tty_display_info *tty = FRAME_TTY (f);
1962 if (tty->TS_exit_attribute_mode)
1964 /* Capability "me" will turn off appearance modes double-bright,
1965 half-bright, reverse-video, standout, underline. It may or
1966 may not turn off alt-char-mode. */
1967 if (face->tty_bold_p
1968 || face->tty_italic_p
1969 || face->tty_reverse_p
1970 || face->tty_underline_p)
1972 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1973 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1974 tty->standout_mode = 0;
1977 else
1979 /* If we don't have "me" we can only have those appearances
1980 that have exit sequences defined. */
1981 if (face->tty_underline_p)
1982 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1985 /* Switch back to default colors. */
1986 if (tty->TN_max_colors > 0
1987 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1988 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1989 || (face->background != FACE_TTY_DEFAULT_COLOR
1990 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1991 OUTPUT1_IF (tty, tty->TS_orig_pair);
1995 /* Return true if the terminal on frame F supports all of the
1996 capabilities in CAPS simultaneously. */
1998 bool
1999 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2001 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2002 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2003 return 0;
2005 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2006 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2008 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2009 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2011 /* We can do it! */
2012 return 1;
2015 /* Return non-zero if the terminal is capable to display colors. */
2017 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2018 0, 1, 0,
2019 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2021 TERMINAL can be a terminal object, a frame, or nil (meaning the
2022 selected frame's terminal). This function always returns nil if
2023 TERMINAL does not refer to a text terminal. */)
2024 (Lisp_Object terminal)
2026 struct terminal *t = decode_tty_terminal (terminal);
2028 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2031 /* Return the number of supported colors. */
2032 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2033 Stty_display_color_cells, 0, 1, 0,
2034 doc: /* Return the number of colors supported by the tty device TERMINAL.
2036 TERMINAL can be a terminal object, a frame, or nil (meaning the
2037 selected frame's terminal). This function always returns 0 if
2038 TERMINAL does not refer to a text terminal. */)
2039 (Lisp_Object terminal)
2041 struct terminal *t = decode_tty_terminal (terminal);
2043 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2046 #ifndef DOS_NT
2048 /* Declare here rather than in the function, as in the rest of Emacs,
2049 to work around an HPUX compiler bug (?). See
2050 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2051 static int default_max_colors;
2052 static int default_no_color_video;
2053 static char *default_orig_pair;
2054 static char *default_set_foreground;
2055 static char *default_set_background;
2057 /* Save or restore the default color-related capabilities of this
2058 terminal. */
2059 static void
2060 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2063 if (save)
2065 dupstring (&default_orig_pair, tty->TS_orig_pair);
2066 dupstring (&default_set_foreground, tty->TS_set_foreground);
2067 dupstring (&default_set_background, tty->TS_set_background);
2068 default_max_colors = tty->TN_max_colors;
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_no_color_video = default_no_color_video;
2081 /* Setup one of the standard tty color schemes according to MODE.
2082 MODE's value is generally the number of colors which we want to
2083 support; zero means set up for the default capabilities, the ones
2084 we saw at init_tty time; -1 means turn off color support. */
2085 static void
2086 tty_setup_colors (struct tty_display_info *tty, int mode)
2088 /* Canonicalize all negative values of MODE. */
2089 if (mode < -1)
2090 mode = -1;
2092 switch (mode)
2094 case -1: /* no colors at all */
2095 tty->TN_max_colors = 0;
2096 tty->TN_no_color_video = 0;
2097 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2098 break;
2099 case 0: /* default colors, if any */
2100 default:
2101 tty_default_color_capabilities (tty, 0);
2102 break;
2103 case 8: /* 8 standard ANSI colors */
2104 tty->TS_orig_pair = "\033[0m";
2105 #ifdef TERMINFO
2106 tty->TS_set_foreground = "\033[3%p1%dm";
2107 tty->TS_set_background = "\033[4%p1%dm";
2108 #else
2109 tty->TS_set_foreground = "\033[3%dm";
2110 tty->TS_set_background = "\033[4%dm";
2111 #endif
2112 tty->TN_max_colors = 8;
2113 tty->TN_no_color_video = 0;
2114 break;
2118 void
2119 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2121 Lisp_Object tem, val;
2122 Lisp_Object color_mode;
2123 int mode;
2124 Lisp_Object tty_color_mode_alist
2125 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2127 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2128 val = CONSP (tem) ? XCDR (tem) : Qnil;
2130 if (INTEGERP (val))
2131 color_mode = val;
2132 else if (SYMBOLP (tty_color_mode_alist))
2134 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2135 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2137 else
2138 color_mode = Qnil;
2140 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2142 if (mode != tty->previous_color_mode)
2144 tty->previous_color_mode = mode;
2145 tty_setup_colors (tty , mode);
2146 /* This recomputes all the faces given the new color definitions. */
2147 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2151 #endif /* !DOS_NT */
2153 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2154 doc: /* Return the type of the tty device that TERMINAL uses.
2155 Returns nil if TERMINAL is not on a tty device.
2157 TERMINAL can be a terminal object, a frame, or nil (meaning the
2158 selected frame's terminal). */)
2159 (Lisp_Object terminal)
2161 struct terminal *t = decode_tty_terminal (terminal);
2163 return (t && t->display_info.tty->type
2164 ? build_string (t->display_info.tty->type) : Qnil);
2167 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2168 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2170 TERMINAL can be a terminal object, a frame, or nil (meaning the
2171 selected frame's terminal). This function always returns nil if
2172 TERMINAL is not on a tty device. */)
2173 (Lisp_Object terminal)
2175 struct terminal *t = decode_tty_terminal (terminal);
2177 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2180 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2181 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2182 This is used to override the terminfo data, for certain terminals that
2183 do not really do underlining, but say that they do. This function has
2184 no effect if used on a non-tty terminal.
2186 TERMINAL can be a terminal object, a frame or nil (meaning the
2187 selected frame's terminal). This function always returns nil if
2188 TERMINAL does not refer to a text terminal. */)
2189 (Lisp_Object terminal)
2191 struct terminal *t = decode_live_terminal (terminal);
2193 if (t->type == output_termcap)
2194 t->display_info.tty->TS_enter_underline_mode = 0;
2195 return Qnil;
2198 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2199 doc: /* Return the topmost terminal frame on TERMINAL.
2200 TERMINAL can be a terminal object, a frame or nil (meaning the
2201 selected frame's terminal). This function returns nil if TERMINAL
2202 does not refer to a text terminal. Otherwise, it returns the
2203 top-most frame on the text terminal. */)
2204 (Lisp_Object terminal)
2206 struct terminal *t = decode_live_terminal (terminal);
2208 if (t->type == output_termcap)
2209 return t->display_info.tty->top_frame;
2210 return Qnil;
2215 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2216 doc: /* Suspend the terminal device TTY.
2218 The device is restored to its default state, and Emacs ceases all
2219 access to the tty device. Frames that use the device are not deleted,
2220 but input is not read from them and if they change, their display is
2221 not updated.
2223 TTY may be a terminal object, a frame, or nil for the terminal device
2224 of the currently selected frame.
2226 This function runs `suspend-tty-functions' after suspending the
2227 device. The functions are run with one arg, the id of the suspended
2228 terminal device.
2230 `suspend-tty' does nothing if it is called on a device that is already
2231 suspended.
2233 A suspended tty may be resumed by calling `resume-tty' on it. */)
2234 (Lisp_Object tty)
2236 struct terminal *t = decode_tty_terminal (tty);
2237 FILE *f;
2239 if (!t)
2240 error ("Attempt to suspend a non-text terminal device");
2242 f = t->display_info.tty->input;
2244 if (f)
2246 /* First run `suspend-tty-functions' and then clean up the tty
2247 state because `suspend-tty-functions' might need to change
2248 the tty state. */
2249 Lisp_Object term;
2250 XSETTERMINAL (term, t);
2251 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2253 reset_sys_modes (t->display_info.tty);
2254 delete_keyboard_wait_descriptor (fileno (f));
2256 #ifndef MSDOS
2257 fclose (f);
2258 if (f != t->display_info.tty->output)
2259 fclose (t->display_info.tty->output);
2260 #endif
2262 t->display_info.tty->input = 0;
2263 t->display_info.tty->output = 0;
2265 if (FRAMEP (t->display_info.tty->top_frame))
2266 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2270 /* Clear display hooks to prevent further output. */
2271 clear_tty_hooks (t);
2273 return Qnil;
2276 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2277 doc: /* Resume the previously suspended terminal device TTY.
2278 The terminal is opened and reinitialized. Frames that are on the
2279 suspended terminal are revived.
2281 It is an error to resume a terminal while another terminal is active
2282 on the same device.
2284 This function runs `resume-tty-functions' after resuming the terminal.
2285 The functions are run with one arg, the id of the resumed terminal
2286 device.
2288 `resume-tty' does nothing if it is called on a device that is not
2289 suspended.
2291 TTY may be a terminal object, a frame, or nil (meaning the selected
2292 frame's terminal). */)
2293 (Lisp_Object tty)
2295 struct terminal *t = decode_tty_terminal (tty);
2296 int fd;
2298 if (!t)
2299 error ("Attempt to resume a non-text terminal device");
2301 if (!t->display_info.tty->input)
2303 if (get_named_terminal (t->display_info.tty->name))
2304 error ("Cannot resume display while another display is active on the same device");
2306 #ifdef MSDOS
2307 t->display_info.tty->output = stdout;
2308 t->display_info.tty->input = stdin;
2309 #else /* !MSDOS */
2310 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2311 t->display_info.tty->input = t->display_info.tty->output
2312 = fd < 0 ? 0 : fdopen (fd, "w+");
2314 if (! t->display_info.tty->input)
2316 int open_errno = errno;
2317 emacs_close (fd);
2318 report_file_errno ("Cannot reopen tty device",
2319 build_string (t->display_info.tty->name),
2320 open_errno);
2323 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2324 dissociate_if_controlling_tty (fd);
2325 #endif
2327 add_keyboard_wait_descriptor (fd);
2329 if (FRAMEP (t->display_info.tty->top_frame))
2331 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2332 int width, height;
2333 int old_height = FRAME_COLS (f);
2334 int old_width = FRAME_TOTAL_LINES (f);
2336 /* Check if terminal/window size has changed while the frame
2337 was suspended. */
2338 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2339 if (width != old_width || height != old_height)
2340 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2341 0, 0, 0, 0);
2342 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2345 set_tty_hooks (t);
2346 init_sys_modes (t->display_info.tty);
2348 /* Run `resume-tty-functions'. */
2349 Lisp_Object term;
2350 XSETTERMINAL (term, t);
2351 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2354 set_tty_hooks (t);
2356 return Qnil;
2360 /***********************************************************************
2361 Mouse
2362 ***********************************************************************/
2364 #ifdef HAVE_GPM
2366 #ifndef HAVE_WINDOW_SYSTEM
2367 void
2368 term_mouse_moveto (int x, int y)
2370 /* TODO: how to set mouse position?
2371 const char *name;
2372 int fd;
2373 name = (const char *) ttyname (0);
2374 fd = emacs_open (name, O_WRONLY, 0);
2375 SOME_FUNCTION (x, y, fd);
2376 emacs_close (fd);
2377 last_mouse_x = x;
2378 last_mouse_y = y; */
2380 #endif /* HAVE_WINDOW_SYSTEM */
2382 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2383 void
2384 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2385 int start_hpos, int end_hpos,
2386 enum draw_glyphs_face draw)
2388 int nglyphs = end_hpos - start_hpos;
2389 struct frame *f = XFRAME (WINDOW_FRAME (w));
2390 struct tty_display_info *tty = FRAME_TTY (f);
2391 int face_id = tty->mouse_highlight.mouse_face_face_id;
2392 int save_x, save_y, pos_x, pos_y;
2394 if (end_hpos >= row->used[TEXT_AREA])
2395 nglyphs = row->used[TEXT_AREA] - start_hpos;
2397 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2398 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2400 /* Save current cursor co-ordinates. */
2401 save_y = curY (tty);
2402 save_x = curX (tty);
2403 cursor_to (f, pos_y, pos_x);
2405 if (draw == DRAW_MOUSE_FACE)
2406 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2407 nglyphs, face_id);
2408 else if (draw == DRAW_NORMAL_TEXT)
2409 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2411 cursor_to (f, save_y, save_x);
2414 static bool
2415 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2417 /* Has the mouse moved off the glyph it was on at the last sighting? */
2418 if (event->x != last_mouse_x || event->y != last_mouse_y)
2420 frame->mouse_moved = 1;
2421 note_mouse_highlight (frame, event->x, event->y);
2422 /* Remember which glyph we're now on. */
2423 last_mouse_x = event->x;
2424 last_mouse_y = event->y;
2425 return 1;
2427 return 0;
2430 /* Return the Time that corresponds to T. Wrap around on overflow. */
2431 static Time
2432 timeval_to_Time (struct timeval const *t)
2434 Time s_1000, ms;
2436 s_1000 = t->tv_sec;
2437 s_1000 *= 1000;
2438 ms = t->tv_usec / 1000;
2439 return s_1000 + ms;
2442 /* Return the current position of the mouse.
2444 Set *f to the frame the mouse is in, or zero if the mouse is in no
2445 Emacs frame. If it is set to zero, all the other arguments are
2446 garbage.
2448 Set *bar_window to Qnil, and *x and *y to the column and
2449 row of the character cell the mouse is over.
2451 Set *timeptr to the time the mouse was at the returned position.
2453 This clears mouse_moved until the next motion
2454 event arrives. */
2455 static void
2456 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2457 enum scroll_bar_part *part, Lisp_Object *x,
2458 Lisp_Object *y, Time *timeptr)
2460 struct timeval now;
2462 *fp = SELECTED_FRAME ();
2463 (*fp)->mouse_moved = 0;
2465 *bar_window = Qnil;
2466 *part = scroll_bar_above_handle;
2468 XSETINT (*x, last_mouse_x);
2469 XSETINT (*y, last_mouse_y);
2470 gettimeofday(&now, 0);
2471 *timeptr = timeval_to_Time (&now);
2474 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2476 If the event is a button press, then note that we have grabbed
2477 the mouse. */
2479 static Lisp_Object
2480 term_mouse_click (struct input_event *result, Gpm_Event *event,
2481 struct frame *f)
2483 struct timeval now;
2484 int i, j;
2486 result->kind = GPM_CLICK_EVENT;
2487 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2489 if (event->buttons & j) {
2490 result->code = i; /* button number */
2491 break;
2494 gettimeofday(&now, 0);
2495 result->timestamp = timeval_to_Time (&now);
2497 if (event->type & GPM_UP)
2498 result->modifiers = up_modifier;
2499 else if (event->type & GPM_DOWN)
2500 result->modifiers = down_modifier;
2501 else
2502 result->modifiers = 0;
2504 if (event->type & GPM_SINGLE)
2505 result->modifiers |= click_modifier;
2507 if (event->type & GPM_DOUBLE)
2508 result->modifiers |= double_modifier;
2510 if (event->type & GPM_TRIPLE)
2511 result->modifiers |= triple_modifier;
2513 if (event->type & GPM_DRAG)
2514 result->modifiers |= drag_modifier;
2516 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2518 /* 1 << KG_SHIFT */
2519 if (event->modifiers & (1 << 0))
2520 result->modifiers |= shift_modifier;
2522 /* 1 << KG_CTRL */
2523 if (event->modifiers & (1 << 2))
2524 result->modifiers |= ctrl_modifier;
2526 /* 1 << KG_ALT || KG_ALTGR */
2527 if (event->modifiers & (1 << 3)
2528 || event->modifiers & (1 << 1))
2529 result->modifiers |= meta_modifier;
2532 XSETINT (result->x, event->x);
2533 XSETINT (result->y, event->y);
2534 XSETFRAME (result->frame_or_window, f);
2535 result->arg = Qnil;
2536 return Qnil;
2540 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event,
2541 struct input_event *hold_quit)
2543 struct frame *f = XFRAME (tty->top_frame);
2544 struct input_event ie;
2545 bool do_help = 0;
2546 int count = 0;
2548 EVENT_INIT (ie);
2549 ie.kind = NO_EVENT;
2550 ie.arg = Qnil;
2552 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2553 previous_help_echo_string = help_echo_string;
2554 help_echo_string = Qnil;
2556 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2558 if (!term_mouse_movement (f, event))
2559 help_echo_string = previous_help_echo_string;
2561 /* If the contents of the global variable help_echo_string
2562 has changed, generate a HELP_EVENT. */
2563 if (!NILP (help_echo_string)
2564 || !NILP (previous_help_echo_string))
2565 do_help = 1;
2567 goto done;
2569 else {
2570 f->mouse_moved = 0;
2571 term_mouse_click (&ie, event, f);
2574 done:
2575 if (ie.kind != NO_EVENT)
2577 kbd_buffer_store_event_hold (&ie, hold_quit);
2578 count++;
2581 if (do_help
2582 && !(hold_quit && hold_quit->kind != NO_EVENT))
2584 Lisp_Object frame;
2586 if (f)
2587 XSETFRAME (frame, f);
2588 else
2589 frame = Qnil;
2591 gen_help_event (help_echo_string, frame, help_echo_window,
2592 help_echo_object, help_echo_pos);
2593 count++;
2596 return count;
2599 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2600 0, 0, 0,
2601 doc: /* Open a connection to Gpm.
2602 Gpm-mouse can only be activated for one tty at a time. */)
2603 (void)
2605 struct frame *f = SELECTED_FRAME ();
2606 struct tty_display_info *tty
2607 = ((f)->output_method == output_termcap
2608 ? (f)->terminal->display_info.tty : NULL);
2609 Gpm_Connect connection;
2611 if (!tty)
2612 error ("Gpm-mouse only works in the GNU/Linux console");
2613 if (gpm_tty == tty)
2614 return Qnil; /* Already activated, nothing to do. */
2615 if (gpm_tty)
2616 error ("Gpm-mouse can only be activated for one tty at a time");
2618 connection.eventMask = ~0;
2619 connection.defaultMask = ~GPM_HARD;
2620 connection.maxMod = ~0;
2621 connection.minMod = 0;
2622 gpm_zerobased = 1;
2624 if (Gpm_Open (&connection, 0) < 0)
2625 error ("Gpm-mouse failed to connect to the gpm daemon");
2626 else
2628 gpm_tty = tty;
2629 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2630 to generate SIGIOs. Apparently we need to call reset_sys_modes
2631 before calling init_sys_modes. */
2632 reset_sys_modes (tty);
2633 init_sys_modes (tty);
2634 add_gpm_wait_descriptor (gpm_fd);
2635 return Qnil;
2639 void
2640 close_gpm (int fd)
2642 if (fd >= 0)
2643 delete_gpm_wait_descriptor (fd);
2644 while (Gpm_Close()); /* close all the stack */
2645 gpm_tty = NULL;
2648 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2649 0, 0, 0,
2650 doc: /* Close a connection to Gpm. */)
2651 (void)
2653 struct frame *f = SELECTED_FRAME ();
2654 struct tty_display_info *tty
2655 = ((f)->output_method == output_termcap
2656 ? (f)->terminal->display_info.tty : NULL);
2658 if (!tty || gpm_tty != tty)
2659 return Qnil; /* Not activated on this terminal, nothing to do. */
2661 close_gpm (gpm_fd);
2662 return Qnil;
2664 #endif /* HAVE_GPM */
2667 /***********************************************************************
2668 Menus
2669 ***********************************************************************/
2671 #if !defined (MSDOS)
2673 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2675 However, unlike on MSDOS, where the menu text is drawn directly to
2676 the display video memory, on a TTY we use display_string (see
2677 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2678 the menu items into the frame's 'desired_matrix' glyph matrix, and
2679 then call update_frame_with_menu to deliver the results to the
2680 glass. The previous contents of the screen, in the form of the
2681 current_matrix, is stashed away, and used to restore screen
2682 contents when the menu selection changes or when the final
2683 selection is made and the menu should be popped down.
2685 The idea of this implementation was suggested by Gerd Moellmann. */
2687 #define TTYM_FAILURE -1
2688 #define TTYM_SUCCESS 1
2689 #define TTYM_NO_SELECT 2
2690 #define TTYM_IA_SELECT 3
2691 #define TTYM_NEXT 4
2692 #define TTYM_PREV 5
2694 /* These hold text of the current and the previous menu help messages. */
2695 static const char *menu_help_message, *prev_menu_help_message;
2696 /* Pane number and item number of the menu item which generated the
2697 last menu help message. */
2698 static int menu_help_paneno, menu_help_itemno;
2700 typedef struct tty_menu_struct
2702 int count;
2703 char **text;
2704 struct tty_menu_struct **submenu;
2705 int *panenumber; /* Also used as enabled flag. */
2706 ptrdiff_t allocated;
2707 int panecount;
2708 int width;
2709 const char **help_text;
2710 } tty_menu;
2712 /* Create a brand new menu structure. */
2714 static tty_menu *
2715 tty_menu_create (void)
2717 return xzalloc (sizeof *tty_menu_create ());
2720 /* Allocate some (more) memory for MENU ensuring that there is room for one
2721 more item. */
2723 static void
2724 tty_menu_make_room (tty_menu *menu)
2726 if (menu->allocated == menu->count)
2728 ptrdiff_t allocated = menu->allocated;
2729 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2730 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2731 menu->submenu = xrealloc (menu->submenu,
2732 allocated * sizeof *menu->submenu);
2733 menu->panenumber = xrealloc (menu->panenumber,
2734 allocated * sizeof *menu->panenumber);
2735 menu->help_text = xrealloc (menu->help_text,
2736 allocated * sizeof *menu->help_text);
2737 menu->allocated = allocated;
2741 /* Search the given menu structure for a given pane number. */
2743 static tty_menu *
2744 tty_menu_search_pane (tty_menu *menu, int pane)
2746 int i;
2747 tty_menu *try;
2749 for (i = 0; i < menu->count; i++)
2750 if (menu->submenu[i])
2752 if (pane == menu->panenumber[i])
2753 return menu->submenu[i];
2754 try = tty_menu_search_pane (menu->submenu[i], pane);
2755 if (try)
2756 return try;
2758 return (tty_menu *) 0;
2761 /* Determine how much screen space a given menu needs. */
2763 static void
2764 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2766 int i, h2, w2, maxsubwidth, maxheight;
2768 maxsubwidth = menu->width;
2769 maxheight = menu->count;
2770 for (i = 0; i < menu->count; i++)
2772 if (menu->submenu[i])
2774 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2775 if (w2 > maxsubwidth) maxsubwidth = w2;
2776 if (i + h2 > maxheight) maxheight = i + h2;
2779 *width = maxsubwidth;
2780 *height = maxheight;
2783 static void
2784 mouse_get_xy (int *x, int *y)
2786 struct frame *sf = SELECTED_FRAME ();
2787 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2788 enum scroll_bar_part part_dummy;
2789 Time time_dummy;
2791 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2792 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2793 &lisp_dummy, &part_dummy,
2794 &lmx, &lmy,
2795 &time_dummy);
2796 if (!NILP (lmx))
2798 *x = XINT (lmx);
2799 *y = XINT (lmy);
2803 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2804 (zero-based). */
2806 static void
2807 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2808 int mx, int my, int first_item, bool disp_help)
2810 int i, face, width, enabled, mousehere, row, col;
2811 struct frame *sf = SELECTED_FRAME ();
2812 struct tty_display_info *tty = FRAME_TTY (sf);
2813 /* Don't try to display more menu items than the console can display
2814 using the available screen lines. Exclude the echo area line, as
2815 it will be overwritten by the help-echo anyway. */
2816 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2818 menu_help_message = NULL;
2820 width = menu->width;
2821 col = cursorX (tty);
2822 row = cursorY (tty);
2823 for (i = 0; i < max_items; i++)
2825 int max_width = width + 2; /* +2 for padding blanks on each side */
2826 int j = i + first_item;
2828 if (menu->submenu[j])
2829 max_width += 2; /* for displaying " >" after the item */
2830 enabled
2831 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2832 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2833 face = faces[enabled + mousehere * 2];
2834 /* Display the menu help string for the i-th menu item even if
2835 the menu item is currently disabled. That's what the GUI
2836 code does. */
2837 if (disp_help && enabled + mousehere * 2 >= 2)
2839 menu_help_message = menu->help_text[j];
2840 menu_help_paneno = pn - 1;
2841 menu_help_itemno = j;
2843 /* Take note of the coordinates of the active menu item, to
2844 display the cursor there. */
2845 if (mousehere)
2847 row = y + i;
2848 col = x;
2850 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2851 menu->submenu[j] != NULL);
2853 update_frame_with_menu (sf, row, col);
2856 /* --------------------------- X Menu emulation ---------------------- */
2858 /* Create a new pane and place it on the outer-most level. */
2860 static int
2861 tty_menu_add_pane (tty_menu *menu, const char *txt)
2863 int len;
2865 tty_menu_make_room (menu);
2866 menu->submenu[menu->count] = tty_menu_create ();
2867 menu->text[menu->count] = (char *)txt;
2868 menu->panenumber[menu->count] = ++menu->panecount;
2869 menu->help_text[menu->count] = NULL;
2870 menu->count++;
2872 /* Update the menu width, if necessary. */
2873 len = menu_item_width ((const unsigned char *) txt);
2874 if (len > menu->width)
2875 menu->width = len;
2877 return menu->panecount;
2880 /* Create a new item in a menu pane. */
2882 static bool
2883 tty_menu_add_selection (tty_menu *menu, int pane,
2884 char *txt, bool enable, char const *help_text)
2886 int len;
2888 if (pane)
2890 menu = tty_menu_search_pane (menu, pane);
2891 if (! menu)
2892 return 0;
2894 tty_menu_make_room (menu);
2895 menu->submenu[menu->count] = (tty_menu *) 0;
2896 menu->text[menu->count] = txt;
2897 menu->panenumber[menu->count] = enable;
2898 menu->help_text[menu->count] = help_text;
2899 menu->count++;
2901 /* Update the menu width, if necessary. */
2902 len = menu_item_width ((const unsigned char *) txt);
2903 if (len > menu->width)
2904 menu->width = len;
2906 return 1;
2909 /* Decide where the menu would be placed if requested at (X,Y). */
2911 static void
2912 tty_menu_locate (tty_menu *menu, int x, int y,
2913 int *ulx, int *uly, int *width, int *height)
2915 tty_menu_calc_size (menu, width, height);
2916 *ulx = x + 1;
2917 *uly = y;
2918 *width += 2;
2921 struct tty_menu_state
2923 struct glyph_matrix *screen_behind;
2924 tty_menu *menu;
2925 int pane;
2926 int x, y;
2929 /* Save away the contents of frame F's current frame matrix, and
2930 enable all its rows. Value is a glyph matrix holding the contents
2931 of F's current frame matrix with all its glyph rows enabled. */
2933 static struct glyph_matrix *
2934 save_and_enable_current_matrix (struct frame *f)
2936 int i;
2937 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2938 saved->nrows = f->current_matrix->nrows;
2939 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2941 for (i = 0; i < saved->nrows; ++i)
2943 struct glyph_row *from = f->current_matrix->rows + i;
2944 struct glyph_row *to = saved->rows + i;
2945 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2947 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2948 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2949 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2950 /* Make sure every row is enabled, or else update_frame will not
2951 redraw them. (Rows that are identical to what is already on
2952 screen will not be redrawn anyway.) */
2953 to->enabled_p = true;
2954 to->hash = from->hash;
2957 return saved;
2960 /* Restore the contents of frame F's desired frame matrix from SAVED,
2961 and free memory associated with SAVED. */
2963 static void
2964 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2966 int i;
2968 for (i = 0; i < saved->nrows; ++i)
2970 struct glyph_row *from = saved->rows + i;
2971 struct glyph_row *to = f->desired_matrix->rows + i;
2972 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2974 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2975 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2976 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2977 to->enabled_p = from->enabled_p;
2978 to->hash = from->hash;
2982 static void
2983 free_saved_screen (struct glyph_matrix *saved)
2985 int i;
2987 if (!saved)
2988 return; /* Already freed! */
2990 for (i = 0; i < saved->nrows; ++i)
2992 struct glyph_row *from = saved->rows + i;
2994 xfree (from->glyphs[TEXT_AREA]);
2997 xfree (saved->rows);
2998 xfree (saved);
3001 /* Update the display of frame F from its saved contents. */
3002 static void
3003 screen_update (struct frame *f, struct glyph_matrix *mtx)
3005 restore_desired_matrix (f, mtx);
3006 update_frame_with_menu (f, -1, -1);
3009 typedef enum {
3010 MI_QUIT_MENU = -1,
3011 MI_CONTINUE = 0,
3012 MI_ITEM_SELECTED = 1,
3013 MI_NEXT_ITEM = 2,
3014 MI_PREV_ITEM = 3,
3015 MI_SCROLL_FORWARD = 4,
3016 MI_SCROLL_BACK = 5
3017 } mi_result;
3019 /* Read user input and return X and Y coordinates where that input
3020 puts us. We only consider mouse movement and click events, and
3021 keyboard movement commands; the rest are ignored. */
3022 static mi_result
3023 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3024 bool *first_time)
3026 if (*first_time)
3028 *first_time = false;
3029 sf->mouse_moved = 1;
3031 else
3033 Lisp_Object cmd;
3034 bool usable_input = 1;
3035 mi_result st = MI_CONTINUE;
3036 struct tty_display_info *tty = FRAME_TTY (sf);
3037 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3039 /* Signal the keyboard reading routines we are displaying a menu
3040 on this terminal. */
3041 tty->showing_menu = 1;
3042 /* We want mouse movements be reported by read_menu_command. */
3043 do_mouse_tracking = Qt;
3044 do {
3045 cmd = read_menu_command ();
3046 } while (NILP (cmd));
3047 tty->showing_menu = 0;
3048 do_mouse_tracking = saved_mouse_tracking;
3050 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3051 /* If some input switched frames under our feet, exit the
3052 menu, since the menu faces are no longer valid, and the
3053 menu is no longer relevant anyway. */
3054 || sf != SELECTED_FRAME ())
3055 return MI_QUIT_MENU;
3056 if (EQ (cmd, Qtty_menu_mouse_movement))
3057 mouse_get_xy (x, y);
3058 else if (EQ (cmd, Qtty_menu_next_menu))
3060 usable_input = 0;
3061 st = MI_NEXT_ITEM;
3063 else if (EQ (cmd, Qtty_menu_prev_menu))
3065 usable_input = 0;
3066 st = MI_PREV_ITEM;
3068 else if (EQ (cmd, Qtty_menu_next_item))
3070 if (*y < max_y)
3071 *y += 1;
3072 else
3073 st = MI_SCROLL_FORWARD;
3075 else if (EQ (cmd, Qtty_menu_prev_item))
3077 if (*y > min_y)
3078 *y -= 1;
3079 else
3080 st = MI_SCROLL_BACK;
3082 else if (EQ (cmd, Qtty_menu_select))
3083 st = MI_ITEM_SELECTED;
3084 else if (!EQ (cmd, Qtty_menu_ignore))
3085 usable_input = 0;
3086 if (usable_input)
3087 sf->mouse_moved = 1;
3088 return st;
3090 return MI_CONTINUE;
3093 /* Display menu, wait for user's response, and return that response. */
3094 static int
3095 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3096 int x0, int y0, char **txt,
3097 void (*help_callback)(char const *, int, int),
3098 bool kbd_navigation)
3100 struct tty_menu_state *state;
3101 int statecount, x, y, i;
3102 bool leave, onepane;
3103 int result UNINIT;
3104 int title_faces[4]; /* Face to display the menu title. */
3105 int faces[4], buffers_num_deleted = 0;
3106 struct frame *sf = SELECTED_FRAME ();
3107 struct tty_display_info *tty = FRAME_TTY (sf);
3108 bool first_time;
3109 Lisp_Object selectface;
3110 int first_item = 0;
3111 int col, row;
3112 Lisp_Object prev_inhibit_redisplay = Vinhibit_redisplay;
3113 USE_SAFE_ALLOCA;
3115 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3116 around the display. */
3117 if (x0 <= 0)
3118 x0 = 1;
3119 if (y0 <= 0)
3120 y0 = 1;
3122 SAFE_NALLOCA (state, 1, menu->panecount);
3123 memset (state, 0, sizeof (*state));
3124 faces[0]
3125 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3126 DEFAULT_FACE_ID, 1);
3127 faces[1]
3128 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3129 DEFAULT_FACE_ID, 1);
3130 selectface = intern ("tty-menu-selected-face");
3131 faces[2] = lookup_derived_face (sf, selectface,
3132 faces[0], 1);
3133 faces[3] = lookup_derived_face (sf, selectface,
3134 faces[1], 1);
3136 /* Make sure the menu title is always displayed with
3137 `tty-menu-selected-face', no matter where the mouse pointer is. */
3138 for (i = 0; i < 4; i++)
3139 title_faces[i] = faces[3];
3141 statecount = 1;
3143 /* Don't let the title for the "Buffers" popup menu include a
3144 digit (which is ugly).
3146 This is a terrible kludge, but I think the "Buffers" case is
3147 the only one where the title includes a number, so it doesn't
3148 seem to be necessary to make this more general. */
3149 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3151 menu->text[0][7] = '\0';
3152 buffers_num_deleted = 1;
3155 /* Inhibit redisplay for as long as the menu is active, to avoid
3156 messing the screen if some timer calls sit-for or a similar
3157 function. */
3158 Vinhibit_redisplay = Qt;
3160 /* Force update of the current frame, so that the desired and the
3161 current matrices are identical. */
3162 update_frame_with_menu (sf, -1, -1);
3163 state[0].menu = menu;
3164 state[0].screen_behind = save_and_enable_current_matrix (sf);
3166 /* Display the menu title. We subtract 1 from x0 and y0 because we
3167 want to interpret them as zero-based column and row coordinates,
3168 and also because we want the first item of the menu, not its
3169 title, to appear at x0,y0. */
3170 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3172 /* Turn off the cursor. Otherwise it shows through the menu
3173 panes, which is ugly. */
3174 col = cursorX (tty);
3175 row = cursorY (tty);
3176 tty_hide_cursor (tty);
3178 if (buffers_num_deleted)
3179 menu->text[0][7] = ' ';
3180 onepane = menu->count == 1 && menu->submenu[0];
3181 if (onepane)
3183 menu->width = menu->submenu[0]->width;
3184 state[0].menu = menu->submenu[0];
3186 else
3188 state[0].menu = menu;
3190 state[0].x = x0 - 1;
3191 state[0].y = y0;
3192 state[0].pane = onepane;
3194 x = state[0].x;
3195 y = state[0].y;
3196 first_time = true;
3198 leave = 0;
3199 while (!leave)
3201 mi_result input_status;
3202 int min_y = state[0].y;
3203 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3205 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3206 if (input_status)
3208 leave = 1;
3209 switch (input_status)
3211 case MI_QUIT_MENU:
3212 /* Remove the last help-echo, so that it doesn't
3213 re-appear after "Quit". */
3214 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3215 result = TTYM_NO_SELECT;
3216 break;
3217 case MI_NEXT_ITEM:
3218 if (kbd_navigation)
3219 result = TTYM_NEXT;
3220 else
3221 leave = 0;
3222 break;
3223 case MI_PREV_ITEM:
3224 if (kbd_navigation)
3225 result = TTYM_PREV;
3226 else
3227 leave = 0;
3228 break;
3229 case MI_SCROLL_FORWARD:
3230 if (y - min_y == state[0].menu->count - 1 - first_item)
3232 y = min_y;
3233 first_item = 0;
3235 else
3236 first_item++;
3237 leave = 0;
3238 break;
3239 case MI_SCROLL_BACK:
3240 if (first_item == 0)
3242 y = max_y;
3243 first_item = state[0].menu->count - 1 - (y - min_y);
3245 else
3246 first_item--;
3247 leave = 0;
3248 break;
3249 default:
3250 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3251 break;
3254 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3256 sf->mouse_moved = 0;
3257 result = TTYM_IA_SELECT;
3258 for (i = 0; i < statecount; i++)
3259 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3261 int dy = y - state[i].y + first_item;
3262 if (0 <= dy && dy < state[i].menu->count)
3264 if (!state[i].menu->submenu[dy])
3266 if (state[i].menu->panenumber[dy])
3267 result = TTYM_SUCCESS;
3268 else
3269 result = TTYM_IA_SELECT;
3271 *pane = state[i].pane - 1;
3272 *selidx = dy;
3273 /* We hit some part of a menu, so drop extra menus that
3274 have been opened. That does not include an open and
3275 active submenu. */
3276 if (i != statecount - 2
3277 || state[i].menu->submenu[dy] != state[i + 1].menu)
3278 while (i != statecount - 1)
3280 statecount--;
3281 screen_update (sf, state[statecount].screen_behind);
3282 state[statecount].screen_behind = NULL;
3284 if (i == statecount - 1 && state[i].menu->submenu[dy])
3286 tty_menu_display (state[i].menu,
3287 state[i].x,
3288 state[i].y,
3289 state[i].pane,
3290 faces, x, y, first_item, 1);
3291 state[statecount].menu = state[i].menu->submenu[dy];
3292 state[statecount].pane = state[i].menu->panenumber[dy];
3293 state[statecount].screen_behind
3294 = save_and_enable_current_matrix (sf);
3295 state[statecount].x
3296 = state[i].x + state[i].menu->width + 2;
3297 state[statecount].y = y;
3298 statecount++;
3302 tty_menu_display (state[statecount - 1].menu,
3303 state[statecount - 1].x,
3304 state[statecount - 1].y,
3305 state[statecount - 1].pane,
3306 faces, x, y, first_item, 1);
3307 /* The call to display help-echo below will move the cursor,
3308 so remember its current position as computed by
3309 tty_menu_display. */
3310 col = cursorX (tty);
3311 row = cursorY (tty);
3314 /* Display the help-echo message for the currently-selected menu
3315 item. */
3316 if ((menu_help_message || prev_menu_help_message)
3317 && menu_help_message != prev_menu_help_message)
3319 help_callback (menu_help_message,
3320 menu_help_paneno, menu_help_itemno);
3321 /* Move the cursor to the beginning of the current menu
3322 item, so that screen readers and other accessibility aids
3323 know where the active region is. */
3324 cursor_to (sf, row, col);
3325 prev_menu_help_message = menu_help_message;
3327 /* Both tty_menu_display and help_callback invoke update_end,
3328 which calls tty_show_cursor. Re-hide it, so it doesn't show
3329 through the menus. */
3330 tty_hide_cursor (tty);
3331 fflush_unlocked (tty->output);
3334 sf->mouse_moved = 0;
3335 screen_update (sf, state[0].screen_behind);
3336 while (statecount--)
3337 free_saved_screen (state[statecount].screen_behind);
3338 tty_show_cursor (tty); /* Turn cursor back on. */
3339 fflush_unlocked (tty->output);
3341 /* Clean up any mouse events that are waiting inside Emacs event queue.
3342 These events are likely to be generated before the menu was even
3343 displayed, probably because the user pressed and released the button
3344 (which invoked the menu) too quickly. If we don't remove these events,
3345 Emacs will process them after we return and surprise the user. */
3346 discard_mouse_events ();
3347 if (!kbd_buffer_events_waiting ())
3348 clear_input_pending ();
3349 SAFE_FREE ();
3350 Vinhibit_redisplay = prev_inhibit_redisplay;
3351 return result;
3354 /* Dispose of a menu. */
3356 static void
3357 tty_menu_destroy (tty_menu *menu)
3359 int i;
3360 if (menu->allocated)
3362 for (i = 0; i < menu->count; i++)
3363 if (menu->submenu[i])
3364 tty_menu_destroy (menu->submenu[i]);
3365 xfree (menu->text);
3366 xfree (menu->submenu);
3367 xfree (menu->panenumber);
3368 xfree (menu->help_text);
3370 xfree (menu);
3371 menu_help_message = prev_menu_help_message = NULL;
3374 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3376 PANE is the pane number, and ITEM is the menu item number in
3377 the menu (currently not used). */
3379 static void
3380 tty_menu_help_callback (char const *help_string, int pane, int item)
3382 Lisp_Object *first_item;
3383 Lisp_Object pane_name;
3384 Lisp_Object menu_object;
3386 first_item = XVECTOR (menu_items)->contents;
3387 if (EQ (first_item[0], Qt))
3388 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3389 else if (EQ (first_item[0], Qquote))
3390 /* This shouldn't happen, see xmenu_show. */
3391 pane_name = empty_unibyte_string;
3392 else
3393 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3395 /* (menu-item MENU-NAME PANE-NUMBER) */
3396 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3397 show_help_echo (help_string ? build_string (help_string) : Qnil,
3398 Qnil, menu_object, make_number (item));
3401 static void
3402 tty_pop_down_menu (Lisp_Object arg)
3404 tty_menu *menu = XSAVE_POINTER (arg, 0);
3405 struct buffer *orig_buffer = XSAVE_POINTER (arg, 1);
3407 block_input ();
3408 tty_menu_destroy (menu);
3409 set_buffer_internal (orig_buffer);
3410 unblock_input ();
3413 /* Return the zero-based index of the last menu-bar item on frame F. */
3414 static int
3415 tty_menu_last_menubar_item (struct frame *f)
3417 int i = 0;
3419 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3420 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3422 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3424 while (i < ASIZE (items))
3426 Lisp_Object str;
3428 str = AREF (items, i + 1);
3429 if (NILP (str))
3430 break;
3431 i += 4;
3433 i -= 4; /* Went one too far! */
3435 return i;
3438 /* Find in frame F's menu bar the menu item that is next or previous
3439 to the item at X/Y, and return that item's position in X/Y. WHICH
3440 says which one--next or previous--item to look for. X and Y are
3441 measured in character cells. This should only be called on TTY
3442 frames. */
3443 static void
3444 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3446 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3447 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3449 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3450 int last_i = tty_menu_last_menubar_item (f);
3451 int i, prev_x;
3453 /* This loop assumes a single menu-bar line, and will fail to
3454 find an item if it is not in the first line. Note that
3455 make_lispy_event in keyboard.c makes the same assumption. */
3456 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3458 Lisp_Object pos, str;
3459 int ix;
3461 str = AREF (items, i + 1);
3462 pos = AREF (items, i + 3);
3463 if (NILP (str))
3464 return;
3465 ix = XINT (pos);
3466 if (ix <= *x
3467 /* We use <= so the blank between 2 items on a TTY is
3468 considered part of the previous item. */
3469 && *x <= ix + menu_item_width (SDATA (str)))
3471 /* Found current item. Now compute the X coordinate of
3472 the previous or next item. */
3473 if (which == TTYM_NEXT)
3475 if (i < last_i)
3476 *x = XINT (AREF (items, i + 4 + 3));
3477 else
3478 *x = 0; /* Wrap around to the first item. */
3480 else if (prev_x < 0)
3482 /* Wrap around to the last item. */
3483 *x = XINT (AREF (items, last_i + 3));
3485 else
3486 *x = prev_x;
3487 return;
3489 prev_x = ix;
3494 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3495 Lisp_Object
3496 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3497 Lisp_Object title, const char **error_name)
3499 tty_menu *menu;
3500 int pane, selidx, lpane, status;
3501 Lisp_Object entry, pane_prefix;
3502 char *datap;
3503 int ulx, uly, width, height;
3504 int item_x, item_y;
3505 int dispwidth, dispheight;
3506 int i, j, lines, maxlines;
3507 int maxwidth;
3508 ptrdiff_t specpdl_count;
3510 eassert (FRAME_TERMCAP_P (f));
3512 *error_name = 0;
3513 if (menu_items_n_panes == 0)
3514 return Qnil;
3516 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3518 *error_name = "Empty menu";
3519 return Qnil;
3522 /* Make the menu on that window. */
3523 menu = tty_menu_create ();
3525 /* Don't GC while we prepare and show the menu, because we give the
3526 menu functions pointers to the contents of strings. */
3527 specpdl_count = inhibit_garbage_collection ();
3529 /* Avoid crashes if, e.g., another client will connect while we
3530 are in a menu. */
3531 temporarily_switch_to_single_kboard (f);
3533 /* Adjust coordinates to be root-window-relative. */
3534 item_x = x += f->left_pos;
3535 item_y = y += f->top_pos;
3537 /* Create all the necessary panes and their items. */
3538 USE_SAFE_ALLOCA;
3539 maxwidth = maxlines = lines = i = 0;
3540 lpane = TTYM_FAILURE;
3541 while (i < menu_items_used)
3543 if (EQ (AREF (menu_items, i), Qt))
3545 /* Create a new pane. */
3546 Lisp_Object pane_name, prefix;
3547 const char *pane_string;
3549 maxlines = max (maxlines, lines);
3550 lines = 0;
3551 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3552 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3553 pane_string = (NILP (pane_name)
3554 ? "" : SSDATA (pane_name));
3555 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3556 pane_string++;
3558 lpane = tty_menu_add_pane (menu, pane_string);
3559 if (lpane == TTYM_FAILURE)
3561 tty_menu_destroy (menu);
3562 *error_name = "Can't create pane";
3563 entry = Qnil;
3564 goto tty_menu_end;
3566 i += MENU_ITEMS_PANE_LENGTH;
3568 /* Find the width of the widest item in this pane. */
3569 j = i;
3570 while (j < menu_items_used)
3572 Lisp_Object item;
3573 item = AREF (menu_items, j);
3574 if (EQ (item, Qt))
3575 break;
3576 if (NILP (item))
3578 j++;
3579 continue;
3581 width = SBYTES (item);
3582 if (width > maxwidth)
3583 maxwidth = width;
3585 j += MENU_ITEMS_ITEM_LENGTH;
3588 /* Ignore a nil in the item list.
3589 It's meaningful only for dialog boxes. */
3590 else if (EQ (AREF (menu_items, i), Qquote))
3591 i += 1;
3592 else
3594 /* Create a new item within current pane. */
3595 Lisp_Object item_name, enable, descrip, help;
3596 char *item_data;
3597 char const *help_string;
3599 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3600 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3601 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3602 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3603 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3605 if (!NILP (descrip))
3607 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3608 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3609 for (j = SCHARS (item_name); j < maxwidth; j++)
3610 item_data[j] = ' ';
3611 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3612 item_data[j + SBYTES (descrip)] = 0;
3614 else
3615 item_data = SSDATA (item_name);
3617 if (lpane == TTYM_FAILURE
3618 || (! tty_menu_add_selection (menu, lpane, item_data,
3619 !NILP (enable), help_string)))
3621 tty_menu_destroy (menu);
3622 *error_name = "Can't add selection to menu";
3623 entry = Qnil;
3624 goto tty_menu_end;
3626 i += MENU_ITEMS_ITEM_LENGTH;
3627 lines++;
3631 maxlines = max (maxlines, lines);
3633 /* All set and ready to fly. */
3634 dispwidth = f->text_cols;
3635 dispheight = f->text_lines;
3636 x = min (x, dispwidth);
3637 y = min (y, dispheight);
3638 x = max (x, 1);
3639 y = max (y, 1);
3640 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3641 if (ulx + width > dispwidth)
3643 x -= (ulx + width) - dispwidth;
3644 ulx = dispwidth - width;
3646 if (uly + height > dispheight)
3648 y -= (uly + height) - dispheight;
3649 uly = dispheight - height;
3652 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3654 /* Move the menu away of the echo area, to avoid overwriting the
3655 menu with help echo messages or vice versa. */
3656 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3658 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3659 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3661 else
3663 y -= 2;
3664 uly -= 2;
3668 if (ulx < 0) x -= ulx;
3669 if (uly < 0) y -= uly;
3671 #if 0
3672 /* This code doesn't make sense on a TTY, since it can easily annul
3673 the adjustments above that carefully avoid truncation of the menu
3674 items. I think it was written to fix some problem that only
3675 happens on X11. */
3676 if (! for_click)
3678 /* If position was not given by a mouse click, adjust so upper left
3679 corner of the menu as a whole ends up at given coordinates. This
3680 is what x-popup-menu says in its documentation. */
3681 x += width / 2;
3682 y += 1.5 * height / (maxlines + 2);
3684 #endif
3686 pane = selidx = 0;
3688 /* We save and restore the current buffer because tty_menu_activate
3689 triggers redisplay, which switches buffers at will. */
3690 record_unwind_protect (tty_pop_down_menu,
3691 make_save_ptr_ptr (menu, current_buffer));
3693 specbind (Qoverriding_terminal_local_map,
3694 Fsymbol_value (Qtty_menu_navigation_map));
3695 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3696 tty_menu_help_callback,
3697 menuflags & MENU_KBD_NAVIGATION);
3698 entry = pane_prefix = Qnil;
3700 switch (status)
3702 case TTYM_SUCCESS:
3703 /* Find the item number SELIDX in pane number PANE. */
3704 i = 0;
3705 while (i < menu_items_used)
3707 if (EQ (AREF (menu_items, i), Qt))
3709 if (pane == 0)
3710 pane_prefix
3711 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3712 pane--;
3713 i += MENU_ITEMS_PANE_LENGTH;
3715 else
3717 if (pane == -1)
3719 if (selidx == 0)
3721 entry
3722 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3723 if (menuflags & MENU_KEYMAPS)
3725 entry = Fcons (entry, Qnil);
3726 if (!NILP (pane_prefix))
3727 entry = Fcons (pane_prefix, entry);
3729 break;
3731 selidx--;
3733 i += MENU_ITEMS_ITEM_LENGTH;
3736 break;
3738 case TTYM_NEXT:
3739 case TTYM_PREV:
3740 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3741 entry = Fcons (make_number (item_x), make_number (item_y));
3742 break;
3744 case TTYM_FAILURE:
3745 *error_name = "Can't activate menu";
3746 case TTYM_IA_SELECT:
3747 break;
3748 case TTYM_NO_SELECT:
3749 /* If the selected frame was changed while we displayed a menu,
3750 throw to top level in order to undo any temporary settings
3751 made by TTY menu code. */
3752 if (f != SELECTED_FRAME ())
3753 Ftop_level ();
3754 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3755 the menu was invoked with a mouse event as POSITION). */
3756 if (!(menuflags & MENU_FOR_CLICK))
3757 quit ();
3758 break;
3761 tty_menu_end:
3763 SAFE_FREE ();
3764 unbind_to (specpdl_count, Qnil);
3765 return entry;
3768 #endif /* !MSDOS */
3771 #ifndef MSDOS
3772 /***********************************************************************
3773 Initialization
3774 ***********************************************************************/
3776 /* Initialize the tty-dependent part of frame F. The frame must
3777 already have its device initialized. */
3779 void
3780 create_tty_output (struct frame *f)
3782 struct tty_output *t = xzalloc (sizeof *t);
3784 eassert (FRAME_TERMCAP_P (f));
3786 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3788 f->output_data.tty = t;
3791 /* Delete frame F's face cache, and its tty-dependent part. */
3793 static void
3794 tty_free_frame_resources (struct frame *f)
3796 eassert (FRAME_TERMCAP_P (f));
3797 free_frame_faces (f);
3798 xfree (f->output_data.tty);
3801 #else /* MSDOS */
3803 /* Delete frame F's face cache. */
3805 static void
3806 tty_free_frame_resources (struct frame *f)
3808 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3809 free_frame_faces (f);
3811 #endif /* MSDOS */
3813 /* Reset the hooks in TERMINAL. */
3815 static void
3816 clear_tty_hooks (struct terminal *terminal)
3818 terminal->rif = 0;
3819 terminal->cursor_to_hook = 0;
3820 terminal->raw_cursor_to_hook = 0;
3821 terminal->clear_to_end_hook = 0;
3822 terminal->clear_frame_hook = 0;
3823 terminal->clear_end_of_line_hook = 0;
3824 terminal->ins_del_lines_hook = 0;
3825 terminal->insert_glyphs_hook = 0;
3826 terminal->write_glyphs_hook = 0;
3827 terminal->delete_glyphs_hook = 0;
3828 terminal->ring_bell_hook = 0;
3829 terminal->reset_terminal_modes_hook = 0;
3830 terminal->set_terminal_modes_hook = 0;
3831 terminal->update_begin_hook = 0;
3832 terminal->update_end_hook = 0;
3833 terminal->set_terminal_window_hook = 0;
3834 terminal->mouse_position_hook = 0;
3835 terminal->frame_rehighlight_hook = 0;
3836 terminal->frame_raise_lower_hook = 0;
3837 terminal->fullscreen_hook = 0;
3838 terminal->menu_show_hook = 0;
3839 terminal->set_vertical_scroll_bar_hook = 0;
3840 terminal->set_horizontal_scroll_bar_hook = 0;
3841 terminal->condemn_scroll_bars_hook = 0;
3842 terminal->redeem_scroll_bar_hook = 0;
3843 terminal->judge_scroll_bars_hook = 0;
3844 terminal->read_socket_hook = 0;
3845 terminal->frame_up_to_date_hook = 0;
3847 /* Leave these two set, or suspended frames are not deleted
3848 correctly. */
3849 terminal->delete_frame_hook = &tty_free_frame_resources;
3850 terminal->delete_terminal_hook = &delete_tty;
3853 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3855 static void
3856 set_tty_hooks (struct terminal *terminal)
3858 terminal->cursor_to_hook = &tty_cursor_to;
3859 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3860 terminal->clear_to_end_hook = &tty_clear_to_end;
3861 terminal->clear_frame_hook = &tty_clear_frame;
3862 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3863 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3864 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3865 terminal->write_glyphs_hook = &tty_write_glyphs;
3866 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3867 terminal->ring_bell_hook = &tty_ring_bell;
3868 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3869 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3870 terminal->update_end_hook = &tty_update_end;
3871 #ifdef MSDOS
3872 terminal->menu_show_hook = &x_menu_show;
3873 #else
3874 terminal->menu_show_hook = &tty_menu_show;
3875 #endif
3876 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3877 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3878 terminal->delete_frame_hook = &tty_free_frame_resources;
3879 terminal->delete_terminal_hook = &delete_tty;
3880 /* Other hooks are NULL by default. */
3883 /* If FD is the controlling terminal, drop it. */
3884 static void
3885 dissociate_if_controlling_tty (int fd)
3887 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3888 so dissociate it by invoking setsid. */
3889 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3891 #ifdef TIOCNOTTY
3892 /* setsid failed, presumably because Emacs is already a process
3893 group leader. Fall back on the obsolescent way to dissociate
3894 a controlling tty. */
3895 sigset_t oldset;
3896 block_tty_out_signal (&oldset);
3897 ioctl (fd, TIOCNOTTY, 0);
3898 unblock_tty_out_signal (&oldset);
3899 #endif
3903 /* Create a termcap display on the tty device with the given name and
3904 type.
3906 If NAME is NULL, then use the controlling tty, i.e., DEV_TTY.
3907 Otherwise NAME should be a path to the tty device file,
3908 e.g. "/dev/pts/7".
3910 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3912 If MUST_SUCCEED is true, then all errors are fatal. */
3914 struct terminal *
3915 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3917 struct tty_display_info *tty = NULL;
3918 struct terminal *terminal = NULL;
3919 #ifndef DOS_NT
3920 char *area;
3921 char **address = &area;
3922 int status;
3923 sigset_t oldset;
3924 bool ctty = false; /* True if asked to open controlling tty. */
3925 #endif
3927 if (!terminal_type)
3928 maybe_fatal (must_succeed, 0,
3929 "Unknown terminal type",
3930 "Unknown terminal type");
3932 if (name == NULL)
3933 name = DEV_TTY;
3934 #ifndef DOS_NT
3935 if (!strcmp (name, DEV_TTY))
3936 ctty = 1;
3937 #endif
3939 /* If we already have a terminal on the given device, use that. If
3940 all such terminals are suspended, create a new one instead. */
3941 /* XXX Perhaps this should be made explicit by having init_tty
3942 always create a new terminal and separating terminal and frame
3943 creation on Lisp level. */
3944 terminal = get_named_terminal (name);
3945 if (terminal)
3946 return terminal;
3948 terminal = create_terminal (output_termcap, NULL);
3949 #ifdef MSDOS
3950 if (been_here > 0)
3951 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3952 name, "");
3953 been_here = 1;
3954 tty = &the_only_display_info;
3955 #else
3956 tty = xzalloc (sizeof *tty);
3957 #endif
3958 tty->top_frame = Qnil;
3959 tty->next = tty_list;
3960 tty_list = tty;
3962 terminal->display_info.tty = tty;
3963 tty->terminal = terminal;
3965 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3966 Wcm_clear (tty);
3968 encode_terminal_src_size = 0;
3969 encode_terminal_dst_size = 0;
3972 #ifndef DOS_NT
3973 set_tty_hooks (terminal);
3976 /* Open the terminal device. */
3978 /* If !ctty, don't recognize it as our controlling terminal, and
3979 don't make it the controlling tty if we don't have one now.
3981 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3982 defined on Hurd. On other systems, we need to explicitly
3983 dissociate ourselves from the controlling tty when we want to
3984 open a frame on the same terminal. */
3985 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3986 int fd = emacs_open (name, flags, 0);
3987 tty->input = tty->output
3988 = ((fd < 0 || ! isatty (fd))
3989 ? NULL
3990 : fdopen (fd, "w+"));
3992 if (! tty->input)
3994 char const *diagnostic
3995 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3996 emacs_close (fd);
3997 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4000 tty->name = xstrdup (name);
4001 terminal->name = xstrdup (name);
4003 if (!O_IGNORE_CTTY && !ctty)
4004 dissociate_if_controlling_tty (fd);
4007 tty->type = xstrdup (terminal_type);
4009 add_keyboard_wait_descriptor (fileno (tty->input));
4011 Wcm_clear (tty);
4013 /* On some systems, tgetent tries to access the controlling
4014 terminal. */
4015 block_tty_out_signal (&oldset);
4016 status = tgetent (tty->termcap_term_buffer, terminal_type);
4017 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4018 emacs_abort ();
4019 unblock_tty_out_signal (&oldset);
4021 if (status < 0)
4023 #ifdef TERMINFO
4024 maybe_fatal (must_succeed, terminal,
4025 "Cannot open terminfo database file",
4026 "Cannot open terminfo database file");
4027 #else
4028 maybe_fatal (must_succeed, terminal,
4029 "Cannot open termcap database file",
4030 "Cannot open termcap database file");
4031 #endif
4033 if (status == 0)
4035 maybe_fatal (must_succeed, terminal,
4036 "Terminal type %s is not defined",
4037 "Terminal type %s is not defined.\n\
4038 If that is not the actual type of terminal you have,\n\
4039 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4040 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4041 #ifdef TERMINFO
4042 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4043 #else
4044 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4045 #endif
4046 terminal_type);
4049 area = tty->termcap_strings_buffer;
4050 tty->TS_ins_line = tgetstr ("al", address);
4051 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4052 tty->TS_bell = tgetstr ("bl", address);
4053 BackTab (tty) = tgetstr ("bt", address);
4054 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4055 tty->TS_clr_line = tgetstr ("ce", address);
4056 tty->TS_clr_frame = tgetstr ("cl", address);
4057 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4058 AbsPosition (tty) = tgetstr ("cm", address);
4059 CR (tty) = tgetstr ("cr", address);
4060 tty->TS_set_scroll_region = tgetstr ("cs", address);
4061 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4062 RowPosition (tty) = tgetstr ("cv", address);
4063 tty->TS_del_char = tgetstr ("dc", address);
4064 tty->TS_del_multi_chars = tgetstr ("DC", address);
4065 tty->TS_del_line = tgetstr ("dl", address);
4066 tty->TS_del_multi_lines = tgetstr ("DL", address);
4067 tty->TS_delete_mode = tgetstr ("dm", address);
4068 tty->TS_end_delete_mode = tgetstr ("ed", address);
4069 tty->TS_end_insert_mode = tgetstr ("ei", address);
4070 Home (tty) = tgetstr ("ho", address);
4071 tty->TS_ins_char = tgetstr ("ic", address);
4072 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4073 tty->TS_insert_mode = tgetstr ("im", address);
4074 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4075 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4076 tty->TS_keypad_mode = tgetstr ("ks", address);
4077 LastLine (tty) = tgetstr ("ll", address);
4078 Right (tty) = tgetstr ("nd", address);
4079 Down (tty) = tgetstr ("do", address);
4080 if (!Down (tty))
4081 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4082 if (tgetflag ("bs"))
4083 Left (tty) = "\b"; /* Can't possibly be longer! */
4084 else /* (Actually, "bs" is obsolete...) */
4085 Left (tty) = tgetstr ("le", address);
4086 if (!Left (tty))
4087 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4088 tty->TS_pad_char = tgetstr ("pc", address);
4089 tty->TS_repeat = tgetstr ("rp", address);
4090 tty->TS_end_standout_mode = tgetstr ("se", address);
4091 tty->TS_fwd_scroll = tgetstr ("sf", address);
4092 tty->TS_standout_mode = tgetstr ("so", address);
4093 tty->TS_rev_scroll = tgetstr ("sr", address);
4094 tty->Wcm->cm_tab = tgetstr ("ta", address);
4095 tty->TS_end_termcap_modes = tgetstr ("te", address);
4096 tty->TS_termcap_modes = tgetstr ("ti", address);
4097 Up (tty) = tgetstr ("up", address);
4098 tty->TS_visible_bell = tgetstr ("vb", address);
4099 tty->TS_cursor_normal = tgetstr ("ve", address);
4100 tty->TS_cursor_visible = tgetstr ("vs", address);
4101 tty->TS_cursor_invisible = tgetstr ("vi", address);
4102 tty->TS_set_window = tgetstr ("wi", address);
4104 tty->TS_enter_underline_mode = tgetstr ("us", address);
4105 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4106 tty->TS_enter_bold_mode = tgetstr ("md", address);
4107 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4108 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4109 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4110 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4111 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4112 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4114 MultiUp (tty) = tgetstr ("UP", address);
4115 MultiDown (tty) = tgetstr ("DO", address);
4116 MultiLeft (tty) = tgetstr ("LE", address);
4117 MultiRight (tty) = tgetstr ("RI", address);
4119 /* SVr4/ANSI color support. If "op" isn't available, don't support
4120 color because we can't switch back to the default foreground and
4121 background. */
4122 tty->TS_orig_pair = tgetstr ("op", address);
4123 if (tty->TS_orig_pair)
4125 tty->TS_set_foreground = tgetstr ("AF", address);
4126 tty->TS_set_background = tgetstr ("AB", address);
4127 if (!tty->TS_set_foreground)
4129 /* SVr4. */
4130 tty->TS_set_foreground = tgetstr ("Sf", address);
4131 tty->TS_set_background = tgetstr ("Sb", address);
4134 tty->TN_max_colors = tgetnum ("Co");
4136 #ifdef TERMINFO
4137 /* Non-standard support for 24-bit colors. */
4139 const char *fg = tigetstr ("setf24");
4140 const char *bg = tigetstr ("setb24");
4141 if (fg && bg
4142 && fg != (char *) (intptr_t) -1
4143 && bg != (char *) (intptr_t) -1)
4145 tty->TS_set_foreground = fg;
4146 tty->TS_set_background = bg;
4147 tty->TN_max_colors = 16777216;
4150 #endif
4152 tty->TN_no_color_video = tgetnum ("NC");
4153 if (tty->TN_no_color_video == -1)
4154 tty->TN_no_color_video = 0;
4157 tty_default_color_capabilities (tty, 1);
4159 MagicWrap (tty) = tgetflag ("xn");
4160 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4161 the former flag imply the latter. */
4162 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4163 tty->memory_below_frame = tgetflag ("db");
4164 tty->TF_hazeltine = tgetflag ("hz");
4165 tty->must_write_spaces = tgetflag ("in");
4166 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4167 tty->TF_insmode_motion = tgetflag ("mi");
4168 tty->TF_standout_motion = tgetflag ("ms");
4169 tty->TF_underscore = tgetflag ("ul");
4170 tty->TF_teleray = tgetflag ("xt");
4172 #else /* DOS_NT */
4173 #ifdef WINDOWSNT
4175 struct frame *f = XFRAME (selected_frame);
4176 int height, width;
4178 initialize_w32_display (terminal, &width, &height);
4180 FrameRows (tty) = height;
4181 FrameCols (tty) = width;
4182 tty->specified_window = height;
4184 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4185 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4186 tty->char_ins_del_ok = 1;
4187 baud_rate = 19200;
4189 #else /* MSDOS */
4191 int height, width;
4192 if (strcmp (terminal_type, "internal") == 0)
4193 terminal->type = output_msdos_raw;
4194 initialize_msdos_display (terminal);
4196 get_tty_size (fileno (tty->input), &width, &height);
4197 FrameCols (tty) = width;
4198 FrameRows (tty) = height;
4199 tty->char_ins_del_ok = 0;
4200 init_baud_rate (fileno (tty->input));
4202 #endif /* MSDOS */
4203 tty->output = stdout;
4204 tty->input = stdin;
4205 /* The following two are inaccessible from w32console.c. */
4206 terminal->delete_frame_hook = &tty_free_frame_resources;
4207 terminal->delete_terminal_hook = &delete_tty;
4209 tty->name = xstrdup (name);
4210 terminal->name = xstrdup (name);
4211 tty->type = xstrdup (terminal_type);
4213 add_keyboard_wait_descriptor (0);
4215 tty->delete_in_insert_mode = 1;
4217 UseTabs (tty) = 0;
4218 tty->scroll_region_ok = 0;
4220 /* Seems to insert lines when it's not supposed to, messing up the
4221 display. In doing a trace, it didn't seem to be called much, so I
4222 don't think we're losing anything by turning it off. */
4223 tty->line_ins_del_ok = 0;
4225 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4226 #endif /* DOS_NT */
4228 #ifdef HAVE_GPM
4229 terminal->mouse_position_hook = term_mouse_position;
4230 tty->mouse_highlight.mouse_face_window = Qnil;
4231 #endif
4233 terminal->kboard = allocate_kboard (Qnil);
4234 terminal->kboard->reference_count++;
4235 /* Don't let the initial kboard remain current longer than necessary.
4236 That would cause problems if a file loaded on startup tries to
4237 prompt in the mini-buffer. */
4238 if (current_kboard == initial_kboard)
4239 current_kboard = terminal->kboard;
4240 #ifndef DOS_NT
4241 term_get_fkeys (address, terminal->kboard);
4243 /* Get frame size from system, or else from termcap. */
4245 int height, width;
4246 get_tty_size (fileno (tty->input), &width, &height);
4247 FrameCols (tty) = width;
4248 FrameRows (tty) = height;
4251 if (FrameCols (tty) <= 0)
4252 FrameCols (tty) = tgetnum ("co");
4253 if (FrameRows (tty) <= 0)
4254 FrameRows (tty) = tgetnum ("li");
4256 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4257 maybe_fatal (must_succeed, terminal,
4258 "Screen size %dx%d is too small",
4259 "Screen size %dx%d is too small",
4260 FrameCols (tty), FrameRows (tty));
4262 TabWidth (tty) = tgetnum ("tw");
4264 if (!tty->TS_bell)
4265 tty->TS_bell = "\07";
4267 if (!tty->TS_fwd_scroll)
4268 tty->TS_fwd_scroll = Down (tty);
4270 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4272 if (TabWidth (tty) < 0)
4273 TabWidth (tty) = 8;
4275 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4276 and newer termcap doc does not seem to say there is a default.
4277 if (!tty->Wcm->cm_tab)
4278 tty->Wcm->cm_tab = "\t";
4281 /* We don't support standout modes that use `magic cookies', so
4282 turn off any that do. */
4283 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4285 tty->TS_standout_mode = 0;
4286 tty->TS_end_standout_mode = 0;
4288 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4290 tty->TS_enter_underline_mode = 0;
4291 tty->TS_exit_underline_mode = 0;
4294 /* If there's no standout mode, try to use underlining instead. */
4295 if (tty->TS_standout_mode == 0)
4297 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4298 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4301 /* If no `se' string, try using a `me' string instead.
4302 If that fails, we can't use standout mode at all. */
4303 if (tty->TS_end_standout_mode == 0)
4305 char *s = tgetstr ("me", address);
4306 if (s != 0)
4307 tty->TS_end_standout_mode = s;
4308 else
4309 tty->TS_standout_mode = 0;
4312 if (tty->TF_teleray)
4314 tty->Wcm->cm_tab = 0;
4315 /* We can't support standout mode, because it uses magic cookies. */
4316 tty->TS_standout_mode = 0;
4317 /* But that means we cannot rely on ^M to go to column zero! */
4318 CR (tty) = 0;
4319 /* LF can't be trusted either -- can alter hpos. */
4320 /* If move at column 0 thru a line with TS_standout_mode. */
4321 Down (tty) = 0;
4324 tty->specified_window = FrameRows (tty);
4326 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4328 maybe_fatal (must_succeed, terminal,
4329 "Terminal type \"%s\" is not powerful enough to run Emacs",
4330 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4331 It lacks the ability to position the cursor.\n\
4332 If that is not the actual type of terminal you have,\n\
4333 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4334 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4335 # ifdef TERMINFO
4336 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4337 # else /* TERMCAP */
4338 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4339 # endif /* TERMINFO */
4340 terminal_type);
4343 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4344 maybe_fatal (must_succeed, terminal,
4345 "Could not determine the frame size",
4346 "Could not determine the frame size");
4348 tty->delete_in_insert_mode
4349 = tty->TS_delete_mode && tty->TS_insert_mode
4350 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4352 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4354 tty->scroll_region_ok
4355 = (tty->Wcm->cm_abs
4356 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4358 tty->line_ins_del_ok
4359 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4360 && (tty->TS_del_line || tty->TS_del_multi_lines))
4361 || (tty->scroll_region_ok
4362 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4364 tty->char_ins_del_ok
4365 = ((tty->TS_ins_char || tty->TS_insert_mode
4366 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4367 && (tty->TS_del_char || tty->TS_del_multi_chars));
4369 init_baud_rate (fileno (tty->input));
4371 #endif /* not DOS_NT */
4373 /* Init system terminal modes (RAW or CBREAK, etc.). */
4374 init_sys_modes (tty);
4376 return terminal;
4380 static void
4381 vfatal (const char *str, va_list ap)
4383 fprintf (stderr, "emacs: ");
4384 vfprintf (stderr, str, ap);
4385 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4386 fprintf (stderr, "\n");
4387 fflush (stderr);
4388 exit (1);
4392 /* Auxiliary error-handling function for init_tty.
4393 Delete TERMINAL, then call error or fatal with str1 or str2,
4394 respectively, according to whether MUST_SUCCEED is true. */
4396 static void
4397 maybe_fatal (bool must_succeed, struct terminal *terminal,
4398 const char *str1, const char *str2, ...)
4400 va_list ap;
4401 va_start (ap, str2);
4402 if (terminal)
4403 delete_tty (terminal);
4405 if (must_succeed)
4406 vfatal (str2, ap);
4407 else
4408 verror (str1, ap);
4411 void
4412 fatal (const char *str, ...)
4414 va_list ap;
4415 va_start (ap, str);
4416 vfatal (str, ap);
4421 /* Delete the given tty terminal, closing all frames on it. */
4423 static void
4424 delete_tty (struct terminal *terminal)
4426 struct tty_display_info *tty;
4428 /* Protect against recursive calls. delete_frame in
4429 delete_terminal calls us back when it deletes our last frame. */
4430 if (!terminal->name)
4431 return;
4433 eassert (terminal->type == output_termcap);
4435 tty = terminal->display_info.tty;
4437 if (tty == tty_list)
4438 tty_list = tty->next;
4439 else
4441 struct tty_display_info *p;
4442 for (p = tty_list; p && p->next != tty; p = p->next)
4445 if (! p)
4446 /* This should not happen. */
4447 emacs_abort ();
4449 p->next = tty->next;
4450 tty->next = 0;
4453 /* reset_sys_modes needs a valid device, so this call needs to be
4454 before delete_terminal. */
4455 reset_sys_modes (tty);
4457 delete_terminal (terminal);
4459 xfree (tty->name);
4460 xfree (tty->type);
4462 if (tty->input)
4464 delete_keyboard_wait_descriptor (fileno (tty->input));
4465 if (tty->input != stdin)
4466 fclose (tty->input);
4468 if (tty->output && tty->output != stdout && tty->output != tty->input)
4469 fclose (tty->output);
4470 if (tty->termscript)
4471 fclose (tty->termscript);
4473 xfree (tty->old_tty);
4474 xfree (tty->Wcm);
4475 xfree (tty);
4478 void
4479 syms_of_term (void)
4481 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4482 doc: /* Non-nil means the system uses terminfo rather than termcap.
4483 This variable can be used by terminal emulator packages. */);
4484 #ifdef TERMINFO
4485 system_uses_terminfo = 1;
4486 #else
4487 system_uses_terminfo = 0;
4488 #endif
4490 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4491 doc: /* Functions run after suspending a tty.
4492 The functions are run with one argument, the terminal object to be suspended.
4493 See `suspend-tty'. */);
4494 Vsuspend_tty_functions = Qnil;
4497 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4498 doc: /* Functions run after resuming a tty.
4499 The functions are run with one argument, the terminal object that was revived.
4500 See `resume-tty'. */);
4501 Vresume_tty_functions = Qnil;
4503 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4504 doc: /* Non-nil means to make the cursor very visible.
4505 This only has an effect when running in a text terminal.
4506 What means \"very visible\" is up to your terminal. It may make the cursor
4507 bigger, or it may make it blink, or it may do nothing at all. */);
4508 visible_cursor = 1;
4510 defsubr (&Stty_display_color_p);
4511 defsubr (&Stty_display_color_cells);
4512 defsubr (&Stty_no_underline);
4513 defsubr (&Stty_type);
4514 defsubr (&Scontrolling_tty_p);
4515 defsubr (&Stty_top_frame);
4516 defsubr (&Ssuspend_tty);
4517 defsubr (&Sresume_tty);
4518 #ifdef HAVE_GPM
4519 defsubr (&Sgpm_mouse_start);
4520 defsubr (&Sgpm_mouse_stop);
4521 #endif /* HAVE_GPM */
4523 #ifndef DOS_NT
4524 default_orig_pair = NULL;
4525 default_set_foreground = NULL;
4526 default_set_background = NULL;
4527 #endif /* !DOS_NT */
4529 encode_terminal_src = NULL;
4530 encode_terminal_dst = NULL;
4532 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4533 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4535 #ifndef MSDOS
4536 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4537 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4538 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4539 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4540 DEFSYM (Qtty_menu_select, "tty-menu-select");
4541 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4542 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4543 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4544 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4545 #endif