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