* etc/NEWS (Incompatible Lisp Changes): Document new restriction on `setq'.
[emacs.git] / src / term.c
blob6ab611d51e20e6fc326180e1b8572259be07bf4d
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2015 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #ifdef MSDOS
48 #include "msdos.h"
49 static int been_here = -1;
50 #endif
52 #ifdef USE_X_TOOLKIT
53 #include "../lwlib/lwlib.h"
54 #endif
56 #include "cm.h"
57 #include "menu.h"
59 /* The name of the default console device. */
60 #ifdef WINDOWSNT
61 #define DEV_TTY "CONOUT$"
62 #include "w32term.h"
63 #else
64 #define DEV_TTY "/dev/tty"
65 #endif
67 static void tty_set_scroll_region (struct frame *f, int start, int stop);
68 static void turn_on_face (struct frame *, int face_id);
69 static void turn_off_face (struct frame *, int face_id);
70 static void tty_turn_off_highlight (struct tty_display_info *);
71 static void tty_show_cursor (struct tty_display_info *);
72 static void tty_hide_cursor (struct tty_display_info *);
73 static void tty_background_highlight (struct tty_display_info *tty);
74 static void clear_tty_hooks (struct terminal *terminal);
75 static void set_tty_hooks (struct terminal *terminal);
76 static void dissociate_if_controlling_tty (int fd);
77 static void delete_tty (struct terminal *);
78 static _Noreturn void maybe_fatal (bool, struct terminal *,
79 const char *, const char *, ...)
80 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
81 static _Noreturn void vfatal (const char *str, va_list ap)
82 ATTRIBUTE_FORMAT_PRINTF (1, 0);
85 #define OUTPUT(tty, a) \
86 emacs_tputs ((tty), a, \
87 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
88 cmputc)
90 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
91 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
93 #define OUTPUT_IF(tty, a) \
94 do { \
95 if (a) \
96 OUTPUT (tty, a); \
97 } while (0)
99 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
101 /* Display space properties. */
103 /* Chain of all tty device parameters. */
104 struct tty_display_info *tty_list;
106 /* Meaning of bits in no_color_video. Each bit set means that the
107 corresponding attribute cannot be combined with colors. */
109 enum no_color_bit
111 NC_STANDOUT = 1 << 0,
112 NC_UNDERLINE = 1 << 1,
113 NC_REVERSE = 1 << 2,
114 NC_ITALIC = 1 << 3,
115 NC_DIM = 1 << 4,
116 NC_BOLD = 1 << 5,
117 NC_INVIS = 1 << 6,
118 NC_PROTECT = 1 << 7
121 /* internal state */
123 /* The largest frame width in any call to calculate_costs. */
125 static int max_frame_cols;
129 #ifdef HAVE_GPM
130 #include <sys/fcntl.h>
132 /* The device for which we have enabled gpm support (or NULL). */
133 struct tty_display_info *gpm_tty = NULL;
135 /* Last recorded mouse coordinates. */
136 static int last_mouse_x, last_mouse_y;
137 #endif /* HAVE_GPM */
139 /* Ring the bell on a tty. */
141 static void
142 tty_ring_bell (struct frame *f)
144 struct tty_display_info *tty = FRAME_TTY (f);
146 if (tty->output)
148 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
149 ? tty->TS_visible_bell
150 : tty->TS_bell));
151 fflush (tty->output);
155 /* Set up termcap modes for Emacs. */
157 static void
158 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
160 Lisp_Object lisp_terminal;
161 Lisp_Object extra_codes;
162 struct tty_display_info *tty = terminal->display_info.tty;
164 XSETTERMINAL (lisp_terminal, terminal);
165 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
166 CONSP (extra_codes);
167 extra_codes = XCDR (extra_codes))
169 Lisp_Object string = XCAR (extra_codes);
170 if (STRINGP (string))
172 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
173 if (tty->termscript)
174 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
179 static void
180 tty_set_terminal_modes (struct terminal *terminal)
182 struct tty_display_info *tty = terminal->display_info.tty;
184 if (tty->output)
186 if (tty->TS_termcap_modes)
187 OUTPUT (tty, tty->TS_termcap_modes);
188 else
190 /* Output enough newlines to scroll all the old screen contents
191 off the screen, so it won't be overwritten and lost. */
192 int i;
193 current_tty = tty;
194 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
195 cmputc ('\n');
198 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
199 OUTPUT_IF (tty, tty->TS_keypad_mode);
200 losecursor (tty);
201 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
202 fflush (tty->output);
206 /* Reset termcap modes before exiting Emacs. */
208 static void
209 tty_reset_terminal_modes (struct terminal *terminal)
211 struct tty_display_info *tty = terminal->display_info.tty;
213 if (tty->output)
215 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
216 tty_turn_off_highlight (tty);
217 tty_turn_off_insert (tty);
218 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
219 OUTPUT_IF (tty, tty->TS_cursor_normal);
220 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
221 OUTPUT_IF (tty, tty->TS_orig_pair);
222 /* Output raw CR so kernel can track the cursor hpos. */
223 current_tty = tty;
224 cmputc ('\r');
225 fflush (tty->output);
229 /* Flag the end of a display update on a termcap terminal. */
231 static void
232 tty_update_end (struct frame *f)
234 struct tty_display_info *tty = FRAME_TTY (f);
236 if (!XWINDOW (selected_window)->cursor_off_p)
237 tty_show_cursor (tty);
238 tty_turn_off_insert (tty);
239 tty_background_highlight (tty);
240 fflush (tty->output);
243 /* The implementation of set_terminal_window for termcap frames. */
245 static void
246 tty_set_terminal_window (struct frame *f, int size)
248 struct tty_display_info *tty = FRAME_TTY (f);
250 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
251 if (FRAME_SCROLL_REGION_OK (f))
252 tty_set_scroll_region (f, 0, tty->specified_window);
255 static void
256 tty_set_scroll_region (struct frame *f, int start, int stop)
258 char *buf;
259 struct tty_display_info *tty = FRAME_TTY (f);
261 if (tty->TS_set_scroll_region)
262 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
263 else if (tty->TS_set_scroll_region_1)
264 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
265 FRAME_TOTAL_LINES (f), start,
266 FRAME_TOTAL_LINES (f) - stop,
267 FRAME_TOTAL_LINES (f));
268 else
269 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
271 OUTPUT (tty, buf);
272 xfree (buf);
273 losecursor (tty);
277 static void
278 tty_turn_on_insert (struct tty_display_info *tty)
280 if (!tty->insert_mode)
281 OUTPUT (tty, tty->TS_insert_mode);
282 tty->insert_mode = 1;
285 void
286 tty_turn_off_insert (struct tty_display_info *tty)
288 if (tty->insert_mode)
289 OUTPUT (tty, tty->TS_end_insert_mode);
290 tty->insert_mode = 0;
293 /* Handle highlighting. */
295 static void
296 tty_turn_off_highlight (struct tty_display_info *tty)
298 if (tty->standout_mode)
299 OUTPUT_IF (tty, tty->TS_end_standout_mode);
300 tty->standout_mode = 0;
303 static void
304 tty_turn_on_highlight (struct tty_display_info *tty)
306 if (!tty->standout_mode)
307 OUTPUT_IF (tty, tty->TS_standout_mode);
308 tty->standout_mode = 1;
311 static void
312 tty_toggle_highlight (struct tty_display_info *tty)
314 if (tty->standout_mode)
315 tty_turn_off_highlight (tty);
316 else
317 tty_turn_on_highlight (tty);
321 /* Make cursor invisible. */
323 static void
324 tty_hide_cursor (struct tty_display_info *tty)
326 if (tty->cursor_hidden == 0)
328 tty->cursor_hidden = 1;
329 #ifdef WINDOWSNT
330 w32con_hide_cursor ();
331 #else
332 OUTPUT_IF (tty, tty->TS_cursor_invisible);
333 #endif
338 /* Ensure that cursor is visible. */
340 static void
341 tty_show_cursor (struct tty_display_info *tty)
343 if (tty->cursor_hidden)
345 tty->cursor_hidden = 0;
346 #ifdef WINDOWSNT
347 w32con_show_cursor ();
348 #else
349 OUTPUT_IF (tty, tty->TS_cursor_normal);
350 if (visible_cursor)
351 OUTPUT_IF (tty, tty->TS_cursor_visible);
352 #endif
357 /* Set standout mode to the state it should be in for
358 empty space inside windows. What this is,
359 depends on the user option inverse-video. */
361 static void
362 tty_background_highlight (struct tty_display_info *tty)
364 if (inverse_video)
365 tty_turn_on_highlight (tty);
366 else
367 tty_turn_off_highlight (tty);
370 /* Set standout mode to the mode specified for the text to be output. */
372 static void
373 tty_highlight_if_desired (struct tty_display_info *tty)
375 if (inverse_video)
376 tty_turn_on_highlight (tty);
377 else
378 tty_turn_off_highlight (tty);
382 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
383 frame-relative coordinates. */
385 static void
386 tty_cursor_to (struct frame *f, int vpos, int hpos)
388 struct tty_display_info *tty = FRAME_TTY (f);
390 /* Detect the case where we are called from reset_sys_modes
391 and the costs have never been calculated. Do nothing. */
392 if (! tty->costs_set)
393 return;
395 if (curY (tty) == vpos
396 && curX (tty) == hpos)
397 return;
398 if (!tty->TF_standout_motion)
399 tty_background_highlight (tty);
400 if (!tty->TF_insmode_motion)
401 tty_turn_off_insert (tty);
402 cmgoto (tty, vpos, hpos);
405 /* Similar but don't take any account of the wasted characters. */
407 static void
408 tty_raw_cursor_to (struct frame *f, int row, int col)
410 struct tty_display_info *tty = FRAME_TTY (f);
412 if (curY (tty) == row
413 && curX (tty) == col)
414 return;
415 if (!tty->TF_standout_motion)
416 tty_background_highlight (tty);
417 if (!tty->TF_insmode_motion)
418 tty_turn_off_insert (tty);
419 cmgoto (tty, row, col);
422 /* Erase operations */
424 /* Clear from cursor to end of frame on a termcap device. */
426 static void
427 tty_clear_to_end (struct frame *f)
429 register int i;
430 struct tty_display_info *tty = FRAME_TTY (f);
432 if (tty->TS_clr_to_bottom)
434 tty_background_highlight (tty);
435 OUTPUT (tty, tty->TS_clr_to_bottom);
437 else
439 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
441 cursor_to (f, i, 0);
442 clear_end_of_line (f, FRAME_COLS (f));
447 /* Clear an entire termcap frame. */
449 static void
450 tty_clear_frame (struct frame *f)
452 struct tty_display_info *tty = FRAME_TTY (f);
454 if (tty->TS_clr_frame)
456 tty_background_highlight (tty);
457 OUTPUT (tty, tty->TS_clr_frame);
458 cmat (tty, 0, 0);
460 else
462 cursor_to (f, 0, 0);
463 clear_to_end (f);
467 /* An implementation of clear_end_of_line for termcap frames.
469 Note that the cursor may be moved, on terminals lacking a `ce' string. */
471 static void
472 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
474 register int i;
475 struct tty_display_info *tty = FRAME_TTY (f);
477 /* Detect the case where we are called from reset_sys_modes
478 and the costs have never been calculated. Do nothing. */
479 if (! tty->costs_set)
480 return;
482 if (curX (tty) >= first_unused_hpos)
483 return;
484 tty_background_highlight (tty);
485 if (tty->TS_clr_line)
487 OUTPUT1 (tty, tty->TS_clr_line);
489 else
490 { /* have to do it the hard way */
491 tty_turn_off_insert (tty);
493 /* Do not write in last row last col with Auto-wrap on. */
494 if (AutoWrap (tty)
495 && curY (tty) == FrameRows (tty) - 1
496 && first_unused_hpos == FrameCols (tty))
497 first_unused_hpos--;
499 for (i = curX (tty); i < first_unused_hpos; i++)
501 if (tty->termscript)
502 fputc (' ', tty->termscript);
503 fputc (' ', tty->output);
505 cmplus (tty, first_unused_hpos - curX (tty));
509 /* Buffers to store the source and result of code conversion for terminal. */
510 static unsigned char *encode_terminal_src;
511 static unsigned char *encode_terminal_dst;
512 /* Allocated sizes of the above buffers. */
513 static ptrdiff_t encode_terminal_src_size;
514 static ptrdiff_t encode_terminal_dst_size;
516 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
517 Set CODING->produced to the byte-length of the resulting byte
518 sequence, and return a pointer to that byte sequence. */
520 unsigned char *
521 encode_terminal_code (struct glyph *src, int src_len,
522 struct coding_system *coding)
524 struct glyph *src_end = src + src_len;
525 unsigned char *buf;
526 ptrdiff_t nchars, nbytes, required;
527 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
528 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
529 Lisp_Object charset_list;
531 /* Allocate sufficient size of buffer to store all characters in
532 multibyte-form. But, it may be enlarged on demand if
533 Vglyph_table contains a string or a composite glyph is
534 encountered. */
535 if (INT_MULTIPLY_WRAPV (src_len, MAX_MULTIBYTE_LENGTH, &required))
536 memory_full (SIZE_MAX);
537 if (encode_terminal_src_size < required)
538 encode_terminal_src = xpalloc (encode_terminal_src,
539 &encode_terminal_src_size,
540 required - encode_terminal_src_size,
541 -1, sizeof *encode_terminal_src);
543 charset_list = coding_charset_list (coding);
545 buf = encode_terminal_src;
546 nchars = 0;
547 while (src < src_end)
549 if (src->type == COMPOSITE_GLYPH)
551 struct composition *cmp IF_LINT (= NULL);
552 Lisp_Object gstring IF_LINT (= Qnil);
553 int i;
555 nbytes = buf - encode_terminal_src;
556 if (src->u.cmp.automatic)
558 gstring = composition_gstring_from_id (src->u.cmp.id);
559 required = src->slice.cmp.to - src->slice.cmp.from + 1;
561 else
563 cmp = composition_table[src->u.cmp.id];
564 required = cmp->glyph_len;
565 required *= MAX_MULTIBYTE_LENGTH;
568 if (encode_terminal_src_size - nbytes < required)
570 encode_terminal_src =
571 xpalloc (encode_terminal_src, &encode_terminal_src_size,
572 required - (encode_terminal_src_size - nbytes),
573 -1, 1);
574 buf = encode_terminal_src + nbytes;
577 if (src->u.cmp.automatic)
578 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
580 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
581 int c = LGLYPH_CHAR (g);
583 if (! char_charset (c, charset_list, NULL))
584 c = '?';
585 buf += CHAR_STRING (c, buf);
586 nchars++;
588 else
589 for (i = 0; i < cmp->glyph_len; i++)
591 int c = COMPOSITION_GLYPH (cmp, i);
593 /* TAB in a composition means display glyphs with
594 padding space on the left or right. */
595 if (c == '\t')
596 continue;
597 if (char_charset (c, charset_list, NULL))
599 if (CHAR_WIDTH (c) == 0
600 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
601 /* Should be left-padded */
603 buf += CHAR_STRING (' ', buf);
604 nchars++;
607 else
608 c = '?';
609 buf += CHAR_STRING (c, buf);
610 nchars++;
613 /* We must skip glyphs to be padded for a wide character. */
614 else if (! CHAR_GLYPH_PADDING_P (*src))
616 GLYPH g;
617 int c IF_LINT (= 0);
618 Lisp_Object string;
620 string = Qnil;
621 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
623 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
625 /* This glyph doesn't have an entry in Vglyph_table. */
626 c = src->u.ch;
628 else
630 /* This glyph has an entry in Vglyph_table,
631 so process any alias before testing for simpleness. */
632 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
634 if (GLYPH_SIMPLE_P (tbase, tlen, g))
635 /* We set the multi-byte form of a character in G
636 (that should be an ASCII character) at WORKBUF. */
637 c = GLYPH_CHAR (g);
638 else
639 /* We have a string in Vglyph_table. */
640 string = tbase[GLYPH_CHAR (g)];
643 if (NILP (string))
645 nbytes = buf - encode_terminal_src;
646 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
648 encode_terminal_src =
649 xpalloc (encode_terminal_src, &encode_terminal_src_size,
650 MAX_MULTIBYTE_LENGTH, -1, 1);
651 buf = encode_terminal_src + nbytes;
653 if (CHAR_BYTE8_P (c)
654 || char_charset (c, charset_list, NULL))
656 /* Store the multibyte form of C at BUF. */
657 buf += CHAR_STRING (c, buf);
658 nchars++;
660 else
662 /* C is not encodable. */
663 *buf++ = '?';
664 nchars++;
665 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
667 *buf++ = '?';
668 nchars++;
669 src++;
673 else
675 if (! STRING_MULTIBYTE (string))
676 string = string_to_multibyte (string);
677 nbytes = buf - encode_terminal_src;
678 if (encode_terminal_src_size - nbytes < SBYTES (string))
680 encode_terminal_src =
681 xpalloc (encode_terminal_src, &encode_terminal_src_size,
682 (SBYTES (string)
683 - (encode_terminal_src_size - nbytes)),
684 -1, 1);
685 buf = encode_terminal_src + nbytes;
687 memcpy (buf, SDATA (string), SBYTES (string));
688 buf += SBYTES (string);
689 nchars += SCHARS (string);
692 src++;
695 if (nchars == 0)
697 coding->produced = 0;
698 return NULL;
701 nbytes = buf - encode_terminal_src;
702 coding->source = encode_terminal_src;
703 if (encode_terminal_dst_size == 0)
705 encode_terminal_dst = xrealloc (encode_terminal_dst,
706 encode_terminal_src_size);
707 encode_terminal_dst_size = encode_terminal_src_size;
709 coding->destination = encode_terminal_dst;
710 coding->dst_bytes = encode_terminal_dst_size;
711 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
712 /* coding->destination may have been reallocated. */
713 encode_terminal_dst = coding->destination;
714 encode_terminal_dst_size = coding->dst_bytes;
716 return (encode_terminal_dst);
721 /* An implementation of write_glyphs for termcap frames. */
723 static void
724 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
726 unsigned char *conversion_buffer;
727 struct coding_system *coding;
728 int n, stringlen;
730 struct tty_display_info *tty = FRAME_TTY (f);
732 tty_turn_off_insert (tty);
733 tty_hide_cursor (tty);
735 /* Don't dare write in last column of bottom line, if Auto-Wrap,
736 since that would scroll the whole frame on some terminals. */
738 if (AutoWrap (tty)
739 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
740 && (curX (tty) + len) == FRAME_COLS (f))
741 len --;
742 if (len <= 0)
743 return;
745 cmplus (tty, len);
747 /* If terminal_coding does any conversion, use it, otherwise use
748 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
749 because it always return 1 if the member src_multibyte is 1. */
750 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
751 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
752 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
753 the tail. */
754 coding->mode &= ~CODING_MODE_LAST_BLOCK;
756 for (stringlen = len; stringlen != 0; stringlen -= n)
758 /* Identify a run of glyphs with the same face. */
759 int face_id = string->face_id;
761 for (n = 1; n < stringlen; ++n)
762 if (string[n].face_id != face_id)
763 break;
765 /* Turn appearance modes of the face of the run on. */
766 tty_highlight_if_desired (tty);
767 turn_on_face (f, face_id);
769 if (n == stringlen)
770 /* This is the last run. */
771 coding->mode |= CODING_MODE_LAST_BLOCK;
772 conversion_buffer = encode_terminal_code (string, n, coding);
773 if (coding->produced > 0)
775 block_input ();
776 fwrite (conversion_buffer, 1, coding->produced, tty->output);
777 if (ferror (tty->output))
778 clearerr (tty->output);
779 if (tty->termscript)
780 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
781 unblock_input ();
783 string += n;
785 /* Turn appearance modes off. */
786 turn_off_face (f, face_id);
787 tty_turn_off_highlight (tty);
790 cmcheckmagic (tty);
793 #ifdef HAVE_GPM /* Only used by GPM code. */
795 static void
796 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
797 register int len, register int face_id)
799 unsigned char *conversion_buffer;
800 struct coding_system *coding;
802 struct tty_display_info *tty = FRAME_TTY (f);
804 tty_turn_off_insert (tty);
805 tty_hide_cursor (tty);
807 /* Don't dare write in last column of bottom line, if Auto-Wrap,
808 since that would scroll the whole frame on some terminals. */
810 if (AutoWrap (tty)
811 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
812 && (curX (tty) + len) == FRAME_COLS (f))
813 len --;
814 if (len <= 0)
815 return;
817 cmplus (tty, len);
819 /* If terminal_coding does any conversion, use it, otherwise use
820 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
821 because it always return 1 if the member src_multibyte is 1. */
822 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
823 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
824 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
825 the tail. */
826 coding->mode &= ~CODING_MODE_LAST_BLOCK;
828 /* Turn appearance modes of the face. */
829 tty_highlight_if_desired (tty);
830 turn_on_face (f, face_id);
832 coding->mode |= CODING_MODE_LAST_BLOCK;
833 conversion_buffer = encode_terminal_code (string, len, coding);
834 if (coding->produced > 0)
836 block_input ();
837 fwrite (conversion_buffer, 1, coding->produced, tty->output);
838 if (ferror (tty->output))
839 clearerr (tty->output);
840 if (tty->termscript)
841 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
842 unblock_input ();
845 /* Turn appearance modes off. */
846 turn_off_face (f, face_id);
847 tty_turn_off_highlight (tty);
849 cmcheckmagic (tty);
851 #endif
853 /* An implementation of insert_glyphs for termcap frames. */
855 static void
856 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
858 char *buf;
859 struct glyph *glyph = NULL;
860 unsigned char *conversion_buffer;
861 unsigned char space[1];
862 struct coding_system *coding;
864 struct tty_display_info *tty = FRAME_TTY (f);
866 if (tty->TS_ins_multi_chars)
868 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
869 OUTPUT1 (tty, buf);
870 xfree (buf);
871 if (start)
872 write_glyphs (f, start, len);
873 return;
876 tty_turn_on_insert (tty);
877 cmplus (tty, len);
879 if (! start)
880 space[0] = SPACEGLYPH;
882 /* If terminal_coding does any conversion, use it, otherwise use
883 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
884 because it always return 1 if the member src_multibyte is 1. */
885 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
886 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
887 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
888 the tail. */
889 coding->mode &= ~CODING_MODE_LAST_BLOCK;
891 while (len-- > 0)
893 OUTPUT1_IF (tty, tty->TS_ins_char);
894 if (!start)
896 conversion_buffer = space;
897 coding->produced = 1;
899 else
901 tty_highlight_if_desired (tty);
902 turn_on_face (f, start->face_id);
903 glyph = start;
904 ++start;
905 /* We must open sufficient space for a character which
906 occupies more than one column. */
907 while (len && CHAR_GLYPH_PADDING_P (*start))
909 OUTPUT1_IF (tty, tty->TS_ins_char);
910 start++, len--;
913 if (len <= 0)
914 /* This is the last glyph. */
915 coding->mode |= CODING_MODE_LAST_BLOCK;
917 conversion_buffer = encode_terminal_code (glyph, 1, coding);
920 if (coding->produced > 0)
922 block_input ();
923 fwrite (conversion_buffer, 1, coding->produced, tty->output);
924 if (ferror (tty->output))
925 clearerr (tty->output);
926 if (tty->termscript)
927 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
928 unblock_input ();
931 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
932 if (start)
934 turn_off_face (f, glyph->face_id);
935 tty_turn_off_highlight (tty);
939 cmcheckmagic (tty);
942 /* An implementation of delete_glyphs for termcap frames. */
944 static void
945 tty_delete_glyphs (struct frame *f, int n)
947 char *buf;
948 register int i;
950 struct tty_display_info *tty = FRAME_TTY (f);
952 if (tty->delete_in_insert_mode)
954 tty_turn_on_insert (tty);
956 else
958 tty_turn_off_insert (tty);
959 OUTPUT_IF (tty, tty->TS_delete_mode);
962 if (tty->TS_del_multi_chars)
964 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
965 OUTPUT1 (tty, buf);
966 xfree (buf);
968 else
969 for (i = 0; i < n; i++)
970 OUTPUT1 (tty, tty->TS_del_char);
971 if (!tty->delete_in_insert_mode)
972 OUTPUT_IF (tty, tty->TS_end_delete_mode);
975 /* An implementation of ins_del_lines for termcap frames. */
977 static void
978 tty_ins_del_lines (struct frame *f, int vpos, int n)
980 struct tty_display_info *tty = FRAME_TTY (f);
981 const char *multi =
982 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
983 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
984 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
986 int i = eabs (n);
987 char *buf;
989 /* If the lines below the insertion are being pushed
990 into the end of the window, this is the same as clearing;
991 and we know the lines are already clear, since the matching
992 deletion has already been done. So can ignore this. */
993 /* If the lines below the deletion are blank lines coming
994 out of the end of the window, don't bother,
995 as there will be a matching inslines later that will flush them. */
996 if (FRAME_SCROLL_REGION_OK (f)
997 && vpos + i >= tty->specified_window)
998 return;
999 if (!FRAME_MEMORY_BELOW_FRAME (f)
1000 && vpos + i >= FRAME_TOTAL_LINES (f))
1001 return;
1003 if (multi)
1005 raw_cursor_to (f, vpos, 0);
1006 tty_background_highlight (tty);
1007 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1008 OUTPUT (tty, buf);
1009 xfree (buf);
1011 else if (single)
1013 raw_cursor_to (f, vpos, 0);
1014 tty_background_highlight (tty);
1015 while (--i >= 0)
1016 OUTPUT (tty, single);
1017 if (tty->TF_teleray)
1018 curX (tty) = 0;
1020 else
1022 tty_set_scroll_region (f, vpos, tty->specified_window);
1023 if (n < 0)
1024 raw_cursor_to (f, tty->specified_window - 1, 0);
1025 else
1026 raw_cursor_to (f, vpos, 0);
1027 tty_background_highlight (tty);
1028 while (--i >= 0)
1029 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1030 tty_set_scroll_region (f, 0, tty->specified_window);
1033 if (!FRAME_SCROLL_REGION_OK (f)
1034 && FRAME_MEMORY_BELOW_FRAME (f)
1035 && n < 0)
1037 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1038 clear_to_end (f);
1042 /* Compute cost of sending "str", in characters,
1043 not counting any line-dependent padding. */
1046 string_cost (const char *str)
1048 cost = 0;
1049 if (str)
1050 tputs (str, 0, evalcost);
1051 return cost;
1054 /* Compute cost of sending "str", in characters,
1055 counting any line-dependent padding at one line. */
1057 static int
1058 string_cost_one_line (const char *str)
1060 cost = 0;
1061 if (str)
1062 tputs (str, 1, evalcost);
1063 return cost;
1066 /* Compute per line amount of line-dependent padding,
1067 in tenths of characters. */
1070 per_line_cost (const char *str)
1072 cost = 0;
1073 if (str)
1074 tputs (str, 0, evalcost);
1075 cost = - cost;
1076 if (str)
1077 tputs (str, 10, evalcost);
1078 return cost;
1081 /* char_ins_del_cost[n] is cost of inserting N characters.
1082 char_ins_del_cost[-n] is cost of deleting N characters.
1083 The length of this vector is based on max_frame_cols. */
1085 int *char_ins_del_vector;
1087 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1089 /* ARGSUSED */
1090 static void
1091 calculate_ins_del_char_costs (struct frame *f)
1093 struct tty_display_info *tty = FRAME_TTY (f);
1094 int ins_startup_cost, del_startup_cost;
1095 int ins_cost_per_char, del_cost_per_char;
1096 register int i;
1097 register int *p;
1099 if (tty->TS_ins_multi_chars)
1101 ins_cost_per_char = 0;
1102 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1104 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1105 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1107 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1108 + string_cost (tty->TS_end_insert_mode))) / 100;
1109 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1110 + string_cost_one_line (tty->TS_pad_inserted_char));
1112 else
1114 ins_startup_cost = 9999;
1115 ins_cost_per_char = 0;
1118 if (tty->TS_del_multi_chars)
1120 del_cost_per_char = 0;
1121 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1123 else if (tty->TS_del_char)
1125 del_startup_cost = (string_cost (tty->TS_delete_mode)
1126 + string_cost (tty->TS_end_delete_mode));
1127 if (tty->delete_in_insert_mode)
1128 del_startup_cost /= 2;
1129 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1131 else
1133 del_startup_cost = 9999;
1134 del_cost_per_char = 0;
1137 /* Delete costs are at negative offsets */
1138 p = &char_ins_del_cost (f)[0];
1139 for (i = FRAME_COLS (f); --i >= 0;)
1140 *--p = (del_startup_cost += del_cost_per_char);
1142 /* Doing nothing is free */
1143 p = &char_ins_del_cost (f)[0];
1144 *p++ = 0;
1146 /* Insert costs are at positive offsets */
1147 for (i = FRAME_COLS (f); --i >= 0;)
1148 *p++ = (ins_startup_cost += ins_cost_per_char);
1151 void
1152 calculate_costs (struct frame *frame)
1154 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1156 if (FRAME_TERMCAP_P (frame))
1158 struct tty_display_info *tty = FRAME_TTY (frame);
1159 register const char *f = (tty->TS_set_scroll_region
1160 ? tty->TS_set_scroll_region
1161 : tty->TS_set_scroll_region_1);
1163 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1165 tty->costs_set = 1;
1167 /* These variables are only used for terminal stuff. They are
1168 allocated once for the terminal frame of X-windows emacs, but not
1169 used afterwards.
1171 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1172 X turns off char_ins_del_ok. */
1174 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1175 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1176 < max_frame_cols)
1177 memory_full (SIZE_MAX);
1179 char_ins_del_vector =
1180 xrealloc (char_ins_del_vector,
1181 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1183 memset (char_ins_del_vector, 0,
1184 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1187 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1188 do_line_insertion_deletion_costs (frame,
1189 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1190 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1191 f, f, 1);
1192 else
1193 do_line_insertion_deletion_costs (frame,
1194 tty->TS_ins_line, tty->TS_ins_multi_lines,
1195 tty->TS_del_line, tty->TS_del_multi_lines,
1196 0, 0, 1);
1198 calculate_ins_del_char_costs (frame);
1200 /* Don't use TS_repeat if its padding is worse than sending the chars */
1201 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1202 tty->RPov = string_cost (tty->TS_repeat);
1203 else
1204 tty->RPov = FRAME_COLS (frame) * 2;
1206 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1210 struct fkey_table {
1211 const char *cap, *name;
1214 /* Termcap capability names that correspond directly to X keysyms.
1215 Some of these (marked "terminfo") aren't supplied by old-style
1216 (Berkeley) termcap entries. They're listed in X keysym order;
1217 except we put the keypad keys first, so that if they clash with
1218 other keys (as on the IBM PC keyboard) they get overridden.
1221 static const struct fkey_table keys[] =
1223 {"kh", "home"}, /* termcap */
1224 {"kl", "left"}, /* termcap */
1225 {"ku", "up"}, /* termcap */
1226 {"kr", "right"}, /* termcap */
1227 {"kd", "down"}, /* termcap */
1228 {"%8", "prior"}, /* terminfo */
1229 {"%5", "next"}, /* terminfo */
1230 {"@7", "end"}, /* terminfo */
1231 {"@1", "begin"}, /* terminfo */
1232 {"*6", "select"}, /* terminfo */
1233 {"%9", "print"}, /* terminfo */
1234 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1236 * "insert" --- see below
1238 {"&8", "undo"}, /* terminfo */
1239 {"%0", "redo"}, /* terminfo */
1240 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1241 {"@0", "find"}, /* terminfo */
1242 {"@2", "cancel"}, /* terminfo */
1243 {"%1", "help"}, /* terminfo */
1245 * "break" goes here, but can't be reliably intercepted with termcap
1247 {"&4", "reset"}, /* terminfo --- actually `restart' */
1249 * "system" and "user" --- no termcaps
1251 {"kE", "clearline"}, /* terminfo */
1252 {"kA", "insertline"}, /* terminfo */
1253 {"kL", "deleteline"}, /* terminfo */
1254 {"kI", "insertchar"}, /* terminfo */
1255 {"kD", "deletechar"}, /* terminfo */
1256 {"kB", "backtab"}, /* terminfo */
1258 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1260 {"@8", "kp-enter"}, /* terminfo */
1262 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1263 * "kp-multiply", "kp-add", "kp-separator",
1264 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1265 * --- no termcaps for any of these.
1267 {"K4", "kp-1"}, /* terminfo */
1269 * "kp-2" --- no termcap
1271 {"K5", "kp-3"}, /* terminfo */
1273 * "kp-4" --- no termcap
1275 {"K2", "kp-5"}, /* terminfo */
1277 * "kp-6" --- no termcap
1279 {"K1", "kp-7"}, /* terminfo */
1281 * "kp-8" --- no termcap
1283 {"K3", "kp-9"}, /* terminfo */
1285 * "kp-equal" --- no termcap
1287 {"k1", "f1"},
1288 {"k2", "f2"},
1289 {"k3", "f3"},
1290 {"k4", "f4"},
1291 {"k5", "f5"},
1292 {"k6", "f6"},
1293 {"k7", "f7"},
1294 {"k8", "f8"},
1295 {"k9", "f9"},
1297 {"&0", "S-cancel"}, /*shifted cancel key*/
1298 {"&9", "S-begin"}, /*shifted begin key*/
1299 {"*0", "S-find"}, /*shifted find key*/
1300 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1301 {"*4", "S-delete"}, /*shifted delete-character key*/
1302 {"*7", "S-end"}, /*shifted end key*/
1303 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1304 {"#1", "S-help"}, /*shifted help key*/
1305 {"#2", "S-home"}, /*shifted home key*/
1306 {"#3", "S-insert"}, /*shifted insert-character key*/
1307 {"#4", "S-left"}, /*shifted left-arrow key*/
1308 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1309 {"%c", "S-next"}, /*shifted next key*/
1310 {"%e", "S-prior"}, /*shifted previous key*/
1311 {"%f", "S-print"}, /*shifted print key*/
1312 {"%g", "S-redo"}, /*shifted redo key*/
1313 {"%i", "S-right"}, /*shifted right-arrow key*/
1314 {"!3", "S-undo"} /*shifted undo key*/
1317 #ifndef DOS_NT
1318 static char **term_get_fkeys_address;
1319 static KBOARD *term_get_fkeys_kboard;
1320 static Lisp_Object term_get_fkeys_1 (void);
1322 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1323 This function scans the termcap function key sequence entries, and
1324 adds entries to Vinput_decode_map for each function key it finds. */
1326 static void
1327 term_get_fkeys (char **address, KBOARD *kboard)
1329 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1330 errors during the call. The only errors should be from Fdefine_key
1331 when given a key sequence containing an invalid prefix key. If the
1332 termcap defines function keys which use a prefix that is already bound
1333 to a command by the default bindings, we should silently ignore that
1334 function key specification, rather than giving the user an error and
1335 refusing to run at all on such a terminal. */
1337 term_get_fkeys_address = address;
1338 term_get_fkeys_kboard = kboard;
1339 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1342 static Lisp_Object
1343 term_get_fkeys_1 (void)
1345 int i;
1347 char **address = term_get_fkeys_address;
1348 KBOARD *kboard = term_get_fkeys_kboard;
1350 /* This can happen if CANNOT_DUMP or with strange options. */
1351 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1352 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1354 for (i = 0; i < ARRAYELTS (keys); i++)
1356 char *sequence = tgetstr (keys[i].cap, address);
1357 if (sequence)
1358 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1359 Fmake_vector (make_number (1),
1360 intern (keys[i].name)));
1363 /* The uses of the "k0" capability are inconsistent; sometimes it
1364 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1365 We will attempt to politely accommodate both systems by testing for
1366 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1369 const char *k_semi = tgetstr ("k;", address);
1370 const char *k0 = tgetstr ("k0", address);
1371 const char *k0_name = "f10";
1373 if (k_semi)
1375 if (k0)
1376 /* Define f0 first, so that f10 takes precedence in case the
1377 key sequences happens to be the same. */
1378 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1379 Fmake_vector (make_number (1), intern ("f0")));
1380 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1381 Fmake_vector (make_number (1), intern ("f10")));
1383 else if (k0)
1384 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1385 Fmake_vector (make_number (1), intern (k0_name)));
1388 /* Set up cookies for numbered function keys above f10. */
1390 char fcap[3], fkey[4];
1392 fcap[0] = 'F'; fcap[2] = '\0';
1393 for (i = 11; i < 64; i++)
1395 if (i <= 19)
1396 fcap[1] = '1' + i - 11;
1397 else if (i <= 45)
1398 fcap[1] = 'A' + i - 20;
1399 else
1400 fcap[1] = 'a' + i - 46;
1403 char *sequence = tgetstr (fcap, address);
1404 if (sequence)
1406 sprintf (fkey, "f%d", i);
1407 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1408 Fmake_vector (make_number (1),
1409 intern (fkey)));
1416 * Various mappings to try and get a better fit.
1419 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1420 if (!tgetstr (cap1, address)) \
1422 char *sequence = tgetstr (cap2, address); \
1423 if (sequence) \
1424 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1425 Fmake_vector (make_number (1), \
1426 intern (sym))); \
1429 /* if there's no key_next keycap, map key_npage to `next' keysym */
1430 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1431 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1432 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1433 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1434 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1435 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1436 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1437 #undef CONDITIONAL_REASSIGN
1440 return Qnil;
1442 #endif /* not DOS_NT */
1445 /***********************************************************************
1446 Character Display Information
1447 ***********************************************************************/
1448 static void append_glyph (struct it *);
1449 static void append_composite_glyph (struct it *);
1450 static void produce_composite_glyph (struct it *);
1451 static void append_glyphless_glyph (struct it *, int, const char *);
1452 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1454 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1455 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1456 the character for which to produce glyphs; IT->face_id contains the
1457 character's face. Padding glyphs are appended if IT->c has a
1458 IT->pixel_width > 1. */
1460 static void
1461 append_glyph (struct it *it)
1463 struct glyph *glyph, *end;
1464 int i;
1466 eassert (it->glyph_row);
1467 glyph = (it->glyph_row->glyphs[it->area]
1468 + it->glyph_row->used[it->area]);
1469 end = it->glyph_row->glyphs[1 + it->area];
1471 /* If the glyph row is reversed, we need to prepend the glyph rather
1472 than append it. */
1473 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1475 struct glyph *g;
1476 int move_by = it->pixel_width;
1478 /* Make room for the new glyphs. */
1479 if (move_by > end - glyph) /* don't overstep end of this area */
1480 move_by = end - glyph;
1481 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1482 g[move_by] = *g;
1483 glyph = it->glyph_row->glyphs[it->area];
1484 end = glyph + move_by;
1487 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1488 right, even in the REVERSED_P case, since (a) all of its u.ch are
1489 identical, and (b) the PADDING_P flag needs to be set for the
1490 leftmost one, because we write to the terminal left-to-right. */
1491 for (i = 0;
1492 i < it->pixel_width && glyph < end;
1493 ++i)
1495 glyph->type = CHAR_GLYPH;
1496 glyph->pixel_width = 1;
1497 glyph->u.ch = it->char_to_display;
1498 glyph->face_id = it->face_id;
1499 glyph->padding_p = i > 0;
1500 glyph->charpos = CHARPOS (it->position);
1501 glyph->object = it->object;
1502 if (it->bidi_p)
1504 glyph->resolved_level = it->bidi_it.resolved_level;
1505 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1506 glyph->bidi_type = it->bidi_it.type;
1508 else
1510 glyph->resolved_level = 0;
1511 glyph->bidi_type = UNKNOWN_BT;
1514 ++it->glyph_row->used[it->area];
1515 ++glyph;
1519 /* For external use. */
1520 void
1521 tty_append_glyph (struct it *it)
1523 append_glyph (it);
1527 /* Produce glyphs for the display element described by IT. *IT
1528 specifies what we want to produce a glyph for (character, image, ...),
1529 and where in the glyph matrix we currently are (glyph row and hpos).
1530 produce_glyphs fills in output fields of *IT with information such as the
1531 pixel width and height of a character, and maybe output actual glyphs at
1532 the same time if IT->glyph_row is non-null. For an overview, see
1533 the explanation in dispextern.h, before the definition of the
1534 display_element_type enumeration.
1536 produce_glyphs also stores the result of glyph width, ascent
1537 etc. computations in *IT.
1539 IT->glyph_row may be null, in which case produce_glyphs does not
1540 actually fill in the glyphs. This is used in the move_* functions
1541 in xdisp.c for text width and height computations.
1543 Callers usually don't call produce_glyphs directly;
1544 instead they use the macro PRODUCE_GLYPHS. */
1546 void
1547 produce_glyphs (struct it *it)
1549 /* If a hook is installed, let it do the work. */
1551 /* Nothing but characters are supported on terminal frames. */
1552 eassert (it->what == IT_CHARACTER
1553 || it->what == IT_COMPOSITION
1554 || it->what == IT_STRETCH
1555 || it->what == IT_GLYPHLESS);
1557 if (it->what == IT_STRETCH)
1559 produce_stretch_glyph (it);
1560 goto done;
1563 if (it->what == IT_COMPOSITION)
1565 produce_composite_glyph (it);
1566 goto done;
1569 if (it->what == IT_GLYPHLESS)
1571 produce_glyphless_glyph (it, Qnil);
1572 goto done;
1575 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1577 it->pixel_width = it->nglyphs = 1;
1578 if (it->glyph_row)
1579 append_glyph (it);
1581 else if (it->char_to_display == '\n')
1582 it->pixel_width = it->nglyphs = 0;
1583 else if (it->char_to_display == '\t')
1585 int absolute_x = (it->current_x
1586 + it->continuation_lines_width);
1587 int next_tab_x
1588 = (((1 + absolute_x + it->tab_width - 1)
1589 / it->tab_width)
1590 * it->tab_width);
1591 int nspaces;
1593 /* If part of the TAB has been displayed on the previous line
1594 which is continued now, continuation_lines_width will have
1595 been incremented already by the part that fitted on the
1596 continued line. So, we will get the right number of spaces
1597 here. */
1598 nspaces = next_tab_x - absolute_x;
1600 if (it->glyph_row)
1602 int n = nspaces;
1604 it->char_to_display = ' ';
1605 it->pixel_width = it->len = 1;
1607 while (n--)
1608 append_glyph (it);
1611 it->pixel_width = nspaces;
1612 it->nglyphs = nspaces;
1614 else if (CHAR_BYTE8_P (it->char_to_display))
1616 /* Coming here means that we must send the raw 8-bit byte as is
1617 to the terminal. Although there's no way to know how many
1618 columns it occupies on a screen, it is a good assumption that
1619 a single byte code has 1-column width. */
1620 it->pixel_width = it->nglyphs = 1;
1621 if (it->glyph_row)
1622 append_glyph (it);
1624 else
1626 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1628 if (char_charset (it->char_to_display, charset_list, NULL))
1630 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1631 it->nglyphs = it->pixel_width;
1632 if (it->glyph_row)
1633 append_glyph (it);
1635 else
1637 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1639 eassert (it->what == IT_GLYPHLESS);
1640 produce_glyphless_glyph (it, acronym);
1644 done:
1645 /* Advance current_x by the pixel width as a convenience for
1646 the caller. */
1647 if (it->area == TEXT_AREA)
1648 it->current_x += it->pixel_width;
1649 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1650 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1653 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1654 Called from produce_composite_glyph for terminal frames if
1655 IT->glyph_row != NULL. IT->face_id contains the character's
1656 face. */
1658 static void
1659 append_composite_glyph (struct it *it)
1661 struct glyph *glyph;
1663 eassert (it->glyph_row);
1664 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1665 if (glyph < it->glyph_row->glyphs[1 + it->area])
1667 /* If the glyph row is reversed, we need to prepend the glyph
1668 rather than append it. */
1669 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1671 struct glyph *g;
1673 /* Make room for the new glyph. */
1674 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1675 g[1] = *g;
1676 glyph = it->glyph_row->glyphs[it->area];
1678 glyph->type = COMPOSITE_GLYPH;
1679 glyph->pixel_width = it->pixel_width;
1680 glyph->u.cmp.id = it->cmp_it.id;
1681 if (it->cmp_it.ch < 0)
1683 glyph->u.cmp.automatic = 0;
1684 glyph->u.cmp.id = it->cmp_it.id;
1686 else
1688 glyph->u.cmp.automatic = 1;
1689 glyph->u.cmp.id = it->cmp_it.id;
1690 glyph->slice.cmp.from = it->cmp_it.from;
1691 glyph->slice.cmp.to = it->cmp_it.to - 1;
1694 glyph->face_id = it->face_id;
1695 glyph->padding_p = 0;
1696 glyph->charpos = CHARPOS (it->position);
1697 glyph->object = it->object;
1698 if (it->bidi_p)
1700 glyph->resolved_level = it->bidi_it.resolved_level;
1701 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1702 glyph->bidi_type = it->bidi_it.type;
1704 else
1706 glyph->resolved_level = 0;
1707 glyph->bidi_type = UNKNOWN_BT;
1710 ++it->glyph_row->used[it->area];
1711 ++glyph;
1716 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1717 the composition. We simply produces components of the composition
1718 assuming that the terminal has a capability to layout/render it
1719 correctly. */
1721 static void
1722 produce_composite_glyph (struct it *it)
1724 if (it->cmp_it.ch < 0)
1726 struct composition *cmp = composition_table[it->cmp_it.id];
1728 it->pixel_width = cmp->width;
1730 else
1732 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1734 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1735 it->cmp_it.to, NULL);
1737 it->nglyphs = 1;
1738 if (it->glyph_row)
1739 append_composite_glyph (it);
1743 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1744 is a face ID to be used for the glyph. What is actually appended
1745 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1746 comes from it->nglyphs bytes). */
1748 static void
1749 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1751 struct glyph *glyph, *end;
1752 int i;
1754 eassert (it->glyph_row);
1755 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1756 end = it->glyph_row->glyphs[1 + it->area];
1758 /* If the glyph row is reversed, we need to prepend the glyph rather
1759 than append it. */
1760 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1762 struct glyph *g;
1763 int move_by = it->pixel_width;
1765 /* Make room for the new glyphs. */
1766 if (move_by > end - glyph) /* don't overstep end of this area */
1767 move_by = end - glyph;
1768 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1769 g[move_by] = *g;
1770 glyph = it->glyph_row->glyphs[it->area];
1771 end = glyph + move_by;
1774 if (glyph >= end)
1775 return;
1776 glyph->type = CHAR_GLYPH;
1777 glyph->pixel_width = 1;
1778 glyph->face_id = face_id;
1779 glyph->padding_p = 0;
1780 glyph->charpos = CHARPOS (it->position);
1781 glyph->object = it->object;
1782 if (it->bidi_p)
1784 glyph->resolved_level = it->bidi_it.resolved_level;
1785 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1786 glyph->bidi_type = it->bidi_it.type;
1788 else
1790 glyph->resolved_level = 0;
1791 glyph->bidi_type = UNKNOWN_BT;
1794 /* BIDI Note: we put the glyphs of characters left to right, even in
1795 the REVERSED_P case because we write to the terminal
1796 left-to-right. */
1797 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1799 if (i > 0)
1800 glyph[0] = glyph[-1];
1801 glyph->u.ch = str[i];
1802 ++it->glyph_row->used[it->area];
1803 ++glyph;
1807 /* Produce glyphs for a glyphless character for iterator IT.
1808 IT->glyphless_method specifies which method to use for displaying
1809 the character. See the description of enum
1810 glyphless_display_method in dispextern.h for the details.
1812 ACRONYM, if non-nil, is an acronym string for the character.
1814 The glyphs actually produced are of type CHAR_GLYPH. */
1816 static void
1817 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1819 int len, face_id = merge_glyphless_glyph_face (it);
1820 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1821 char const *str = " ";
1823 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1825 /* As there's no way to produce a thin space, we produce a space
1826 of canonical width. */
1827 len = 1;
1829 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1831 len = CHAR_WIDTH (it->c);
1832 if (len == 0)
1833 len = 1;
1834 else if (len > 4)
1835 len = 4;
1836 len = sprintf (buf, "[%.*s]", len, str);
1837 str = buf;
1839 else
1841 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1843 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1844 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1845 if (CONSP (acronym))
1846 acronym = XCDR (acronym);
1847 buf[0] = '[';
1848 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1849 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1850 buf[1 + len] = str[len];
1851 buf[1 + len] = ']';
1852 len += 2;
1854 else
1856 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1857 len = sprintf (buf,
1858 (it->c < 0x10000 ? "\\u%04X"
1859 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1860 : "\\x%06X"),
1861 it->c + 0u);
1863 str = buf;
1866 it->pixel_width = len;
1867 it->nglyphs = len;
1868 if (it->glyph_row)
1869 append_glyphless_glyph (it, face_id, str);
1873 /***********************************************************************
1874 Faces
1875 ***********************************************************************/
1877 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1878 one of the enumerators from enum no_color_bit, or a bit set built
1879 from them. Some display attributes may not be used together with
1880 color; the termcap capability `NC' specifies which ones. */
1882 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1883 (tty->TN_max_colors > 0 \
1884 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1885 : 1)
1887 /* Turn appearances of face FACE_ID on tty frame F on.
1888 FACE_ID is a realized face ID number, in the face cache. */
1890 static void
1891 turn_on_face (struct frame *f, int face_id)
1893 struct face *face = FACE_FROM_ID (f, face_id);
1894 unsigned long fg = face->foreground;
1895 unsigned long bg = face->background;
1896 struct tty_display_info *tty = FRAME_TTY (f);
1898 /* Use reverse video if the face specifies that.
1899 Do this first because TS_end_standout_mode may be the same
1900 as TS_exit_attribute_mode, which turns all appearances off. */
1901 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1902 && (inverse_video
1903 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1904 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1905 tty_toggle_highlight (tty);
1907 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1908 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1910 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1912 if (tty->TS_enter_italic_mode)
1913 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1914 else
1915 /* Italics mode is unavailable on many terminals. In that
1916 case, map slant to dimmed text; we want italic text to
1917 appear different and dimming is not otherwise used. */
1918 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1921 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1922 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1924 if (tty->TN_max_colors > 0)
1926 const char *ts;
1927 char *p;
1929 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1930 if (face_tty_specified_color (fg) && ts)
1932 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1933 OUTPUT (tty, p);
1934 xfree (p);
1937 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1938 if (face_tty_specified_color (bg) && ts)
1940 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1941 OUTPUT (tty, p);
1942 xfree (p);
1948 /* Turn off appearances of face FACE_ID on tty frame F. */
1950 static void
1951 turn_off_face (struct frame *f, int face_id)
1953 struct face *face = FACE_FROM_ID (f, face_id);
1954 struct tty_display_info *tty = FRAME_TTY (f);
1956 eassert (face != NULL);
1958 if (tty->TS_exit_attribute_mode)
1960 /* Capability "me" will turn off appearance modes double-bright,
1961 half-bright, reverse-video, standout, underline. It may or
1962 may not turn off alt-char-mode. */
1963 if (face->tty_bold_p
1964 || face->tty_italic_p
1965 || face->tty_reverse_p
1966 || face->tty_underline_p)
1968 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1969 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1970 tty->standout_mode = 0;
1973 else
1975 /* If we don't have "me" we can only have those appearances
1976 that have exit sequences defined. */
1977 if (face->tty_underline_p)
1978 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1981 /* Switch back to default colors. */
1982 if (tty->TN_max_colors > 0
1983 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1984 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1985 || (face->background != FACE_TTY_DEFAULT_COLOR
1986 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1987 OUTPUT1_IF (tty, tty->TS_orig_pair);
1991 /* Return true if the terminal on frame F supports all of the
1992 capabilities in CAPS simultaneously. */
1994 bool
1995 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
1997 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
1998 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
1999 return 0;
2001 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2002 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2003 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2004 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2005 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2007 /* We can do it! */
2008 return 1;
2011 /* Return non-zero if the terminal is capable to display colors. */
2013 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2014 0, 1, 0,
2015 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2017 TERMINAL can be a terminal object, a frame, or nil (meaning the
2018 selected frame's terminal). This function always returns nil if
2019 TERMINAL does not refer to a text terminal. */)
2020 (Lisp_Object terminal)
2022 struct terminal *t = decode_tty_terminal (terminal);
2024 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2027 /* Return the number of supported colors. */
2028 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2029 Stty_display_color_cells, 0, 1, 0,
2030 doc: /* Return the number of colors supported by the tty device TERMINAL.
2032 TERMINAL can be a terminal object, a frame, or nil (meaning the
2033 selected frame's terminal). This function always returns 0 if
2034 TERMINAL does not refer to a text terminal. */)
2035 (Lisp_Object terminal)
2037 struct terminal *t = decode_tty_terminal (terminal);
2039 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2042 #ifndef DOS_NT
2044 /* Declare here rather than in the function, as in the rest of Emacs,
2045 to work around an HPUX compiler bug (?). See
2046 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2047 static int default_max_colors;
2048 static int default_max_pairs;
2049 static int default_no_color_video;
2050 static char *default_orig_pair;
2051 static char *default_set_foreground;
2052 static char *default_set_background;
2054 /* Save or restore the default color-related capabilities of this
2055 terminal. */
2056 static void
2057 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2060 if (save)
2062 dupstring (&default_orig_pair, tty->TS_orig_pair);
2063 dupstring (&default_set_foreground, tty->TS_set_foreground);
2064 dupstring (&default_set_background, tty->TS_set_background);
2065 default_max_colors = tty->TN_max_colors;
2066 default_max_pairs = tty->TN_max_pairs;
2067 default_no_color_video = tty->TN_no_color_video;
2069 else
2071 tty->TS_orig_pair = default_orig_pair;
2072 tty->TS_set_foreground = default_set_foreground;
2073 tty->TS_set_background = default_set_background;
2074 tty->TN_max_colors = default_max_colors;
2075 tty->TN_max_pairs = default_max_pairs;
2076 tty->TN_no_color_video = default_no_color_video;
2080 /* Setup one of the standard tty color schemes according to MODE.
2081 MODE's value is generally the number of colors which we want to
2082 support; zero means set up for the default capabilities, the ones
2083 we saw at init_tty time; -1 means turn off color support. */
2084 static void
2085 tty_setup_colors (struct tty_display_info *tty, int mode)
2087 /* Canonicalize all negative values of MODE. */
2088 if (mode < -1)
2089 mode = -1;
2091 switch (mode)
2093 case -1: /* no colors at all */
2094 tty->TN_max_colors = 0;
2095 tty->TN_max_pairs = 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_max_pairs = 64;
2114 tty->TN_no_color_video = 0;
2115 break;
2119 void
2120 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2122 Lisp_Object tem, val;
2123 Lisp_Object color_mode;
2124 int mode;
2125 Lisp_Object tty_color_mode_alist
2126 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2128 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2129 val = CONSP (tem) ? XCDR (tem) : Qnil;
2131 if (INTEGERP (val))
2132 color_mode = val;
2133 else if (SYMBOLP (tty_color_mode_alist))
2135 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2136 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2138 else
2139 color_mode = Qnil;
2141 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2143 if (mode != tty->previous_color_mode)
2145 tty->previous_color_mode = mode;
2146 tty_setup_colors (tty , mode);
2147 /* This recomputes all the faces given the new color definitions. */
2148 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2152 #endif /* !DOS_NT */
2154 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2155 doc: /* Return the type of the tty device that TERMINAL uses.
2156 Returns nil if TERMINAL is not on a tty device.
2158 TERMINAL can be a terminal object, a frame, or nil (meaning the
2159 selected frame's terminal). */)
2160 (Lisp_Object terminal)
2162 struct terminal *t = decode_tty_terminal (terminal);
2164 return (t && t->display_info.tty->type
2165 ? build_string (t->display_info.tty->type) : Qnil);
2168 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2169 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2171 TERMINAL can be a terminal object, a frame, or nil (meaning the
2172 selected frame's terminal). This function always returns nil if
2173 TERMINAL is not on a tty device. */)
2174 (Lisp_Object terminal)
2176 struct terminal *t = decode_tty_terminal (terminal);
2178 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2181 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2182 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2183 This is used to override the terminfo data, for certain terminals that
2184 do not really do underlining, but say that they do. This function has
2185 no effect if used on a non-tty terminal.
2187 TERMINAL can be a terminal object, a frame or nil (meaning the
2188 selected frame's terminal). This function always returns nil if
2189 TERMINAL does not refer to a text terminal. */)
2190 (Lisp_Object terminal)
2192 struct terminal *t = decode_live_terminal (terminal);
2194 if (t->type == output_termcap)
2195 t->display_info.tty->TS_enter_underline_mode = 0;
2196 return Qnil;
2199 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2200 doc: /* Return the topmost terminal frame on TERMINAL.
2201 TERMINAL can be a terminal object, a frame or nil (meaning the
2202 selected frame's terminal). This function returns nil if TERMINAL
2203 does not refer to a text terminal. Otherwise, it returns the
2204 top-most frame on the text terminal. */)
2205 (Lisp_Object terminal)
2207 struct terminal *t = decode_live_terminal (terminal);
2209 if (t->type == output_termcap)
2210 return t->display_info.tty->top_frame;
2211 return Qnil;
2216 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2217 doc: /* Suspend the terminal device TTY.
2219 The device is restored to its default state, and Emacs ceases all
2220 access to the tty device. Frames that use the device are not deleted,
2221 but input is not read from them and if they change, their display is
2222 not updated.
2224 TTY may be a terminal object, a frame, or nil for the terminal device
2225 of the currently selected frame.
2227 This function runs `suspend-tty-functions' after suspending the
2228 device. The functions are run with one arg, the id of the suspended
2229 terminal device.
2231 `suspend-tty' does nothing if it is called on a device that is already
2232 suspended.
2234 A suspended tty may be resumed by calling `resume-tty' on it. */)
2235 (Lisp_Object tty)
2237 struct terminal *t = decode_tty_terminal (tty);
2238 FILE *f;
2240 if (!t)
2241 error ("Attempt to suspend a non-text terminal device");
2243 f = t->display_info.tty->input;
2245 if (f)
2247 /* First run `suspend-tty-functions' and then clean up the tty
2248 state because `suspend-tty-functions' might need to change
2249 the tty state. */
2250 Lisp_Object term;
2251 XSETTERMINAL (term, t);
2252 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2254 reset_sys_modes (t->display_info.tty);
2255 delete_keyboard_wait_descriptor (fileno (f));
2257 #ifndef MSDOS
2258 fclose (f);
2259 if (f != t->display_info.tty->output)
2260 fclose (t->display_info.tty->output);
2261 #endif
2263 t->display_info.tty->input = 0;
2264 t->display_info.tty->output = 0;
2266 if (FRAMEP (t->display_info.tty->top_frame))
2267 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2271 /* Clear display hooks to prevent further output. */
2272 clear_tty_hooks (t);
2274 return Qnil;
2277 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2278 doc: /* Resume the previously suspended terminal device TTY.
2279 The terminal is opened and reinitialized. Frames that are on the
2280 suspended terminal are revived.
2282 It is an error to resume a terminal while another terminal is active
2283 on the same device.
2285 This function runs `resume-tty-functions' after resuming the terminal.
2286 The functions are run with one arg, the id of the resumed terminal
2287 device.
2289 `resume-tty' does nothing if it is called on a device that is not
2290 suspended.
2292 TTY may be a terminal object, a frame, or nil (meaning the selected
2293 frame's terminal). */)
2294 (Lisp_Object tty)
2296 struct terminal *t = decode_tty_terminal (tty);
2297 int fd;
2299 if (!t)
2300 error ("Attempt to resume a non-text terminal device");
2302 if (!t->display_info.tty->input)
2304 if (get_named_terminal (t->display_info.tty->name))
2305 error ("Cannot resume display while another display is active on the same device");
2307 #ifdef MSDOS
2308 t->display_info.tty->output = stdout;
2309 t->display_info.tty->input = stdin;
2310 #else /* !MSDOS */
2311 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2312 t->display_info.tty->input = t->display_info.tty->output
2313 = fd < 0 ? 0 : fdopen (fd, "w+");
2315 if (! t->display_info.tty->input)
2317 int open_errno = errno;
2318 emacs_close (fd);
2319 report_file_errno ("Cannot reopen tty device",
2320 build_string (t->display_info.tty->name),
2321 open_errno);
2324 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2325 dissociate_if_controlling_tty (fd);
2326 #endif
2328 add_keyboard_wait_descriptor (fd);
2330 if (FRAMEP (t->display_info.tty->top_frame))
2332 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2333 int width, height;
2334 int old_height = FRAME_COLS (f);
2335 int old_width = FRAME_TOTAL_LINES (f);
2337 /* Check if terminal/window size has changed while the frame
2338 was suspended. */
2339 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2340 if (width != old_width || height != old_height)
2341 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2342 0, 0, 0, 0);
2343 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2346 set_tty_hooks (t);
2347 init_sys_modes (t->display_info.tty);
2349 /* Run `resume-tty-functions'. */
2350 Lisp_Object term;
2351 XSETTERMINAL (term, t);
2352 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2355 set_tty_hooks (t);
2357 return Qnil;
2361 /***********************************************************************
2362 Mouse
2363 ***********************************************************************/
2365 #ifdef HAVE_GPM
2367 #ifndef HAVE_WINDOW_SYSTEM
2368 void
2369 term_mouse_moveto (int x, int y)
2371 /* TODO: how to set mouse position?
2372 const char *name;
2373 int fd;
2374 name = (const char *) ttyname (0);
2375 fd = emacs_open (name, O_WRONLY, 0);
2376 SOME_FUNCTION (x, y, fd);
2377 emacs_close (fd);
2378 last_mouse_x = x;
2379 last_mouse_y = y; */
2381 #endif /* HAVE_WINDOW_SYSTEM */
2383 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2384 void
2385 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2386 int start_hpos, int end_hpos,
2387 enum draw_glyphs_face draw)
2389 int nglyphs = end_hpos - start_hpos;
2390 struct frame *f = XFRAME (WINDOW_FRAME (w));
2391 struct tty_display_info *tty = FRAME_TTY (f);
2392 int face_id = tty->mouse_highlight.mouse_face_face_id;
2393 int save_x, save_y, pos_x, pos_y;
2395 if (end_hpos >= row->used[TEXT_AREA])
2396 nglyphs = row->used[TEXT_AREA] - start_hpos;
2398 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2399 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2401 /* Save current cursor co-ordinates. */
2402 save_y = curY (tty);
2403 save_x = curX (tty);
2404 cursor_to (f, pos_y, pos_x);
2406 if (draw == DRAW_MOUSE_FACE)
2407 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2408 nglyphs, face_id);
2409 else if (draw == DRAW_NORMAL_TEXT)
2410 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2412 cursor_to (f, save_y, save_x);
2415 static bool
2416 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2418 /* Has the mouse moved off the glyph it was on at the last sighting? */
2419 if (event->x != last_mouse_x || event->y != last_mouse_y)
2421 frame->mouse_moved = 1;
2422 note_mouse_highlight (frame, event->x, event->y);
2423 /* Remember which glyph we're now on. */
2424 last_mouse_x = event->x;
2425 last_mouse_y = event->y;
2426 return 1;
2428 return 0;
2431 /* Return the Time that corresponds to T. Wrap around on overflow. */
2432 static Time
2433 timeval_to_Time (struct timeval const *t)
2435 Time s_1000, ms;
2437 s_1000 = t->tv_sec;
2438 s_1000 *= 1000;
2439 ms = t->tv_usec / 1000;
2440 return s_1000 + ms;
2443 /* Return the current position of the mouse.
2445 Set *f to the frame the mouse is in, or zero if the mouse is in no
2446 Emacs frame. If it is set to zero, all the other arguments are
2447 garbage.
2449 Set *bar_window to Qnil, and *x and *y to the column and
2450 row of the character cell the mouse is over.
2452 Set *timeptr to the time the mouse was at the returned position.
2454 This clears mouse_moved until the next motion
2455 event arrives. */
2456 static void
2457 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2458 enum scroll_bar_part *part, Lisp_Object *x,
2459 Lisp_Object *y, Time *timeptr)
2461 struct timeval now;
2463 *fp = SELECTED_FRAME ();
2464 (*fp)->mouse_moved = 0;
2466 *bar_window = Qnil;
2467 *part = scroll_bar_above_handle;
2469 XSETINT (*x, last_mouse_x);
2470 XSETINT (*y, last_mouse_y);
2471 gettimeofday(&now, 0);
2472 *timeptr = timeval_to_Time (&now);
2475 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2477 If the event is a button press, then note that we have grabbed
2478 the mouse. */
2480 static Lisp_Object
2481 term_mouse_click (struct input_event *result, Gpm_Event *event,
2482 struct frame *f)
2484 struct timeval now;
2485 int i, j;
2487 result->kind = GPM_CLICK_EVENT;
2488 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2490 if (event->buttons & j) {
2491 result->code = i; /* button number */
2492 break;
2495 gettimeofday(&now, 0);
2496 result->timestamp = timeval_to_Time (&now);
2498 if (event->type & GPM_UP)
2499 result->modifiers = up_modifier;
2500 else if (event->type & GPM_DOWN)
2501 result->modifiers = down_modifier;
2502 else
2503 result->modifiers = 0;
2505 if (event->type & GPM_SINGLE)
2506 result->modifiers |= click_modifier;
2508 if (event->type & GPM_DOUBLE)
2509 result->modifiers |= double_modifier;
2511 if (event->type & GPM_TRIPLE)
2512 result->modifiers |= triple_modifier;
2514 if (event->type & GPM_DRAG)
2515 result->modifiers |= drag_modifier;
2517 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2519 /* 1 << KG_SHIFT */
2520 if (event->modifiers & (1 << 0))
2521 result->modifiers |= shift_modifier;
2523 /* 1 << KG_CTRL */
2524 if (event->modifiers & (1 << 2))
2525 result->modifiers |= ctrl_modifier;
2527 /* 1 << KG_ALT || KG_ALTGR */
2528 if (event->modifiers & (1 << 3)
2529 || event->modifiers & (1 << 1))
2530 result->modifiers |= meta_modifier;
2533 XSETINT (result->x, event->x);
2534 XSETINT (result->y, event->y);
2535 XSETFRAME (result->frame_or_window, f);
2536 result->arg = Qnil;
2537 return Qnil;
2541 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, 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 IF_LINT (= 0);
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 (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 (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);
3406 block_input ();
3407 tty_menu_destroy (menu);
3408 unblock_input ();
3411 /* Return the zero-based index of the last menu-bar item on frame F. */
3412 static int
3413 tty_menu_last_menubar_item (struct frame *f)
3415 int i = 0;
3417 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3418 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3420 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3422 while (i < ASIZE (items))
3424 Lisp_Object str;
3426 str = AREF (items, i + 1);
3427 if (NILP (str))
3428 break;
3429 i += 4;
3431 i -= 4; /* Went one too far! */
3433 return i;
3436 /* Find in frame F's menu bar the menu item that is next or previous
3437 to the item at X/Y, and return that item's position in X/Y. WHICH
3438 says which one--next or previous--item to look for. X and Y are
3439 measured in character cells. This should only be called on TTY
3440 frames. */
3441 static void
3442 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3444 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3445 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3447 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3448 int last_i = tty_menu_last_menubar_item (f);
3449 int i, prev_x;
3451 /* This loop assumes a single menu-bar line, and will fail to
3452 find an item if it is not in the first line. Note that
3453 make_lispy_event in keyboard.c makes the same assumption. */
3454 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3456 Lisp_Object pos, str;
3457 int ix;
3459 str = AREF (items, i + 1);
3460 pos = AREF (items, i + 3);
3461 if (NILP (str))
3462 return;
3463 ix = XINT (pos);
3464 if (ix <= *x
3465 /* We use <= so the blank between 2 items on a TTY is
3466 considered part of the previous item. */
3467 && *x <= ix + menu_item_width (SDATA (str)))
3469 /* Found current item. Now compute the X coordinate of
3470 the previous or next item. */
3471 if (which == TTYM_NEXT)
3473 if (i < last_i)
3474 *x = XINT (AREF (items, i + 4 + 3));
3475 else
3476 *x = 0; /* Wrap around to the first item. */
3478 else if (prev_x < 0)
3480 /* Wrap around to the last item. */
3481 *x = XINT (AREF (items, last_i + 3));
3483 else
3484 *x = prev_x;
3485 return;
3487 prev_x = ix;
3492 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3493 Lisp_Object
3494 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3495 Lisp_Object title, const char **error_name)
3497 tty_menu *menu;
3498 int pane, selidx, lpane, status;
3499 Lisp_Object entry, pane_prefix;
3500 char *datap;
3501 int ulx, uly, width, height;
3502 int item_x, item_y;
3503 int dispwidth, dispheight;
3504 int i, j, lines, maxlines;
3505 int maxwidth;
3506 ptrdiff_t specpdl_count;
3508 eassert (FRAME_TERMCAP_P (f));
3510 *error_name = 0;
3511 if (menu_items_n_panes == 0)
3512 return Qnil;
3514 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3516 *error_name = "Empty menu";
3517 return Qnil;
3520 /* Make the menu on that window. */
3521 menu = tty_menu_create ();
3523 /* Don't GC while we prepare and show the menu, because we give the
3524 menu functions pointers to the contents of strings. */
3525 specpdl_count = inhibit_garbage_collection ();
3527 /* Avoid crashes if, e.g., another client will connect while we
3528 are in a menu. */
3529 temporarily_switch_to_single_kboard (f);
3531 /* Adjust coordinates to be root-window-relative. */
3532 item_x = x += f->left_pos;
3533 item_y = y += f->top_pos;
3535 /* Create all the necessary panes and their items. */
3536 USE_SAFE_ALLOCA;
3537 maxwidth = maxlines = lines = i = 0;
3538 lpane = TTYM_FAILURE;
3539 while (i < menu_items_used)
3541 if (EQ (AREF (menu_items, i), Qt))
3543 /* Create a new pane. */
3544 Lisp_Object pane_name, prefix;
3545 const char *pane_string;
3547 maxlines = max (maxlines, lines);
3548 lines = 0;
3549 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3550 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3551 pane_string = (NILP (pane_name)
3552 ? "" : SSDATA (pane_name));
3553 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3554 pane_string++;
3556 lpane = tty_menu_add_pane (menu, pane_string);
3557 if (lpane == TTYM_FAILURE)
3559 tty_menu_destroy (menu);
3560 *error_name = "Can't create pane";
3561 entry = Qnil;
3562 goto tty_menu_end;
3564 i += MENU_ITEMS_PANE_LENGTH;
3566 /* Find the width of the widest item in this pane. */
3567 j = i;
3568 while (j < menu_items_used)
3570 Lisp_Object item;
3571 item = AREF (menu_items, j);
3572 if (EQ (item, Qt))
3573 break;
3574 if (NILP (item))
3576 j++;
3577 continue;
3579 width = SBYTES (item);
3580 if (width > maxwidth)
3581 maxwidth = width;
3583 j += MENU_ITEMS_ITEM_LENGTH;
3586 /* Ignore a nil in the item list.
3587 It's meaningful only for dialog boxes. */
3588 else if (EQ (AREF (menu_items, i), Qquote))
3589 i += 1;
3590 else
3592 /* Create a new item within current pane. */
3593 Lisp_Object item_name, enable, descrip, help;
3594 char *item_data;
3595 char const *help_string;
3597 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3598 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3599 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3600 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3601 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3603 if (!NILP (descrip))
3605 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3606 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3607 for (j = SCHARS (item_name); j < maxwidth; j++)
3608 item_data[j] = ' ';
3609 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3610 item_data[j + SBYTES (descrip)] = 0;
3612 else
3613 item_data = SSDATA (item_name);
3615 if (lpane == TTYM_FAILURE
3616 || (! tty_menu_add_selection (menu, lpane, item_data,
3617 !NILP (enable), help_string)))
3619 tty_menu_destroy (menu);
3620 *error_name = "Can't add selection to menu";
3621 entry = Qnil;
3622 goto tty_menu_end;
3624 i += MENU_ITEMS_ITEM_LENGTH;
3625 lines++;
3629 maxlines = max (maxlines, lines);
3631 /* All set and ready to fly. */
3632 dispwidth = f->text_cols;
3633 dispheight = f->text_lines;
3634 x = min (x, dispwidth);
3635 y = min (y, dispheight);
3636 x = max (x, 1);
3637 y = max (y, 1);
3638 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3639 if (ulx + width > dispwidth)
3641 x -= (ulx + width) - dispwidth;
3642 ulx = dispwidth - width;
3644 if (uly + height > dispheight)
3646 y -= (uly + height) - dispheight;
3647 uly = dispheight - height;
3650 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3652 /* Move the menu away of the echo area, to avoid overwriting the
3653 menu with help echo messages or vice versa. */
3654 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3656 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3657 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3659 else
3661 y -= 2;
3662 uly -= 2;
3666 if (ulx < 0) x -= ulx;
3667 if (uly < 0) y -= uly;
3669 #if 0
3670 /* This code doesn't make sense on a TTY, since it can easily annul
3671 the adjustments above that carefully avoid truncation of the menu
3672 items. I think it was written to fix some problem that only
3673 happens on X11. */
3674 if (! for_click)
3676 /* If position was not given by a mouse click, adjust so upper left
3677 corner of the menu as a whole ends up at given coordinates. This
3678 is what x-popup-menu says in its documentation. */
3679 x += width / 2;
3680 y += 1.5 * height / (maxlines + 2);
3682 #endif
3684 pane = selidx = 0;
3686 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3688 specbind (Qoverriding_terminal_local_map,
3689 Fsymbol_value (Qtty_menu_navigation_map));
3690 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3691 tty_menu_help_callback,
3692 menuflags & MENU_KBD_NAVIGATION);
3693 entry = pane_prefix = Qnil;
3695 switch (status)
3697 case TTYM_SUCCESS:
3698 /* Find the item number SELIDX in pane number PANE. */
3699 i = 0;
3700 while (i < menu_items_used)
3702 if (EQ (AREF (menu_items, i), Qt))
3704 if (pane == 0)
3705 pane_prefix
3706 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3707 pane--;
3708 i += MENU_ITEMS_PANE_LENGTH;
3710 else
3712 if (pane == -1)
3714 if (selidx == 0)
3716 entry
3717 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3718 if (menuflags & MENU_KEYMAPS)
3720 entry = Fcons (entry, Qnil);
3721 if (!NILP (pane_prefix))
3722 entry = Fcons (pane_prefix, entry);
3724 break;
3726 selidx--;
3728 i += MENU_ITEMS_ITEM_LENGTH;
3731 break;
3733 case TTYM_NEXT:
3734 case TTYM_PREV:
3735 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3736 entry = Fcons (make_number (item_x), make_number (item_y));
3737 break;
3739 case TTYM_FAILURE:
3740 *error_name = "Can't activate menu";
3741 case TTYM_IA_SELECT:
3742 break;
3743 case TTYM_NO_SELECT:
3744 /* If the selected frame was changed while we displayed a menu,
3745 throw to top level in order to undo any temporary settings
3746 made by TTY menu code. */
3747 if (f != SELECTED_FRAME ())
3748 Ftop_level ();
3749 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3750 the menu was invoked with a mouse event as POSITION). */
3751 if (!(menuflags & MENU_FOR_CLICK))
3752 Fsignal (Qquit, Qnil);
3753 break;
3756 tty_menu_end:
3758 SAFE_FREE ();
3759 unbind_to (specpdl_count, Qnil);
3760 return entry;
3763 #endif /* !MSDOS */
3766 #ifndef MSDOS
3767 /***********************************************************************
3768 Initialization
3769 ***********************************************************************/
3771 /* Initialize the tty-dependent part of frame F. The frame must
3772 already have its device initialized. */
3774 void
3775 create_tty_output (struct frame *f)
3777 struct tty_output *t = xzalloc (sizeof *t);
3779 eassert (FRAME_TERMCAP_P (f));
3781 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3783 f->output_data.tty = t;
3786 /* Delete frame F's face cache, and its tty-dependent part. */
3788 static void
3789 tty_free_frame_resources (struct frame *f)
3791 eassert (FRAME_TERMCAP_P (f));
3792 free_frame_faces (f);
3793 xfree (f->output_data.tty);
3796 #else /* MSDOS */
3798 /* Delete frame F's face cache. */
3800 static void
3801 tty_free_frame_resources (struct frame *f)
3803 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3804 free_frame_faces (f);
3806 #endif /* MSDOS */
3808 /* Reset the hooks in TERMINAL. */
3810 static void
3811 clear_tty_hooks (struct terminal *terminal)
3813 terminal->rif = 0;
3814 terminal->cursor_to_hook = 0;
3815 terminal->raw_cursor_to_hook = 0;
3816 terminal->clear_to_end_hook = 0;
3817 terminal->clear_frame_hook = 0;
3818 terminal->clear_end_of_line_hook = 0;
3819 terminal->ins_del_lines_hook = 0;
3820 terminal->insert_glyphs_hook = 0;
3821 terminal->write_glyphs_hook = 0;
3822 terminal->delete_glyphs_hook = 0;
3823 terminal->ring_bell_hook = 0;
3824 terminal->reset_terminal_modes_hook = 0;
3825 terminal->set_terminal_modes_hook = 0;
3826 terminal->update_begin_hook = 0;
3827 terminal->update_end_hook = 0;
3828 terminal->set_terminal_window_hook = 0;
3829 terminal->mouse_position_hook = 0;
3830 terminal->frame_rehighlight_hook = 0;
3831 terminal->frame_raise_lower_hook = 0;
3832 terminal->fullscreen_hook = 0;
3833 terminal->menu_show_hook = 0;
3834 terminal->set_vertical_scroll_bar_hook = 0;
3835 terminal->set_horizontal_scroll_bar_hook = 0;
3836 terminal->condemn_scroll_bars_hook = 0;
3837 terminal->redeem_scroll_bar_hook = 0;
3838 terminal->judge_scroll_bars_hook = 0;
3839 terminal->read_socket_hook = 0;
3840 terminal->frame_up_to_date_hook = 0;
3842 /* Leave these two set, or suspended frames are not deleted
3843 correctly. */
3844 terminal->delete_frame_hook = &tty_free_frame_resources;
3845 terminal->delete_terminal_hook = &delete_tty;
3848 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3850 static void
3851 set_tty_hooks (struct terminal *terminal)
3853 terminal->cursor_to_hook = &tty_cursor_to;
3854 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3855 terminal->clear_to_end_hook = &tty_clear_to_end;
3856 terminal->clear_frame_hook = &tty_clear_frame;
3857 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3858 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3859 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3860 terminal->write_glyphs_hook = &tty_write_glyphs;
3861 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3862 terminal->ring_bell_hook = &tty_ring_bell;
3863 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3864 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3865 terminal->update_end_hook = &tty_update_end;
3866 #ifdef MSDOS
3867 terminal->menu_show_hook = &x_menu_show;
3868 #else
3869 terminal->menu_show_hook = &tty_menu_show;
3870 #endif
3871 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3872 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3873 terminal->delete_frame_hook = &tty_free_frame_resources;
3874 terminal->delete_terminal_hook = &delete_tty;
3875 /* Other hooks are NULL by default. */
3878 /* If FD is the controlling terminal, drop it. */
3879 static void
3880 dissociate_if_controlling_tty (int fd)
3882 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3883 so dissociate it by invoking setsid. */
3884 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3886 #ifdef TIOCNOTTY
3887 /* setsid failed, presumably because Emacs is already a process
3888 group leader. Fall back on the obsolescent way to dissociate
3889 a controlling tty. */
3890 sigset_t oldset;
3891 block_tty_out_signal (&oldset);
3892 ioctl (fd, TIOCNOTTY, 0);
3893 unblock_tty_out_signal (&oldset);
3894 #endif
3898 /* Create a termcap display on the tty device with the given name and
3899 type.
3901 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3902 Otherwise NAME should be a path to the tty device file,
3903 e.g. "/dev/pts/7".
3905 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3907 If MUST_SUCCEED is true, then all errors are fatal. */
3909 struct terminal *
3910 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3912 char *area;
3913 char **address = &area;
3914 int status;
3915 struct tty_display_info *tty = NULL;
3916 struct terminal *terminal = NULL;
3917 sigset_t oldset;
3918 bool ctty = false; /* True if asked to open controlling tty. */
3920 if (!terminal_type)
3921 maybe_fatal (must_succeed, 0,
3922 "Unknown terminal type",
3923 "Unknown terminal type");
3925 if (name == NULL)
3926 name = DEV_TTY;
3927 if (!strcmp (name, DEV_TTY))
3928 ctty = 1;
3930 /* If we already have a terminal on the given device, use that. If
3931 all such terminals are suspended, create a new one instead. */
3932 /* XXX Perhaps this should be made explicit by having init_tty
3933 always create a new terminal and separating terminal and frame
3934 creation on Lisp level. */
3935 terminal = get_named_terminal (name);
3936 if (terminal)
3937 return terminal;
3939 terminal = create_terminal (output_termcap, NULL);
3940 #ifdef MSDOS
3941 if (been_here > 0)
3942 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3943 name, "");
3944 been_here = 1;
3945 tty = &the_only_display_info;
3946 #else
3947 tty = xzalloc (sizeof *tty);
3948 #endif
3949 tty->top_frame = Qnil;
3950 tty->next = tty_list;
3951 tty_list = tty;
3953 terminal->display_info.tty = tty;
3954 tty->terminal = terminal;
3956 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3957 Wcm_clear (tty);
3959 encode_terminal_src_size = 0;
3960 encode_terminal_dst_size = 0;
3963 #ifndef DOS_NT
3964 set_tty_hooks (terminal);
3967 /* Open the terminal device. */
3969 /* If !ctty, don't recognize it as our controlling terminal, and
3970 don't make it the controlling tty if we don't have one now.
3972 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3973 defined on Hurd. On other systems, we need to explicitly
3974 dissociate ourselves from the controlling tty when we want to
3975 open a frame on the same terminal. */
3976 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3977 int fd = emacs_open (name, flags, 0);
3978 tty->input = tty->output
3979 = ((fd < 0 || ! isatty (fd))
3980 ? NULL
3981 : fdopen (fd, "w+"));
3983 if (! tty->input)
3985 char const *diagnostic
3986 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3987 emacs_close (fd);
3988 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
3991 tty->name = xstrdup (name);
3992 terminal->name = xstrdup (name);
3994 if (!O_IGNORE_CTTY && !ctty)
3995 dissociate_if_controlling_tty (fd);
3998 tty->type = xstrdup (terminal_type);
4000 add_keyboard_wait_descriptor (fileno (tty->input));
4002 Wcm_clear (tty);
4004 /* On some systems, tgetent tries to access the controlling
4005 terminal. */
4006 block_tty_out_signal (&oldset);
4007 status = tgetent (tty->termcap_term_buffer, terminal_type);
4008 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4009 emacs_abort ();
4010 unblock_tty_out_signal (&oldset);
4012 if (status < 0)
4014 #ifdef TERMINFO
4015 maybe_fatal (must_succeed, terminal,
4016 "Cannot open terminfo database file",
4017 "Cannot open terminfo database file");
4018 #else
4019 maybe_fatal (must_succeed, terminal,
4020 "Cannot open termcap database file",
4021 "Cannot open termcap database file");
4022 #endif
4024 if (status == 0)
4026 maybe_fatal (must_succeed, terminal,
4027 "Terminal type %s is not defined",
4028 "Terminal type %s is not defined.\n\
4029 If that is not the actual type of terminal you have,\n\
4030 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4031 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4032 #ifdef TERMINFO
4033 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4034 #else
4035 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4036 #endif
4037 terminal_type);
4040 area = tty->termcap_strings_buffer;
4041 tty->TS_ins_line = tgetstr ("al", address);
4042 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4043 tty->TS_bell = tgetstr ("bl", address);
4044 BackTab (tty) = tgetstr ("bt", address);
4045 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4046 tty->TS_clr_line = tgetstr ("ce", address);
4047 tty->TS_clr_frame = tgetstr ("cl", address);
4048 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4049 AbsPosition (tty) = tgetstr ("cm", address);
4050 CR (tty) = tgetstr ("cr", address);
4051 tty->TS_set_scroll_region = tgetstr ("cs", address);
4052 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4053 RowPosition (tty) = tgetstr ("cv", address);
4054 tty->TS_del_char = tgetstr ("dc", address);
4055 tty->TS_del_multi_chars = tgetstr ("DC", address);
4056 tty->TS_del_line = tgetstr ("dl", address);
4057 tty->TS_del_multi_lines = tgetstr ("DL", address);
4058 tty->TS_delete_mode = tgetstr ("dm", address);
4059 tty->TS_end_delete_mode = tgetstr ("ed", address);
4060 tty->TS_end_insert_mode = tgetstr ("ei", address);
4061 Home (tty) = tgetstr ("ho", address);
4062 tty->TS_ins_char = tgetstr ("ic", address);
4063 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4064 tty->TS_insert_mode = tgetstr ("im", address);
4065 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4066 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4067 tty->TS_keypad_mode = tgetstr ("ks", address);
4068 LastLine (tty) = tgetstr ("ll", address);
4069 Right (tty) = tgetstr ("nd", address);
4070 Down (tty) = tgetstr ("do", address);
4071 if (!Down (tty))
4072 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4073 if (tgetflag ("bs"))
4074 Left (tty) = "\b"; /* Can't possibly be longer! */
4075 else /* (Actually, "bs" is obsolete...) */
4076 Left (tty) = tgetstr ("le", address);
4077 if (!Left (tty))
4078 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4079 tty->TS_pad_char = tgetstr ("pc", address);
4080 tty->TS_repeat = tgetstr ("rp", address);
4081 tty->TS_end_standout_mode = tgetstr ("se", address);
4082 tty->TS_fwd_scroll = tgetstr ("sf", address);
4083 tty->TS_standout_mode = tgetstr ("so", address);
4084 tty->TS_rev_scroll = tgetstr ("sr", address);
4085 tty->Wcm->cm_tab = tgetstr ("ta", address);
4086 tty->TS_end_termcap_modes = tgetstr ("te", address);
4087 tty->TS_termcap_modes = tgetstr ("ti", address);
4088 Up (tty) = tgetstr ("up", address);
4089 tty->TS_visible_bell = tgetstr ("vb", address);
4090 tty->TS_cursor_normal = tgetstr ("ve", address);
4091 tty->TS_cursor_visible = tgetstr ("vs", address);
4092 tty->TS_cursor_invisible = tgetstr ("vi", address);
4093 tty->TS_set_window = tgetstr ("wi", address);
4095 tty->TS_enter_underline_mode = tgetstr ("us", address);
4096 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4097 tty->TS_enter_bold_mode = tgetstr ("md", address);
4098 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4099 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4100 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4101 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4102 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4103 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4105 MultiUp (tty) = tgetstr ("UP", address);
4106 MultiDown (tty) = tgetstr ("DO", address);
4107 MultiLeft (tty) = tgetstr ("LE", address);
4108 MultiRight (tty) = tgetstr ("RI", address);
4110 /* SVr4/ANSI color support. If "op" isn't available, don't support
4111 color because we can't switch back to the default foreground and
4112 background. */
4113 tty->TS_orig_pair = tgetstr ("op", address);
4114 if (tty->TS_orig_pair)
4116 tty->TS_set_foreground = tgetstr ("AF", address);
4117 tty->TS_set_background = tgetstr ("AB", address);
4118 if (!tty->TS_set_foreground)
4120 /* SVr4. */
4121 tty->TS_set_foreground = tgetstr ("Sf", address);
4122 tty->TS_set_background = tgetstr ("Sb", address);
4125 tty->TN_max_colors = tgetnum ("Co");
4126 tty->TN_max_pairs = tgetnum ("pa");
4128 tty->TN_no_color_video = tgetnum ("NC");
4129 if (tty->TN_no_color_video == -1)
4130 tty->TN_no_color_video = 0;
4133 tty_default_color_capabilities (tty, 1);
4135 MagicWrap (tty) = tgetflag ("xn");
4136 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4137 the former flag imply the latter. */
4138 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4139 tty->memory_below_frame = tgetflag ("db");
4140 tty->TF_hazeltine = tgetflag ("hz");
4141 tty->must_write_spaces = tgetflag ("in");
4142 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4143 tty->TF_insmode_motion = tgetflag ("mi");
4144 tty->TF_standout_motion = tgetflag ("ms");
4145 tty->TF_underscore = tgetflag ("ul");
4146 tty->TF_teleray = tgetflag ("xt");
4148 #else /* DOS_NT */
4149 #ifdef WINDOWSNT
4151 struct frame *f = XFRAME (selected_frame);
4152 int height, width;
4154 initialize_w32_display (terminal, &width, &height);
4156 FrameRows (tty) = height;
4157 FrameCols (tty) = width;
4158 tty->specified_window = height;
4160 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4161 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4162 tty->char_ins_del_ok = 1;
4163 baud_rate = 19200;
4165 #else /* MSDOS */
4167 int height, width;
4168 if (strcmp (terminal_type, "internal") == 0)
4169 terminal->type = output_msdos_raw;
4170 initialize_msdos_display (terminal);
4172 get_tty_size (fileno (tty->input), &width, &height);
4173 FrameCols (tty) = width;
4174 FrameRows (tty) = height;
4175 tty->char_ins_del_ok = 0;
4176 init_baud_rate (fileno (tty->input));
4178 #endif /* MSDOS */
4179 tty->output = stdout;
4180 tty->input = stdin;
4181 /* The following two are inaccessible from w32console.c. */
4182 terminal->delete_frame_hook = &tty_free_frame_resources;
4183 terminal->delete_terminal_hook = &delete_tty;
4185 tty->name = xstrdup (name);
4186 terminal->name = xstrdup (name);
4187 tty->type = xstrdup (terminal_type);
4189 add_keyboard_wait_descriptor (0);
4191 tty->delete_in_insert_mode = 1;
4193 UseTabs (tty) = 0;
4194 tty->scroll_region_ok = 0;
4196 /* Seems to insert lines when it's not supposed to, messing up the
4197 display. In doing a trace, it didn't seem to be called much, so I
4198 don't think we're losing anything by turning it off. */
4199 tty->line_ins_del_ok = 0;
4201 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4202 #endif /* DOS_NT */
4204 #ifdef HAVE_GPM
4205 terminal->mouse_position_hook = term_mouse_position;
4206 tty->mouse_highlight.mouse_face_window = Qnil;
4207 #endif
4209 terminal->kboard = allocate_kboard (Qnil);
4210 terminal->kboard->reference_count++;
4211 /* Don't let the initial kboard remain current longer than necessary.
4212 That would cause problems if a file loaded on startup tries to
4213 prompt in the mini-buffer. */
4214 if (current_kboard == initial_kboard)
4215 current_kboard = terminal->kboard;
4216 #ifndef DOS_NT
4217 term_get_fkeys (address, terminal->kboard);
4219 /* Get frame size from system, or else from termcap. */
4221 int height, width;
4222 get_tty_size (fileno (tty->input), &width, &height);
4223 FrameCols (tty) = width;
4224 FrameRows (tty) = height;
4227 if (FrameCols (tty) <= 0)
4228 FrameCols (tty) = tgetnum ("co");
4229 if (FrameRows (tty) <= 0)
4230 FrameRows (tty) = tgetnum ("li");
4232 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4233 maybe_fatal (must_succeed, terminal,
4234 "Screen size %dx%d is too small",
4235 "Screen size %dx%d is too small",
4236 FrameCols (tty), FrameRows (tty));
4238 TabWidth (tty) = tgetnum ("tw");
4240 if (!tty->TS_bell)
4241 tty->TS_bell = "\07";
4243 if (!tty->TS_fwd_scroll)
4244 tty->TS_fwd_scroll = Down (tty);
4246 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4248 if (TabWidth (tty) < 0)
4249 TabWidth (tty) = 8;
4251 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4252 and newer termcap doc does not seem to say there is a default.
4253 if (!tty->Wcm->cm_tab)
4254 tty->Wcm->cm_tab = "\t";
4257 /* We don't support standout modes that use `magic cookies', so
4258 turn off any that do. */
4259 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4261 tty->TS_standout_mode = 0;
4262 tty->TS_end_standout_mode = 0;
4264 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4266 tty->TS_enter_underline_mode = 0;
4267 tty->TS_exit_underline_mode = 0;
4270 /* If there's no standout mode, try to use underlining instead. */
4271 if (tty->TS_standout_mode == 0)
4273 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4274 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4277 /* If no `se' string, try using a `me' string instead.
4278 If that fails, we can't use standout mode at all. */
4279 if (tty->TS_end_standout_mode == 0)
4281 char *s = tgetstr ("me", address);
4282 if (s != 0)
4283 tty->TS_end_standout_mode = s;
4284 else
4285 tty->TS_standout_mode = 0;
4288 if (tty->TF_teleray)
4290 tty->Wcm->cm_tab = 0;
4291 /* We can't support standout mode, because it uses magic cookies. */
4292 tty->TS_standout_mode = 0;
4293 /* But that means we cannot rely on ^M to go to column zero! */
4294 CR (tty) = 0;
4295 /* LF can't be trusted either -- can alter hpos. */
4296 /* If move at column 0 thru a line with TS_standout_mode. */
4297 Down (tty) = 0;
4300 tty->specified_window = FrameRows (tty);
4302 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4304 maybe_fatal (must_succeed, terminal,
4305 "Terminal type \"%s\" is not powerful enough to run Emacs",
4306 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4307 It lacks the ability to position the cursor.\n\
4308 If that is not the actual type of terminal you have,\n\
4309 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4310 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4311 # ifdef TERMINFO
4312 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4313 # else /* TERMCAP */
4314 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4315 # endif /* TERMINFO */
4316 terminal_type);
4319 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4320 maybe_fatal (must_succeed, terminal,
4321 "Could not determine the frame size",
4322 "Could not determine the frame size");
4324 tty->delete_in_insert_mode
4325 = tty->TS_delete_mode && tty->TS_insert_mode
4326 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4328 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4330 tty->scroll_region_ok
4331 = (tty->Wcm->cm_abs
4332 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4334 tty->line_ins_del_ok
4335 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4336 && (tty->TS_del_line || tty->TS_del_multi_lines))
4337 || (tty->scroll_region_ok
4338 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4340 tty->char_ins_del_ok
4341 = ((tty->TS_ins_char || tty->TS_insert_mode
4342 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4343 && (tty->TS_del_char || tty->TS_del_multi_chars));
4345 init_baud_rate (fileno (tty->input));
4347 #endif /* not DOS_NT */
4349 /* Init system terminal modes (RAW or CBREAK, etc.). */
4350 init_sys_modes (tty);
4352 return terminal;
4356 static void
4357 vfatal (const char *str, va_list ap)
4359 fprintf (stderr, "emacs: ");
4360 vfprintf (stderr, str, ap);
4361 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4362 fprintf (stderr, "\n");
4363 fflush (stderr);
4364 exit (1);
4368 /* Auxiliary error-handling function for init_tty.
4369 Delete TERMINAL, then call error or fatal with str1 or str2,
4370 respectively, according to whether MUST_SUCCEED is true. */
4372 static void
4373 maybe_fatal (bool must_succeed, struct terminal *terminal,
4374 const char *str1, const char *str2, ...)
4376 va_list ap;
4377 va_start (ap, str2);
4378 if (terminal)
4379 delete_tty (terminal);
4381 if (must_succeed)
4382 vfatal (str2, ap);
4383 else
4384 verror (str1, ap);
4387 void
4388 fatal (const char *str, ...)
4390 va_list ap;
4391 va_start (ap, str);
4392 vfatal (str, ap);
4397 /* Delete the given tty terminal, closing all frames on it. */
4399 static void
4400 delete_tty (struct terminal *terminal)
4402 struct tty_display_info *tty;
4404 /* Protect against recursive calls. delete_frame in
4405 delete_terminal calls us back when it deletes our last frame. */
4406 if (!terminal->name)
4407 return;
4409 eassert (terminal->type == output_termcap);
4411 tty = terminal->display_info.tty;
4413 if (tty == tty_list)
4414 tty_list = tty->next;
4415 else
4417 struct tty_display_info *p;
4418 for (p = tty_list; p && p->next != tty; p = p->next)
4421 if (! p)
4422 /* This should not happen. */
4423 emacs_abort ();
4425 p->next = tty->next;
4426 tty->next = 0;
4429 /* reset_sys_modes needs a valid device, so this call needs to be
4430 before delete_terminal. */
4431 reset_sys_modes (tty);
4433 delete_terminal (terminal);
4435 xfree (tty->name);
4436 xfree (tty->type);
4438 if (tty->input)
4440 delete_keyboard_wait_descriptor (fileno (tty->input));
4441 if (tty->input != stdin)
4442 fclose (tty->input);
4444 if (tty->output && tty->output != stdout && tty->output != tty->input)
4445 fclose (tty->output);
4446 if (tty->termscript)
4447 fclose (tty->termscript);
4449 xfree (tty->old_tty);
4450 xfree (tty->Wcm);
4451 xfree (tty);
4454 void
4455 syms_of_term (void)
4457 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4458 doc: /* Non-nil means the system uses terminfo rather than termcap.
4459 This variable can be used by terminal emulator packages. */);
4460 #ifdef TERMINFO
4461 system_uses_terminfo = 1;
4462 #else
4463 system_uses_terminfo = 0;
4464 #endif
4466 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4467 doc: /* Functions run after suspending a tty.
4468 The functions are run with one argument, the terminal object to be suspended.
4469 See `suspend-tty'. */);
4470 Vsuspend_tty_functions = Qnil;
4473 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4474 doc: /* Functions run after resuming a tty.
4475 The functions are run with one argument, the terminal object that was revived.
4476 See `resume-tty'. */);
4477 Vresume_tty_functions = Qnil;
4479 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4480 doc: /* Non-nil means to make the cursor very visible.
4481 This only has an effect when running in a text terminal.
4482 What means \"very visible\" is up to your terminal. It may make the cursor
4483 bigger, or it may make it blink, or it may do nothing at all. */);
4484 visible_cursor = 1;
4486 defsubr (&Stty_display_color_p);
4487 defsubr (&Stty_display_color_cells);
4488 defsubr (&Stty_no_underline);
4489 defsubr (&Stty_type);
4490 defsubr (&Scontrolling_tty_p);
4491 defsubr (&Stty_top_frame);
4492 defsubr (&Ssuspend_tty);
4493 defsubr (&Sresume_tty);
4494 #ifdef HAVE_GPM
4495 defsubr (&Sgpm_mouse_start);
4496 defsubr (&Sgpm_mouse_stop);
4497 #endif /* HAVE_GPM */
4499 #ifndef DOS_NT
4500 default_orig_pair = NULL;
4501 default_set_foreground = NULL;
4502 default_set_background = NULL;
4503 #endif /* !DOS_NT */
4505 encode_terminal_src = NULL;
4506 encode_terminal_dst = NULL;
4508 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4509 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4511 #ifndef MSDOS
4512 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4513 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4514 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4515 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4516 DEFSYM (Qtty_menu_select, "tty-menu-select");
4517 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4518 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4519 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4520 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4521 #endif