; Typo fixes, mostly repeated words
[emacs.git] / src / term.c
blob06695d1ec61c49e0e88fd30fbda88517b45811a6
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 <https://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 /* Use only accessors like CDR_SAFE and assq_no_quit to avoid any
159 form of quitting or signaling an error, since this function can
160 run as part of the "emergency escape" procedure invoked in the
161 middle of GC, where quitting means crashing (Bug#17406). */
162 if (! terminal->name)
163 return;
164 struct tty_display_info *tty = terminal->display_info.tty;
166 for (Lisp_Object extra_codes
167 = CDR_SAFE (assq_no_quit (sym, terminal->param_alist));
168 CONSP (extra_codes);
169 extra_codes = XCDR (extra_codes))
171 Lisp_Object string = XCAR (extra_codes);
172 if (STRINGP (string))
174 fwrite_unlocked (SDATA (string), 1, SBYTES (string), tty->output);
175 if (tty->termscript)
176 fwrite_unlocked (SDATA (string), 1, SBYTES (string),
177 tty->termscript);
182 static void
183 tty_set_terminal_modes (struct terminal *terminal)
185 struct tty_display_info *tty = terminal->display_info.tty;
187 if (tty->output)
189 if (tty->TS_termcap_modes)
190 OUTPUT (tty, tty->TS_termcap_modes);
191 else
193 /* Output enough newlines to scroll all the old screen contents
194 off the screen, so it won't be overwritten and lost. */
195 int i;
196 current_tty = tty;
197 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
198 cmputc ('\n');
201 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
202 OUTPUT_IF (tty, tty->TS_keypad_mode);
203 losecursor (tty);
204 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
205 fflush_unlocked (tty->output);
209 /* Reset termcap modes before exiting Emacs. */
211 static void
212 tty_reset_terminal_modes (struct terminal *terminal)
214 struct tty_display_info *tty = terminal->display_info.tty;
216 if (tty->output)
218 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
219 tty_turn_off_highlight (tty);
220 tty_turn_off_insert (tty);
221 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
222 OUTPUT_IF (tty, tty->TS_cursor_normal);
223 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
224 OUTPUT_IF (tty, tty->TS_orig_pair);
225 /* Output raw CR so kernel can track the cursor hpos. */
226 current_tty = tty;
227 cmputc ('\r');
228 fflush_unlocked (tty->output);
232 /* Flag the end of a display update on a termcap terminal. */
234 static void
235 tty_update_end (struct frame *f)
237 struct tty_display_info *tty = FRAME_TTY (f);
239 if (!XWINDOW (selected_window)->cursor_off_p)
240 tty_show_cursor (tty);
241 tty_turn_off_insert (tty);
242 tty_background_highlight (tty);
243 fflush_unlocked (tty->output);
246 /* The implementation of set_terminal_window for termcap frames. */
248 static void
249 tty_set_terminal_window (struct frame *f, int size)
251 struct tty_display_info *tty = FRAME_TTY (f);
253 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
254 if (FRAME_SCROLL_REGION_OK (f))
255 tty_set_scroll_region (f, 0, tty->specified_window);
258 static void
259 tty_set_scroll_region (struct frame *f, int start, int stop)
261 char *buf;
262 struct tty_display_info *tty = FRAME_TTY (f);
264 if (tty->TS_set_scroll_region)
265 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
266 else if (tty->TS_set_scroll_region_1)
267 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
268 FRAME_TOTAL_LINES (f), start,
269 FRAME_TOTAL_LINES (f) - stop,
270 FRAME_TOTAL_LINES (f));
271 else
272 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
274 OUTPUT (tty, buf);
275 xfree (buf);
276 losecursor (tty);
280 static void
281 tty_turn_on_insert (struct tty_display_info *tty)
283 if (!tty->insert_mode)
284 OUTPUT (tty, tty->TS_insert_mode);
285 tty->insert_mode = 1;
288 void
289 tty_turn_off_insert (struct tty_display_info *tty)
291 if (tty->insert_mode)
292 OUTPUT (tty, tty->TS_end_insert_mode);
293 tty->insert_mode = 0;
296 /* Handle highlighting. */
298 static void
299 tty_turn_off_highlight (struct tty_display_info *tty)
301 if (tty->standout_mode)
302 OUTPUT_IF (tty, tty->TS_end_standout_mode);
303 tty->standout_mode = 0;
306 static void
307 tty_turn_on_highlight (struct tty_display_info *tty)
309 if (!tty->standout_mode)
310 OUTPUT_IF (tty, tty->TS_standout_mode);
311 tty->standout_mode = 1;
314 static void
315 tty_toggle_highlight (struct tty_display_info *tty)
317 if (tty->standout_mode)
318 tty_turn_off_highlight (tty);
319 else
320 tty_turn_on_highlight (tty);
324 /* Make cursor invisible. */
326 static void
327 tty_hide_cursor (struct tty_display_info *tty)
329 if (tty->cursor_hidden == 0)
331 tty->cursor_hidden = 1;
332 #ifdef WINDOWSNT
333 w32con_hide_cursor ();
334 #else
335 OUTPUT_IF (tty, tty->TS_cursor_invisible);
336 #endif
341 /* Ensure that cursor is visible. */
343 static void
344 tty_show_cursor (struct tty_display_info *tty)
346 if (tty->cursor_hidden)
348 tty->cursor_hidden = 0;
349 #ifdef WINDOWSNT
350 w32con_show_cursor ();
351 #else
352 OUTPUT_IF (tty, tty->TS_cursor_normal);
353 if (visible_cursor)
354 OUTPUT_IF (tty, tty->TS_cursor_visible);
355 #endif
360 /* Set standout mode to the state it should be in for
361 empty space inside windows. What this is,
362 depends on the user option inverse-video. */
364 static void
365 tty_background_highlight (struct tty_display_info *tty)
367 if (inverse_video)
368 tty_turn_on_highlight (tty);
369 else
370 tty_turn_off_highlight (tty);
373 /* Set standout mode to the mode specified for the text to be output. */
375 static void
376 tty_highlight_if_desired (struct tty_display_info *tty)
378 if (inverse_video)
379 tty_turn_on_highlight (tty);
380 else
381 tty_turn_off_highlight (tty);
385 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
386 frame-relative coordinates. */
388 static void
389 tty_cursor_to (struct frame *f, int vpos, int hpos)
391 struct tty_display_info *tty = FRAME_TTY (f);
393 /* Detect the case where we are called from reset_sys_modes
394 and the costs have never been calculated. Do nothing. */
395 if (! tty->costs_set)
396 return;
398 if (curY (tty) == vpos
399 && curX (tty) == hpos)
400 return;
401 if (!tty->TF_standout_motion)
402 tty_background_highlight (tty);
403 if (!tty->TF_insmode_motion)
404 tty_turn_off_insert (tty);
405 cmgoto (tty, vpos, hpos);
408 /* Similar but don't take any account of the wasted characters. */
410 static void
411 tty_raw_cursor_to (struct frame *f, int row, int col)
413 struct tty_display_info *tty = FRAME_TTY (f);
415 if (curY (tty) == row
416 && curX (tty) == col)
417 return;
418 if (!tty->TF_standout_motion)
419 tty_background_highlight (tty);
420 if (!tty->TF_insmode_motion)
421 tty_turn_off_insert (tty);
422 cmgoto (tty, row, col);
425 /* Erase operations */
427 /* Clear from cursor to end of frame on a termcap device. */
429 static void
430 tty_clear_to_end (struct frame *f)
432 register int i;
433 struct tty_display_info *tty = FRAME_TTY (f);
435 if (tty->TS_clr_to_bottom)
437 tty_background_highlight (tty);
438 OUTPUT (tty, tty->TS_clr_to_bottom);
440 else
442 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
444 cursor_to (f, i, 0);
445 clear_end_of_line (f, FRAME_COLS (f));
450 /* Clear an entire termcap frame. */
452 static void
453 tty_clear_frame (struct frame *f)
455 struct tty_display_info *tty = FRAME_TTY (f);
457 if (tty->TS_clr_frame)
459 tty_background_highlight (tty);
460 OUTPUT (tty, tty->TS_clr_frame);
461 cmat (tty, 0, 0);
463 else
465 cursor_to (f, 0, 0);
466 clear_to_end (f);
470 /* An implementation of clear_end_of_line for termcap frames.
472 Note that the cursor may be moved, on terminals lacking a `ce' string. */
474 static void
475 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
477 register int i;
478 struct tty_display_info *tty = FRAME_TTY (f);
480 /* Detect the case where we are called from reset_sys_modes
481 and the costs have never been calculated. Do nothing. */
482 if (! tty->costs_set)
483 return;
485 if (curX (tty) >= first_unused_hpos)
486 return;
487 tty_background_highlight (tty);
488 if (tty->TS_clr_line)
490 OUTPUT1 (tty, tty->TS_clr_line);
492 else
493 { /* have to do it the hard way */
494 tty_turn_off_insert (tty);
496 /* Do not write in last row last col with Auto-wrap on. */
497 if (AutoWrap (tty)
498 && curY (tty) == FrameRows (tty) - 1
499 && first_unused_hpos == FrameCols (tty))
500 first_unused_hpos--;
502 for (i = curX (tty); i < first_unused_hpos; i++)
504 if (tty->termscript)
505 fputc_unlocked (' ', tty->termscript);
506 fputc_unlocked (' ', tty->output);
508 cmplus (tty, first_unused_hpos - curX (tty));
512 /* Buffers to store the source and result of code conversion for terminal. */
513 static unsigned char *encode_terminal_src;
514 static unsigned char *encode_terminal_dst;
515 /* Allocated sizes of the above buffers. */
516 static ptrdiff_t encode_terminal_src_size;
517 static ptrdiff_t encode_terminal_dst_size;
519 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
520 Set CODING->produced to the byte-length of the resulting byte
521 sequence, and return a pointer to that byte sequence. */
523 unsigned char *
524 encode_terminal_code (struct glyph *src, int src_len,
525 struct coding_system *coding)
527 struct glyph *src_end = src + src_len;
528 unsigned char *buf;
529 ptrdiff_t nchars, nbytes, required;
530 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
531 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
532 Lisp_Object charset_list;
534 /* Allocate sufficient size of buffer to store all characters in
535 multibyte-form. But, it may be enlarged on demand if
536 Vglyph_table contains a string or a composite glyph is
537 encountered. */
538 if (INT_MULTIPLY_WRAPV (src_len, MAX_MULTIBYTE_LENGTH, &required))
539 memory_full (SIZE_MAX);
540 if (encode_terminal_src_size < required)
541 encode_terminal_src = xpalloc (encode_terminal_src,
542 &encode_terminal_src_size,
543 required - encode_terminal_src_size,
544 -1, sizeof *encode_terminal_src);
546 charset_list = coding_charset_list (coding);
548 buf = encode_terminal_src;
549 nchars = 0;
550 while (src < src_end)
552 if (src->type == COMPOSITE_GLYPH)
554 struct composition *cmp UNINIT;
555 Lisp_Object gstring UNINIT;
556 int i;
558 nbytes = buf - encode_terminal_src;
559 if (src->u.cmp.automatic)
561 gstring = composition_gstring_from_id (src->u.cmp.id);
562 required = src->slice.cmp.to - src->slice.cmp.from + 1;
564 else
566 cmp = composition_table[src->u.cmp.id];
567 required = cmp->glyph_len;
568 required *= MAX_MULTIBYTE_LENGTH;
571 if (encode_terminal_src_size - nbytes < required)
573 encode_terminal_src =
574 xpalloc (encode_terminal_src, &encode_terminal_src_size,
575 required - (encode_terminal_src_size - nbytes),
576 -1, 1);
577 buf = encode_terminal_src + nbytes;
580 if (src->u.cmp.automatic)
581 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
583 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
584 int c = LGLYPH_CHAR (g);
586 if (! char_charset (c, charset_list, NULL))
587 c = '?';
588 buf += CHAR_STRING (c, buf);
589 nchars++;
591 else
592 for (i = 0; i < cmp->glyph_len; i++)
594 int c = COMPOSITION_GLYPH (cmp, i);
596 /* TAB in a composition means display glyphs with
597 padding space on the left or right. */
598 if (c == '\t')
599 continue;
600 if (char_charset (c, charset_list, NULL))
602 if (CHARACTER_WIDTH (c) == 0
603 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
604 /* Should be left-padded */
606 buf += CHAR_STRING (' ', buf);
607 nchars++;
610 else
611 c = '?';
612 buf += CHAR_STRING (c, buf);
613 nchars++;
616 /* We must skip glyphs to be padded for a wide character. */
617 else if (! CHAR_GLYPH_PADDING_P (*src))
619 GLYPH g;
620 int c UNINIT;
621 Lisp_Object string;
623 string = Qnil;
624 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
626 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
628 /* This glyph doesn't have an entry in Vglyph_table. */
629 c = src->u.ch;
631 else
633 /* This glyph has an entry in Vglyph_table,
634 so process any alias before testing for simpleness. */
635 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
637 if (GLYPH_SIMPLE_P (tbase, tlen, g))
638 /* We set the multi-byte form of a character in G
639 (that should be an ASCII character) at WORKBUF. */
640 c = GLYPH_CHAR (g);
641 else
642 /* We have a string in Vglyph_table. */
643 string = tbase[GLYPH_CHAR (g)];
646 if (NILP (string))
648 nbytes = buf - encode_terminal_src;
649 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
651 encode_terminal_src =
652 xpalloc (encode_terminal_src, &encode_terminal_src_size,
653 MAX_MULTIBYTE_LENGTH, -1, 1);
654 buf = encode_terminal_src + nbytes;
656 if (CHAR_BYTE8_P (c)
657 || char_charset (c, charset_list, NULL))
659 /* Store the multibyte form of C at BUF. */
660 buf += CHAR_STRING (c, buf);
661 nchars++;
663 else
665 /* C is not encodable. */
666 *buf++ = '?';
667 nchars++;
668 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
670 *buf++ = '?';
671 nchars++;
672 src++;
676 else
678 if (! STRING_MULTIBYTE (string))
679 string = string_to_multibyte (string);
680 nbytes = buf - encode_terminal_src;
681 if (encode_terminal_src_size - nbytes < SBYTES (string))
683 encode_terminal_src =
684 xpalloc (encode_terminal_src, &encode_terminal_src_size,
685 (SBYTES (string)
686 - (encode_terminal_src_size - nbytes)),
687 -1, 1);
688 buf = encode_terminal_src + nbytes;
690 memcpy (buf, SDATA (string), SBYTES (string));
691 buf += SBYTES (string);
692 nchars += SCHARS (string);
695 src++;
698 if (nchars == 0)
700 coding->produced = 0;
701 return NULL;
704 nbytes = buf - encode_terminal_src;
705 coding->source = encode_terminal_src;
706 if (encode_terminal_dst_size == 0)
708 encode_terminal_dst = xrealloc (encode_terminal_dst,
709 encode_terminal_src_size);
710 encode_terminal_dst_size = encode_terminal_src_size;
712 coding->destination = encode_terminal_dst;
713 coding->dst_bytes = encode_terminal_dst_size;
714 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
715 /* coding->destination may have been reallocated. */
716 encode_terminal_dst = coding->destination;
717 encode_terminal_dst_size = coding->dst_bytes;
719 return (encode_terminal_dst);
724 /* An implementation of write_glyphs for termcap frames. */
726 static void
727 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
729 unsigned char *conversion_buffer;
730 struct coding_system *coding;
731 int n, stringlen;
733 struct tty_display_info *tty = FRAME_TTY (f);
735 tty_turn_off_insert (tty);
736 tty_hide_cursor (tty);
738 /* Don't dare write in last column of bottom line, if Auto-Wrap,
739 since that would scroll the whole frame on some terminals. */
741 if (AutoWrap (tty)
742 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
743 && (curX (tty) + len) == FRAME_COLS (f))
744 len --;
745 if (len <= 0)
746 return;
748 cmplus (tty, len);
750 /* If terminal_coding does any conversion, use it, otherwise use
751 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
752 because it always return 1 if the member src_multibyte is 1. */
753 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
754 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
755 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
756 the tail. */
757 coding->mode &= ~CODING_MODE_LAST_BLOCK;
759 for (stringlen = len; stringlen != 0; stringlen -= n)
761 /* Identify a run of glyphs with the same face. */
762 int face_id = string->face_id;
764 for (n = 1; n < stringlen; ++n)
765 if (string[n].face_id != face_id)
766 break;
768 /* Turn appearance modes of the face of the run on. */
769 tty_highlight_if_desired (tty);
770 turn_on_face (f, face_id);
772 if (n == stringlen)
773 /* This is the last run. */
774 coding->mode |= CODING_MODE_LAST_BLOCK;
775 conversion_buffer = encode_terminal_code (string, n, coding);
776 if (coding->produced > 0)
778 block_input ();
779 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
780 clearerr_unlocked (tty->output);
781 if (tty->termscript)
782 fwrite_unlocked (conversion_buffer, 1, coding->produced,
783 tty->termscript);
784 unblock_input ();
786 string += n;
788 /* Turn appearance modes off. */
789 turn_off_face (f, face_id);
790 tty_turn_off_highlight (tty);
793 cmcheckmagic (tty);
796 #ifdef HAVE_GPM /* Only used by GPM code. */
798 static void
799 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
800 register int len, register int face_id)
802 unsigned char *conversion_buffer;
803 struct coding_system *coding;
805 struct tty_display_info *tty = FRAME_TTY (f);
807 tty_turn_off_insert (tty);
808 tty_hide_cursor (tty);
810 /* Don't dare write in last column of bottom line, if Auto-Wrap,
811 since that would scroll the whole frame on some terminals. */
813 if (AutoWrap (tty)
814 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
815 && (curX (tty) + len) == FRAME_COLS (f))
816 len --;
817 if (len <= 0)
818 return;
820 cmplus (tty, len);
822 /* If terminal_coding does any conversion, use it, otherwise use
823 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
824 because it always return 1 if the member src_multibyte is 1. */
825 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
826 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
827 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
828 the tail. */
829 coding->mode &= ~CODING_MODE_LAST_BLOCK;
831 /* Turn appearance modes of the face. */
832 tty_highlight_if_desired (tty);
833 turn_on_face (f, face_id);
835 coding->mode |= CODING_MODE_LAST_BLOCK;
836 conversion_buffer = encode_terminal_code (string, len, coding);
837 if (coding->produced > 0)
839 block_input ();
840 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
841 clearerr_unlocked (tty->output);
842 if (tty->termscript)
843 fwrite_unlocked (conversion_buffer, 1, coding->produced,
844 tty->termscript);
845 unblock_input ();
848 /* Turn appearance modes off. */
849 turn_off_face (f, face_id);
850 tty_turn_off_highlight (tty);
852 cmcheckmagic (tty);
854 #endif
856 /* An implementation of insert_glyphs for termcap frames. */
858 static void
859 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
861 char *buf;
862 struct glyph *glyph = NULL;
863 unsigned char *conversion_buffer;
864 unsigned char space[1];
865 struct coding_system *coding;
867 struct tty_display_info *tty = FRAME_TTY (f);
869 if (tty->TS_ins_multi_chars)
871 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
872 OUTPUT1 (tty, buf);
873 xfree (buf);
874 if (start)
875 write_glyphs (f, start, len);
876 return;
879 tty_turn_on_insert (tty);
880 cmplus (tty, len);
882 if (! start)
883 space[0] = SPACEGLYPH;
885 /* If terminal_coding does any conversion, use it, otherwise use
886 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
887 because it always return 1 if the member src_multibyte is 1. */
888 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
889 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
890 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
891 the tail. */
892 coding->mode &= ~CODING_MODE_LAST_BLOCK;
894 while (len-- > 0)
896 OUTPUT1_IF (tty, tty->TS_ins_char);
897 if (!start)
899 conversion_buffer = space;
900 coding->produced = 1;
902 else
904 tty_highlight_if_desired (tty);
905 turn_on_face (f, start->face_id);
906 glyph = start;
907 ++start;
908 /* We must open sufficient space for a character which
909 occupies more than one column. */
910 while (len && CHAR_GLYPH_PADDING_P (*start))
912 OUTPUT1_IF (tty, tty->TS_ins_char);
913 start++, len--;
916 if (len <= 0)
917 /* This is the last glyph. */
918 coding->mode |= CODING_MODE_LAST_BLOCK;
920 conversion_buffer = encode_terminal_code (glyph, 1, coding);
923 if (coding->produced > 0)
925 block_input ();
926 fwrite_unlocked (conversion_buffer, 1, coding->produced, tty->output);
927 clearerr_unlocked (tty->output);
928 if (tty->termscript)
929 fwrite_unlocked (conversion_buffer, 1, coding->produced,
930 tty->termscript);
931 unblock_input ();
934 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
935 if (start)
937 turn_off_face (f, glyph->face_id);
938 tty_turn_off_highlight (tty);
942 cmcheckmagic (tty);
945 /* An implementation of delete_glyphs for termcap frames. */
947 static void
948 tty_delete_glyphs (struct frame *f, int n)
950 char *buf;
951 register int i;
953 struct tty_display_info *tty = FRAME_TTY (f);
955 if (tty->delete_in_insert_mode)
957 tty_turn_on_insert (tty);
959 else
961 tty_turn_off_insert (tty);
962 OUTPUT_IF (tty, tty->TS_delete_mode);
965 if (tty->TS_del_multi_chars)
967 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
968 OUTPUT1 (tty, buf);
969 xfree (buf);
971 else
972 for (i = 0; i < n; i++)
973 OUTPUT1 (tty, tty->TS_del_char);
974 if (!tty->delete_in_insert_mode)
975 OUTPUT_IF (tty, tty->TS_end_delete_mode);
978 /* An implementation of ins_del_lines for termcap frames. */
980 static void
981 tty_ins_del_lines (struct frame *f, int vpos, int n)
983 struct tty_display_info *tty = FRAME_TTY (f);
984 const char *multi =
985 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
986 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
987 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
989 int i = eabs (n);
990 char *buf;
992 /* If the lines below the insertion are being pushed
993 into the end of the window, this is the same as clearing;
994 and we know the lines are already clear, since the matching
995 deletion has already been done. So can ignore this. */
996 /* If the lines below the deletion are blank lines coming
997 out of the end of the window, don't bother,
998 as there will be a matching inslines later that will flush them. */
999 if (FRAME_SCROLL_REGION_OK (f)
1000 && vpos + i >= tty->specified_window)
1001 return;
1002 if (!FRAME_MEMORY_BELOW_FRAME (f)
1003 && vpos + i >= FRAME_TOTAL_LINES (f))
1004 return;
1006 if (multi)
1008 raw_cursor_to (f, vpos, 0);
1009 tty_background_highlight (tty);
1010 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1011 OUTPUT (tty, buf);
1012 xfree (buf);
1014 else if (single)
1016 raw_cursor_to (f, vpos, 0);
1017 tty_background_highlight (tty);
1018 while (--i >= 0)
1019 OUTPUT (tty, single);
1020 if (tty->TF_teleray)
1021 curX (tty) = 0;
1023 else
1025 tty_set_scroll_region (f, vpos, tty->specified_window);
1026 if (n < 0)
1027 raw_cursor_to (f, tty->specified_window - 1, 0);
1028 else
1029 raw_cursor_to (f, vpos, 0);
1030 tty_background_highlight (tty);
1031 while (--i >= 0)
1032 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1033 tty_set_scroll_region (f, 0, tty->specified_window);
1036 if (!FRAME_SCROLL_REGION_OK (f)
1037 && FRAME_MEMORY_BELOW_FRAME (f)
1038 && n < 0)
1040 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1041 clear_to_end (f);
1045 /* Compute cost of sending "str", in characters,
1046 not counting any line-dependent padding. */
1049 string_cost (const char *str)
1051 cost = 0;
1052 if (str)
1053 tputs (str, 0, evalcost);
1054 return cost;
1057 /* Compute cost of sending "str", in characters,
1058 counting any line-dependent padding at one line. */
1060 static int
1061 string_cost_one_line (const char *str)
1063 cost = 0;
1064 if (str)
1065 tputs (str, 1, evalcost);
1066 return cost;
1069 /* Compute per line amount of line-dependent padding,
1070 in tenths of characters. */
1073 per_line_cost (const char *str)
1075 cost = 0;
1076 if (str)
1077 tputs (str, 0, evalcost);
1078 cost = - cost;
1079 if (str)
1080 tputs (str, 10, evalcost);
1081 return cost;
1084 /* char_ins_del_cost[n] is cost of inserting N characters.
1085 char_ins_del_cost[-n] is cost of deleting N characters.
1086 The length of this vector is based on max_frame_cols. */
1088 int *char_ins_del_vector;
1090 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1092 /* ARGSUSED */
1093 static void
1094 calculate_ins_del_char_costs (struct frame *f)
1096 struct tty_display_info *tty = FRAME_TTY (f);
1097 int ins_startup_cost, del_startup_cost;
1098 int ins_cost_per_char, del_cost_per_char;
1099 register int i;
1100 register int *p;
1102 if (tty->TS_ins_multi_chars)
1104 ins_cost_per_char = 0;
1105 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1107 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1108 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1110 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1111 + string_cost (tty->TS_end_insert_mode))) / 100;
1112 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1113 + string_cost_one_line (tty->TS_pad_inserted_char));
1115 else
1117 ins_startup_cost = 9999;
1118 ins_cost_per_char = 0;
1121 if (tty->TS_del_multi_chars)
1123 del_cost_per_char = 0;
1124 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1126 else if (tty->TS_del_char)
1128 del_startup_cost = (string_cost (tty->TS_delete_mode)
1129 + string_cost (tty->TS_end_delete_mode));
1130 if (tty->delete_in_insert_mode)
1131 del_startup_cost /= 2;
1132 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1134 else
1136 del_startup_cost = 9999;
1137 del_cost_per_char = 0;
1140 /* Delete costs are at negative offsets */
1141 p = &char_ins_del_cost (f)[0];
1142 for (i = FRAME_COLS (f); --i >= 0;)
1143 *--p = (del_startup_cost += del_cost_per_char);
1145 /* Doing nothing is free */
1146 p = &char_ins_del_cost (f)[0];
1147 *p++ = 0;
1149 /* Insert costs are at positive offsets */
1150 for (i = FRAME_COLS (f); --i >= 0;)
1151 *p++ = (ins_startup_cost += ins_cost_per_char);
1154 void
1155 calculate_costs (struct frame *frame)
1157 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1159 if (FRAME_TERMCAP_P (frame))
1161 struct tty_display_info *tty = FRAME_TTY (frame);
1162 register const char *f = (tty->TS_set_scroll_region
1163 ? tty->TS_set_scroll_region
1164 : tty->TS_set_scroll_region_1);
1166 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1168 tty->costs_set = 1;
1170 /* These variables are only used for terminal stuff. They are
1171 allocated once for the terminal frame of X-windows emacs, but not
1172 used afterwards.
1174 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1175 X turns off char_ins_del_ok. */
1177 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1178 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1179 < max_frame_cols)
1180 memory_full (SIZE_MAX);
1182 char_ins_del_vector =
1183 xrealloc (char_ins_del_vector,
1184 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1186 memset (char_ins_del_vector, 0,
1187 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1190 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1191 do_line_insertion_deletion_costs (frame,
1192 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1193 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1194 f, f, 1);
1195 else
1196 do_line_insertion_deletion_costs (frame,
1197 tty->TS_ins_line, tty->TS_ins_multi_lines,
1198 tty->TS_del_line, tty->TS_del_multi_lines,
1199 0, 0, 1);
1201 calculate_ins_del_char_costs (frame);
1203 /* Don't use TS_repeat if its padding is worse than sending the chars */
1204 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1205 tty->RPov = string_cost (tty->TS_repeat);
1206 else
1207 tty->RPov = FRAME_COLS (frame) * 2;
1209 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1213 struct fkey_table {
1214 const char *cap, *name;
1217 #ifndef DOS_NT
1218 /* Termcap capability names that correspond directly to X keysyms.
1219 Some of these (marked "terminfo") aren't supplied by old-style
1220 (Berkeley) termcap entries. They're listed in X keysym order;
1221 except we put the keypad keys first, so that if they clash with
1222 other keys (as on the IBM PC keyboard) they get overridden.
1225 static const struct fkey_table keys[] =
1227 {"kh", "home"}, /* termcap */
1228 {"kl", "left"}, /* termcap */
1229 {"ku", "up"}, /* termcap */
1230 {"kr", "right"}, /* termcap */
1231 {"kd", "down"}, /* termcap */
1232 {"%8", "prior"}, /* terminfo */
1233 {"%5", "next"}, /* terminfo */
1234 {"@7", "end"}, /* terminfo */
1235 {"@1", "begin"}, /* terminfo */
1236 {"*6", "select"}, /* terminfo */
1237 {"%9", "print"}, /* terminfo */
1238 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1240 * "insert" --- see below
1242 {"&8", "undo"}, /* terminfo */
1243 {"%0", "redo"}, /* terminfo */
1244 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1245 {"@0", "find"}, /* terminfo */
1246 {"@2", "cancel"}, /* terminfo */
1247 {"%1", "help"}, /* terminfo */
1249 * "break" goes here, but can't be reliably intercepted with termcap
1251 {"&4", "reset"}, /* terminfo --- actually `restart' */
1253 * "system" and "user" --- no termcaps
1255 {"kE", "clearline"}, /* terminfo */
1256 {"kA", "insertline"}, /* terminfo */
1257 {"kL", "deleteline"}, /* terminfo */
1258 {"kI", "insertchar"}, /* terminfo */
1259 {"kD", "deletechar"}, /* terminfo */
1260 {"kB", "backtab"}, /* terminfo */
1262 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1264 {"@8", "kp-enter"}, /* terminfo */
1266 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1267 * "kp-multiply", "kp-add", "kp-separator",
1268 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1269 * --- no termcaps for any of these.
1271 {"K4", "kp-1"}, /* terminfo */
1273 * "kp-2" --- no termcap
1275 {"K5", "kp-3"}, /* terminfo */
1277 * "kp-4" --- no termcap
1279 {"K2", "kp-5"}, /* terminfo */
1281 * "kp-6" --- no termcap
1283 {"K1", "kp-7"}, /* terminfo */
1285 * "kp-8" --- no termcap
1287 {"K3", "kp-9"}, /* terminfo */
1289 * "kp-equal" --- no termcap
1291 {"k1", "f1"},
1292 {"k2", "f2"},
1293 {"k3", "f3"},
1294 {"k4", "f4"},
1295 {"k5", "f5"},
1296 {"k6", "f6"},
1297 {"k7", "f7"},
1298 {"k8", "f8"},
1299 {"k9", "f9"},
1301 {"&0", "S-cancel"}, /*shifted cancel key*/
1302 {"&9", "S-begin"}, /*shifted begin key*/
1303 {"*0", "S-find"}, /*shifted find key*/
1304 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1305 {"*4", "S-delete"}, /*shifted delete-character key*/
1306 {"*7", "S-end"}, /*shifted end key*/
1307 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1308 {"#1", "S-help"}, /*shifted help key*/
1309 {"#2", "S-home"}, /*shifted home key*/
1310 {"#3", "S-insert"}, /*shifted insert-character key*/
1311 {"#4", "S-left"}, /*shifted left-arrow key*/
1312 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1313 {"%c", "S-next"}, /*shifted next key*/
1314 {"%e", "S-prior"}, /*shifted previous key*/
1315 {"%f", "S-print"}, /*shifted print key*/
1316 {"%g", "S-redo"}, /*shifted redo key*/
1317 {"%i", "S-right"}, /*shifted right-arrow key*/
1318 {"!3", "S-undo"} /*shifted undo key*/
1321 static char **term_get_fkeys_address;
1322 static KBOARD *term_get_fkeys_kboard;
1323 static Lisp_Object term_get_fkeys_1 (void);
1325 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1326 This function scans the termcap function key sequence entries, and
1327 adds entries to Vinput_decode_map for each function key it finds. */
1329 static void
1330 term_get_fkeys (char **address, KBOARD *kboard)
1332 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1333 errors during the call. The only errors should be from Fdefine_key
1334 when given a key sequence containing an invalid prefix key. If the
1335 termcap defines function keys which use a prefix that is already bound
1336 to a command by the default bindings, we should silently ignore that
1337 function key specification, rather than giving the user an error and
1338 refusing to run at all on such a terminal. */
1340 term_get_fkeys_address = address;
1341 term_get_fkeys_kboard = kboard;
1342 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1345 static Lisp_Object
1346 term_get_fkeys_1 (void)
1348 int i;
1350 char **address = term_get_fkeys_address;
1351 KBOARD *kboard = term_get_fkeys_kboard;
1353 /* This can happen if CANNOT_DUMP or with strange options. */
1354 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1355 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1357 for (i = 0; i < ARRAYELTS (keys); i++)
1359 char *sequence = tgetstr (keys[i].cap, address);
1360 if (sequence)
1361 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1362 Fmake_vector (make_number (1),
1363 intern (keys[i].name)));
1366 /* The uses of the "k0" capability are inconsistent; sometimes it
1367 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1368 We will attempt to politely accommodate both systems by testing for
1369 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1372 const char *k_semi = tgetstr ("k;", address);
1373 const char *k0 = tgetstr ("k0", address);
1374 const char *k0_name = "f10";
1376 if (k_semi)
1378 if (k0)
1379 /* Define f0 first, so that f10 takes precedence in case the
1380 key sequences happens to be the same. */
1381 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1382 Fmake_vector (make_number (1), intern ("f0")));
1383 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1384 Fmake_vector (make_number (1), intern ("f10")));
1386 else if (k0)
1387 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1388 Fmake_vector (make_number (1), intern (k0_name)));
1391 /* Set up cookies for numbered function keys above f10. */
1393 char fcap[3], fkey[4];
1395 fcap[0] = 'F'; fcap[2] = '\0';
1396 for (i = 11; i < 64; i++)
1398 if (i <= 19)
1399 fcap[1] = '1' + i - 11;
1400 else if (i <= 45)
1401 fcap[1] = 'A' + i - 20;
1402 else
1403 fcap[1] = 'a' + i - 46;
1406 char *sequence = tgetstr (fcap, address);
1407 if (sequence)
1409 sprintf (fkey, "f%d", i);
1410 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1411 Fmake_vector (make_number (1),
1412 intern (fkey)));
1419 * Various mappings to try and get a better fit.
1422 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1423 if (!tgetstr (cap1, address)) \
1425 char *sequence = tgetstr (cap2, address); \
1426 if (sequence) \
1427 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1428 Fmake_vector (make_number (1), \
1429 intern (sym))); \
1432 /* if there's no key_next keycap, map key_npage to `next' keysym */
1433 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1434 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1435 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1436 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1437 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1438 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1439 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1440 #undef CONDITIONAL_REASSIGN
1443 return Qnil;
1445 #endif /* not DOS_NT */
1448 /***********************************************************************
1449 Character Display Information
1450 ***********************************************************************/
1451 static void append_glyph (struct it *);
1452 static void append_composite_glyph (struct it *);
1453 static void produce_composite_glyph (struct it *);
1454 static void append_glyphless_glyph (struct it *, int, const char *);
1455 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1457 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1458 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1459 the character for which to produce glyphs; IT->face_id contains the
1460 character's face. Padding glyphs are appended if IT->c has a
1461 IT->pixel_width > 1. */
1463 static void
1464 append_glyph (struct it *it)
1466 struct glyph *glyph, *end;
1467 int i;
1469 eassert (it->glyph_row);
1470 glyph = (it->glyph_row->glyphs[it->area]
1471 + it->glyph_row->used[it->area]);
1472 end = it->glyph_row->glyphs[1 + it->area];
1474 /* If the glyph row is reversed, we need to prepend the glyph rather
1475 than append it. */
1476 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1478 struct glyph *g;
1479 int move_by = it->pixel_width;
1481 /* Make room for the new glyphs. */
1482 if (move_by > end - glyph) /* don't overstep end of this area */
1483 move_by = end - glyph;
1484 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1485 g[move_by] = *g;
1486 glyph = it->glyph_row->glyphs[it->area];
1487 end = glyph + move_by;
1490 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1491 right, even in the REVERSED_P case, since (a) all of its u.ch are
1492 identical, and (b) the PADDING_P flag needs to be set for the
1493 leftmost one, because we write to the terminal left-to-right. */
1494 for (i = 0;
1495 i < it->pixel_width && glyph < end;
1496 ++i)
1498 glyph->type = CHAR_GLYPH;
1499 glyph->pixel_width = 1;
1500 glyph->u.ch = it->char_to_display;
1501 glyph->face_id = it->face_id;
1502 glyph->avoid_cursor_p = it->avoid_cursor_p;
1503 glyph->multibyte_p = it->multibyte_p;
1504 glyph->padding_p = i > 0;
1505 glyph->charpos = CHARPOS (it->position);
1506 glyph->object = it->object;
1507 if (it->bidi_p)
1509 glyph->resolved_level = it->bidi_it.resolved_level;
1510 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1511 glyph->bidi_type = it->bidi_it.type;
1513 else
1515 glyph->resolved_level = 0;
1516 glyph->bidi_type = UNKNOWN_BT;
1519 ++it->glyph_row->used[it->area];
1520 ++glyph;
1524 /* For external use. */
1525 void
1526 tty_append_glyph (struct it *it)
1528 append_glyph (it);
1532 /* Produce glyphs for the display element described by IT. *IT
1533 specifies what we want to produce a glyph for (character, image, ...),
1534 and where in the glyph matrix we currently are (glyph row and hpos).
1535 produce_glyphs fills in output fields of *IT with information such as the
1536 pixel width and height of a character, and maybe output actual glyphs at
1537 the same time if IT->glyph_row is non-null. For an overview, see
1538 the explanation in dispextern.h, before the definition of the
1539 display_element_type enumeration.
1541 produce_glyphs also stores the result of glyph width, ascent
1542 etc. computations in *IT.
1544 IT->glyph_row may be null, in which case produce_glyphs does not
1545 actually fill in the glyphs. This is used in the move_* functions
1546 in xdisp.c for text width and height computations.
1548 Callers usually don't call produce_glyphs directly;
1549 instead they use the macro PRODUCE_GLYPHS. */
1551 void
1552 produce_glyphs (struct it *it)
1554 /* If a hook is installed, let it do the work. */
1556 /* Nothing but characters are supported on terminal frames. */
1557 eassert (it->what == IT_CHARACTER
1558 || it->what == IT_COMPOSITION
1559 || it->what == IT_STRETCH
1560 || it->what == IT_GLYPHLESS);
1562 if (it->what == IT_STRETCH)
1564 produce_stretch_glyph (it);
1565 goto done;
1568 if (it->what == IT_COMPOSITION)
1570 produce_composite_glyph (it);
1571 goto done;
1574 if (it->what == IT_GLYPHLESS)
1576 produce_glyphless_glyph (it, Qnil);
1577 goto done;
1580 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1582 it->pixel_width = it->nglyphs = 1;
1583 if (it->glyph_row)
1584 append_glyph (it);
1586 else if (it->char_to_display == '\n')
1587 it->pixel_width = it->nglyphs = 0;
1588 else if (it->char_to_display == '\t')
1590 int absolute_x = (it->current_x
1591 + it->continuation_lines_width);
1592 int x0 = absolute_x;
1593 /* Adjust for line numbers. */
1594 if (!NILP (Vdisplay_line_numbers))
1595 absolute_x -= it->lnum_pixel_width;
1596 int next_tab_x
1597 = (((1 + absolute_x + it->tab_width - 1)
1598 / it->tab_width)
1599 * it->tab_width);
1600 if (!NILP (Vdisplay_line_numbers))
1601 next_tab_x += it->lnum_pixel_width;
1602 int nspaces;
1604 /* If part of the TAB has been displayed on the previous line
1605 which is continued now, continuation_lines_width will have
1606 been incremented already by the part that fitted on the
1607 continued line. So, we will get the right number of spaces
1608 here. */
1609 nspaces = next_tab_x - x0;
1611 if (it->glyph_row)
1613 int n = nspaces;
1615 it->char_to_display = ' ';
1616 it->pixel_width = it->len = 1;
1618 while (n--)
1619 append_glyph (it);
1622 it->pixel_width = nspaces;
1623 it->nglyphs = nspaces;
1625 else if (CHAR_BYTE8_P (it->char_to_display))
1627 /* Coming here means that we must send the raw 8-bit byte as is
1628 to the terminal. Although there's no way to know how many
1629 columns it occupies on a screen, it is a good assumption that
1630 a single byte code has 1-column width. */
1631 it->pixel_width = it->nglyphs = 1;
1632 if (it->glyph_row)
1633 append_glyph (it);
1635 else
1637 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1639 if (char_charset (it->char_to_display, charset_list, NULL))
1641 it->pixel_width = CHARACTER_WIDTH (it->char_to_display);
1642 it->nglyphs = it->pixel_width;
1643 if (it->glyph_row)
1644 append_glyph (it);
1646 else
1648 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1650 eassert (it->what == IT_GLYPHLESS);
1651 produce_glyphless_glyph (it, acronym);
1655 done:
1656 /* Advance current_x by the pixel width as a convenience for
1657 the caller. */
1658 if (it->area == TEXT_AREA)
1659 it->current_x += it->pixel_width;
1660 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1661 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1664 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1665 Called from produce_composite_glyph for terminal frames if
1666 IT->glyph_row != NULL. IT->face_id contains the character's
1667 face. */
1669 static void
1670 append_composite_glyph (struct it *it)
1672 struct glyph *glyph;
1674 eassert (it->glyph_row);
1675 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1676 if (glyph < it->glyph_row->glyphs[1 + it->area])
1678 /* If the glyph row is reversed, we need to prepend the glyph
1679 rather than append it. */
1680 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1682 struct glyph *g;
1684 /* Make room for the new glyph. */
1685 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1686 g[1] = *g;
1687 glyph = it->glyph_row->glyphs[it->area];
1689 glyph->type = COMPOSITE_GLYPH;
1690 eassert (it->pixel_width <= SHRT_MAX);
1691 glyph->pixel_width = it->pixel_width;
1692 glyph->u.cmp.id = it->cmp_it.id;
1693 if (it->cmp_it.ch < 0)
1695 glyph->u.cmp.automatic = 0;
1696 glyph->u.cmp.id = it->cmp_it.id;
1698 else
1700 glyph->u.cmp.automatic = 1;
1701 glyph->u.cmp.id = it->cmp_it.id;
1702 glyph->slice.cmp.from = it->cmp_it.from;
1703 glyph->slice.cmp.to = it->cmp_it.to - 1;
1706 glyph->avoid_cursor_p = it->avoid_cursor_p;
1707 glyph->multibyte_p = it->multibyte_p;
1708 glyph->face_id = it->face_id;
1709 glyph->padding_p = false;
1710 glyph->charpos = CHARPOS (it->position);
1711 glyph->object = it->object;
1712 if (it->bidi_p)
1714 glyph->resolved_level = it->bidi_it.resolved_level;
1715 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1716 glyph->bidi_type = it->bidi_it.type;
1718 else
1720 glyph->resolved_level = 0;
1721 glyph->bidi_type = UNKNOWN_BT;
1724 ++it->glyph_row->used[it->area];
1725 ++glyph;
1730 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1731 the composition. We simply produces components of the composition
1732 assuming that the terminal has a capability to layout/render it
1733 correctly. */
1735 static void
1736 produce_composite_glyph (struct it *it)
1738 if (it->cmp_it.ch < 0)
1740 struct composition *cmp = composition_table[it->cmp_it.id];
1742 it->pixel_width = cmp->width;
1744 else
1746 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1748 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1749 it->cmp_it.to, NULL);
1751 it->nglyphs = 1;
1752 if (it->glyph_row)
1753 append_composite_glyph (it);
1757 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1758 is a face ID to be used for the glyph. What is actually appended
1759 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1760 comes from it->nglyphs bytes). */
1762 static void
1763 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1765 struct glyph *glyph, *end;
1766 int i;
1768 eassert (it->glyph_row);
1769 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1770 end = it->glyph_row->glyphs[1 + it->area];
1772 /* If the glyph row is reversed, we need to prepend the glyph rather
1773 than append it. */
1774 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1776 struct glyph *g;
1777 int move_by = it->pixel_width;
1779 /* Make room for the new glyphs. */
1780 if (move_by > end - glyph) /* don't overstep end of this area */
1781 move_by = end - glyph;
1782 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1783 g[move_by] = *g;
1784 glyph = it->glyph_row->glyphs[it->area];
1785 end = glyph + move_by;
1788 if (glyph >= end)
1789 return;
1790 glyph->type = CHAR_GLYPH;
1791 glyph->pixel_width = 1;
1792 glyph->avoid_cursor_p = it->avoid_cursor_p;
1793 glyph->multibyte_p = it->multibyte_p;
1794 glyph->face_id = face_id;
1795 glyph->padding_p = false;
1796 glyph->charpos = CHARPOS (it->position);
1797 glyph->object = it->object;
1798 if (it->bidi_p)
1800 glyph->resolved_level = it->bidi_it.resolved_level;
1801 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1802 glyph->bidi_type = it->bidi_it.type;
1804 else
1806 glyph->resolved_level = 0;
1807 glyph->bidi_type = UNKNOWN_BT;
1810 /* BIDI Note: we put the glyphs of characters left to right, even in
1811 the REVERSED_P case because we write to the terminal
1812 left-to-right. */
1813 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1815 if (i > 0)
1816 glyph[0] = glyph[-1];
1817 glyph->u.ch = str[i];
1818 ++it->glyph_row->used[it->area];
1819 ++glyph;
1823 /* Produce glyphs for a glyphless character for iterator IT.
1824 IT->glyphless_method specifies which method to use for displaying
1825 the character. See the description of enum
1826 glyphless_display_method in dispextern.h for the details.
1828 ACRONYM, if non-nil, is an acronym string for the character.
1830 The glyphs actually produced are of type CHAR_GLYPH. */
1832 static void
1833 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1835 int len, face_id = merge_glyphless_glyph_face (it);
1836 char buf[sizeof "\\x" + max (6, (INT_WIDTH + 3) / 4)];
1837 char const *str = " ";
1839 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1841 /* As there's no way to produce a thin space, we produce a space
1842 of canonical width. */
1843 len = 1;
1845 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1847 len = CHARACTER_WIDTH (it->c);
1848 if (len == 0)
1849 len = 1;
1850 else if (len > 4)
1851 len = 4;
1852 len = sprintf (buf, "[%.*s]", len, str);
1853 str = buf;
1855 else
1857 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1859 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1860 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1861 if (CONSP (acronym))
1862 acronym = XCDR (acronym);
1863 buf[0] = '[';
1864 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1865 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1866 buf[1 + len] = str[len];
1867 buf[1 + len] = ']';
1868 len += 2;
1870 else
1872 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1873 len = sprintf (buf,
1874 (it->c < 0x10000 ? "\\u%04X"
1875 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1876 : "\\x%06X"),
1877 it->c + 0u);
1879 str = buf;
1882 it->pixel_width = len;
1883 it->nglyphs = len;
1884 if (it->glyph_row)
1885 append_glyphless_glyph (it, face_id, str);
1889 /***********************************************************************
1890 Faces
1891 ***********************************************************************/
1893 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1894 one of the enumerators from enum no_color_bit, or a bit set built
1895 from them. Some display attributes may not be used together with
1896 color; the termcap capability `NC' specifies which ones. */
1898 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1899 (tty->TN_max_colors > 0 \
1900 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1901 : 1)
1903 /* Turn appearances of face FACE_ID on tty frame F on.
1904 FACE_ID is a realized face ID number, in the face cache. */
1906 static void
1907 turn_on_face (struct frame *f, int face_id)
1909 struct face *face = FACE_FROM_ID (f, face_id);
1910 unsigned long fg = face->foreground;
1911 unsigned long bg = face->background;
1912 struct tty_display_info *tty = FRAME_TTY (f);
1914 /* Use reverse video if the face specifies that.
1915 Do this first because TS_end_standout_mode may be the same
1916 as TS_exit_attribute_mode, which turns all appearances off. */
1917 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1918 && (inverse_video
1919 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1920 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1921 tty_toggle_highlight (tty);
1923 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1924 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1926 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1928 if (tty->TS_enter_italic_mode)
1929 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1930 else
1931 /* Italics mode is unavailable on many terminals. In that
1932 case, map slant to dimmed text; we want italic text to
1933 appear different and dimming is not otherwise used. */
1934 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1937 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1938 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1940 if (tty->TN_max_colors > 0)
1942 const char *ts;
1943 char *p;
1945 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1946 if (face_tty_specified_color (fg) && ts)
1948 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1949 OUTPUT (tty, p);
1950 xfree (p);
1953 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1954 if (face_tty_specified_color (bg) && ts)
1956 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1957 OUTPUT (tty, p);
1958 xfree (p);
1964 /* Turn off appearances of face FACE_ID on tty frame F. */
1966 static void
1967 turn_off_face (struct frame *f, int face_id)
1969 struct face *face = FACE_FROM_ID (f, face_id);
1970 struct tty_display_info *tty = FRAME_TTY (f);
1972 if (tty->TS_exit_attribute_mode)
1974 /* Capability "me" will turn off appearance modes double-bright,
1975 half-bright, reverse-video, standout, underline. It may or
1976 may not turn off alt-char-mode. */
1977 if (face->tty_bold_p
1978 || face->tty_italic_p
1979 || face->tty_reverse_p
1980 || face->tty_underline_p)
1982 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1983 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1984 tty->standout_mode = 0;
1987 else
1989 /* If we don't have "me" we can only have those appearances
1990 that have exit sequences defined. */
1991 if (face->tty_underline_p)
1992 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1995 /* Switch back to default colors. */
1996 if (tty->TN_max_colors > 0
1997 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1998 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1999 || (face->background != FACE_TTY_DEFAULT_COLOR
2000 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
2001 OUTPUT1_IF (tty, tty->TS_orig_pair);
2005 /* Return true if the terminal on frame F supports all of the
2006 capabilities in CAPS simultaneously. */
2008 bool
2009 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2011 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2012 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2013 return 0;
2015 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2016 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2017 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2018 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2019 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2021 /* We can do it! */
2022 return 1;
2025 /* Return non-zero if the terminal is capable to display colors. */
2027 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2028 0, 1, 0,
2029 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2031 TERMINAL can be a terminal object, a frame, or nil (meaning the
2032 selected frame's terminal). This function always returns nil if
2033 TERMINAL does not refer to a text terminal. */)
2034 (Lisp_Object terminal)
2036 struct terminal *t = decode_tty_terminal (terminal);
2038 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2041 /* Return the number of supported colors. */
2042 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2043 Stty_display_color_cells, 0, 1, 0,
2044 doc: /* Return the number of colors supported by the tty device TERMINAL.
2046 TERMINAL can be a terminal object, a frame, or nil (meaning the
2047 selected frame's terminal). This function always returns 0 if
2048 TERMINAL does not refer to a text terminal. */)
2049 (Lisp_Object terminal)
2051 struct terminal *t = decode_tty_terminal (terminal);
2053 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2056 #ifndef DOS_NT
2058 /* Declare here rather than in the function, as in the rest of Emacs,
2059 to work around an HPUX compiler bug (?). See
2060 https://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2061 static int default_max_colors;
2062 static int default_no_color_video;
2063 static char *default_orig_pair;
2064 static char *default_set_foreground;
2065 static char *default_set_background;
2067 /* Save or restore the default color-related capabilities of this
2068 terminal. */
2069 static void
2070 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2073 if (save)
2075 dupstring (&default_orig_pair, tty->TS_orig_pair);
2076 dupstring (&default_set_foreground, tty->TS_set_foreground);
2077 dupstring (&default_set_background, tty->TS_set_background);
2078 default_max_colors = tty->TN_max_colors;
2079 default_no_color_video = tty->TN_no_color_video;
2081 else
2083 tty->TS_orig_pair = default_orig_pair;
2084 tty->TS_set_foreground = default_set_foreground;
2085 tty->TS_set_background = default_set_background;
2086 tty->TN_max_colors = default_max_colors;
2087 tty->TN_no_color_video = default_no_color_video;
2091 /* Setup one of the standard tty color schemes according to MODE.
2092 MODE's value is generally the number of colors which we want to
2093 support; zero means set up for the default capabilities, the ones
2094 we saw at init_tty time; -1 means turn off color support. */
2095 static void
2096 tty_setup_colors (struct tty_display_info *tty, int mode)
2098 /* Canonicalize all negative values of MODE. */
2099 if (mode < -1)
2100 mode = -1;
2102 switch (mode)
2104 case -1: /* no colors at all */
2105 tty->TN_max_colors = 0;
2106 tty->TN_no_color_video = 0;
2107 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2108 break;
2109 case 0: /* default colors, if any */
2110 default:
2111 tty_default_color_capabilities (tty, 0);
2112 break;
2113 case 8: /* 8 standard ANSI colors */
2114 tty->TS_orig_pair = "\033[0m";
2115 #ifdef TERMINFO
2116 tty->TS_set_foreground = "\033[3%p1%dm";
2117 tty->TS_set_background = "\033[4%p1%dm";
2118 #else
2119 tty->TS_set_foreground = "\033[3%dm";
2120 tty->TS_set_background = "\033[4%dm";
2121 #endif
2122 tty->TN_max_colors = 8;
2123 tty->TN_no_color_video = 0;
2124 break;
2128 void
2129 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2131 Lisp_Object tem, val;
2132 Lisp_Object color_mode;
2133 int mode;
2134 Lisp_Object tty_color_mode_alist
2135 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2137 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2138 val = CONSP (tem) ? XCDR (tem) : Qnil;
2140 if (INTEGERP (val))
2141 color_mode = val;
2142 else if (SYMBOLP (tty_color_mode_alist))
2144 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2145 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2147 else
2148 color_mode = Qnil;
2150 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2152 if (mode != tty->previous_color_mode)
2154 tty->previous_color_mode = mode;
2155 tty_setup_colors (tty , mode);
2156 /* This recomputes all the faces given the new color definitions. */
2157 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2161 #endif /* !DOS_NT */
2163 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2164 doc: /* Return the type of the tty device that TERMINAL uses.
2165 Returns nil if TERMINAL is not on a tty device.
2167 TERMINAL can be a terminal object, a frame, or nil (meaning the
2168 selected frame's terminal). */)
2169 (Lisp_Object terminal)
2171 struct terminal *t = decode_tty_terminal (terminal);
2173 return (t && t->display_info.tty->type
2174 ? build_string (t->display_info.tty->type) : Qnil);
2177 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2178 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2180 TERMINAL can be a terminal object, a frame, or nil (meaning the
2181 selected frame's terminal). This function always returns nil if
2182 TERMINAL is not on a tty device. */)
2183 (Lisp_Object terminal)
2185 struct terminal *t = decode_tty_terminal (terminal);
2187 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2190 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2191 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2192 This is used to override the terminfo data, for certain terminals that
2193 do not really do underlining, but say that they do. This function has
2194 no effect if used on a non-tty terminal.
2196 TERMINAL can be a terminal object, a frame or nil (meaning the
2197 selected frame's terminal). This function always returns nil if
2198 TERMINAL does not refer to a text terminal. */)
2199 (Lisp_Object terminal)
2201 struct terminal *t = decode_live_terminal (terminal);
2203 if (t->type == output_termcap)
2204 t->display_info.tty->TS_enter_underline_mode = 0;
2205 return Qnil;
2208 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2209 doc: /* Return the topmost terminal frame on TERMINAL.
2210 TERMINAL can be a terminal object, a frame or nil (meaning the
2211 selected frame's terminal). This function returns nil if TERMINAL
2212 does not refer to a text terminal. Otherwise, it returns the
2213 top-most frame on the text terminal. */)
2214 (Lisp_Object terminal)
2216 struct terminal *t = decode_live_terminal (terminal);
2218 if (t->type == output_termcap)
2219 return t->display_info.tty->top_frame;
2220 return Qnil;
2225 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2226 doc: /* Suspend the terminal device TTY.
2228 The device is restored to its default state, and Emacs ceases all
2229 access to the tty device. Frames that use the device are not deleted,
2230 but input is not read from them and if they change, their display is
2231 not updated.
2233 TTY may be a terminal object, a frame, or nil for the terminal device
2234 of the currently selected frame.
2236 This function runs `suspend-tty-functions' after suspending the
2237 device. The functions are run with one arg, the id of the suspended
2238 terminal device.
2240 `suspend-tty' does nothing if it is called on a device that is already
2241 suspended.
2243 A suspended tty may be resumed by calling `resume-tty' on it. */)
2244 (Lisp_Object tty)
2246 struct terminal *t = decode_tty_terminal (tty);
2247 FILE *f;
2249 if (!t)
2250 error ("Attempt to suspend a non-text terminal device");
2252 f = t->display_info.tty->input;
2254 if (f)
2256 /* First run `suspend-tty-functions' and then clean up the tty
2257 state because `suspend-tty-functions' might need to change
2258 the tty state. */
2259 Lisp_Object term;
2260 XSETTERMINAL (term, t);
2261 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2263 reset_sys_modes (t->display_info.tty);
2264 delete_keyboard_wait_descriptor (fileno (f));
2266 #ifndef MSDOS
2267 fclose (f);
2268 if (f != t->display_info.tty->output)
2269 fclose (t->display_info.tty->output);
2270 #endif
2272 t->display_info.tty->input = 0;
2273 t->display_info.tty->output = 0;
2275 if (FRAMEP (t->display_info.tty->top_frame))
2276 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2280 /* Clear display hooks to prevent further output. */
2281 clear_tty_hooks (t);
2283 return Qnil;
2286 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2287 doc: /* Resume the previously suspended terminal device TTY.
2288 The terminal is opened and reinitialized. Frames that are on the
2289 suspended terminal are revived.
2291 It is an error to resume a terminal while another terminal is active
2292 on the same device.
2294 This function runs `resume-tty-functions' after resuming the terminal.
2295 The functions are run with one arg, the id of the resumed terminal
2296 device.
2298 `resume-tty' does nothing if it is called on a device that is not
2299 suspended.
2301 TTY may be a terminal object, a frame, or nil (meaning the selected
2302 frame's terminal). */)
2303 (Lisp_Object tty)
2305 struct terminal *t = decode_tty_terminal (tty);
2306 int fd;
2308 if (!t)
2309 error ("Attempt to resume a non-text terminal device");
2311 if (!t->display_info.tty->input)
2313 if (get_named_terminal (t->display_info.tty->name))
2314 error ("Cannot resume display while another display is active on the same device");
2316 #ifdef MSDOS
2317 t->display_info.tty->output = stdout;
2318 t->display_info.tty->input = stdin;
2319 #else /* !MSDOS */
2320 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2321 t->display_info.tty->input = t->display_info.tty->output
2322 = fd < 0 ? 0 : fdopen (fd, "w+");
2324 if (! t->display_info.tty->input)
2326 int open_errno = errno;
2327 emacs_close (fd);
2328 report_file_errno ("Cannot reopen tty device",
2329 build_string (t->display_info.tty->name),
2330 open_errno);
2333 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2334 dissociate_if_controlling_tty (fd);
2335 #endif
2337 add_keyboard_wait_descriptor (fd);
2339 if (FRAMEP (t->display_info.tty->top_frame))
2341 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2342 int width, height;
2343 int old_height = FRAME_COLS (f);
2344 int old_width = FRAME_TOTAL_LINES (f);
2346 /* Check if terminal/window size has changed while the frame
2347 was suspended. */
2348 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2349 if (width != old_width || height != old_height)
2350 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2351 0, 0, 0, 0);
2352 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2355 set_tty_hooks (t);
2356 init_sys_modes (t->display_info.tty);
2358 /* Run `resume-tty-functions'. */
2359 Lisp_Object term;
2360 XSETTERMINAL (term, t);
2361 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2364 set_tty_hooks (t);
2366 return Qnil;
2370 /***********************************************************************
2371 Mouse
2372 ***********************************************************************/
2374 #ifdef HAVE_GPM
2376 #ifndef HAVE_WINDOW_SYSTEM
2377 void
2378 term_mouse_moveto (int x, int y)
2380 /* TODO: how to set mouse position?
2381 const char *name;
2382 int fd;
2383 name = (const char *) ttyname (0);
2384 fd = emacs_open (name, O_WRONLY, 0);
2385 SOME_FUNCTION (x, y, fd);
2386 emacs_close (fd);
2387 last_mouse_x = x;
2388 last_mouse_y = y; */
2390 #endif /* HAVE_WINDOW_SYSTEM */
2392 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2393 void
2394 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2395 int start_hpos, int end_hpos,
2396 enum draw_glyphs_face draw)
2398 int nglyphs = end_hpos - start_hpos;
2399 struct frame *f = XFRAME (WINDOW_FRAME (w));
2400 struct tty_display_info *tty = FRAME_TTY (f);
2401 int face_id = tty->mouse_highlight.mouse_face_face_id;
2402 int save_x, save_y, pos_x, pos_y;
2404 if (end_hpos >= row->used[TEXT_AREA])
2405 nglyphs = row->used[TEXT_AREA] - start_hpos;
2407 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2408 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2410 /* Save current cursor co-ordinates. */
2411 save_y = curY (tty);
2412 save_x = curX (tty);
2413 cursor_to (f, pos_y, pos_x);
2415 if (draw == DRAW_MOUSE_FACE)
2416 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2417 nglyphs, face_id);
2418 else if (draw == DRAW_NORMAL_TEXT)
2419 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2421 cursor_to (f, save_y, save_x);
2424 static bool
2425 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2427 /* Has the mouse moved off the glyph it was on at the last sighting? */
2428 if (event->x != last_mouse_x || event->y != last_mouse_y)
2430 frame->mouse_moved = 1;
2431 note_mouse_highlight (frame, event->x, event->y);
2432 /* Remember which glyph we're now on. */
2433 last_mouse_x = event->x;
2434 last_mouse_y = event->y;
2435 return 1;
2437 return 0;
2440 /* Return the Time that corresponds to T. Wrap around on overflow. */
2441 static Time
2442 timeval_to_Time (struct timeval const *t)
2444 Time s_1000, ms;
2446 s_1000 = t->tv_sec;
2447 s_1000 *= 1000;
2448 ms = t->tv_usec / 1000;
2449 return s_1000 + ms;
2452 /* Return the current position of the mouse.
2454 Set *f to the frame the mouse is in, or zero if the mouse is in no
2455 Emacs frame. If it is set to zero, all the other arguments are
2456 garbage.
2458 Set *bar_window to Qnil, and *x and *y to the column and
2459 row of the character cell the mouse is over.
2461 Set *timeptr to the time the mouse was at the returned position.
2463 This clears mouse_moved until the next motion
2464 event arrives. */
2465 static void
2466 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2467 enum scroll_bar_part *part, Lisp_Object *x,
2468 Lisp_Object *y, Time *timeptr)
2470 struct timeval now;
2472 *fp = SELECTED_FRAME ();
2473 (*fp)->mouse_moved = 0;
2475 *bar_window = Qnil;
2476 *part = scroll_bar_above_handle;
2478 XSETINT (*x, last_mouse_x);
2479 XSETINT (*y, last_mouse_y);
2480 gettimeofday(&now, 0);
2481 *timeptr = timeval_to_Time (&now);
2484 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2486 If the event is a button press, then note that we have grabbed
2487 the mouse. */
2489 static Lisp_Object
2490 term_mouse_click (struct input_event *result, Gpm_Event *event,
2491 struct frame *f)
2493 struct timeval now;
2494 int i, j;
2496 result->kind = GPM_CLICK_EVENT;
2497 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2499 if (event->buttons & j) {
2500 result->code = i; /* button number */
2501 break;
2504 gettimeofday(&now, 0);
2505 result->timestamp = timeval_to_Time (&now);
2507 if (event->type & GPM_UP)
2508 result->modifiers = up_modifier;
2509 else if (event->type & GPM_DOWN)
2510 result->modifiers = down_modifier;
2511 else
2512 result->modifiers = 0;
2514 if (event->type & GPM_SINGLE)
2515 result->modifiers |= click_modifier;
2517 if (event->type & GPM_DOUBLE)
2518 result->modifiers |= double_modifier;
2520 if (event->type & GPM_TRIPLE)
2521 result->modifiers |= triple_modifier;
2523 if (event->type & GPM_DRAG)
2524 result->modifiers |= drag_modifier;
2526 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2528 /* 1 << KG_SHIFT */
2529 if (event->modifiers & (1 << 0))
2530 result->modifiers |= shift_modifier;
2532 /* 1 << KG_CTRL */
2533 if (event->modifiers & (1 << 2))
2534 result->modifiers |= ctrl_modifier;
2536 /* 1 << KG_ALT || KG_ALTGR */
2537 if (event->modifiers & (1 << 3)
2538 || event->modifiers & (1 << 1))
2539 result->modifiers |= meta_modifier;
2542 XSETINT (result->x, event->x);
2543 XSETINT (result->y, event->y);
2544 XSETFRAME (result->frame_or_window, f);
2545 result->arg = Qnil;
2546 return Qnil;
2550 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event,
2551 struct input_event *hold_quit)
2553 struct frame *f = XFRAME (tty->top_frame);
2554 struct input_event ie;
2555 bool do_help = 0;
2556 int count = 0;
2558 EVENT_INIT (ie);
2559 ie.kind = NO_EVENT;
2560 ie.arg = Qnil;
2562 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2563 previous_help_echo_string = help_echo_string;
2564 help_echo_string = Qnil;
2566 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2568 if (!term_mouse_movement (f, event))
2569 help_echo_string = previous_help_echo_string;
2571 /* If the contents of the global variable help_echo_string
2572 has changed, generate a HELP_EVENT. */
2573 if (!NILP (help_echo_string)
2574 || !NILP (previous_help_echo_string))
2575 do_help = 1;
2577 goto done;
2579 else {
2580 f->mouse_moved = 0;
2581 term_mouse_click (&ie, event, f);
2584 done:
2585 if (ie.kind != NO_EVENT)
2587 kbd_buffer_store_event_hold (&ie, hold_quit);
2588 count++;
2591 if (do_help
2592 && !(hold_quit && hold_quit->kind != NO_EVENT))
2594 Lisp_Object frame;
2596 if (f)
2597 XSETFRAME (frame, f);
2598 else
2599 frame = Qnil;
2601 gen_help_event (help_echo_string, frame, help_echo_window,
2602 help_echo_object, help_echo_pos);
2603 count++;
2606 return count;
2609 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2610 0, 0, 0,
2611 doc: /* Open a connection to Gpm.
2612 Gpm-mouse can only be activated for one tty at a time. */)
2613 (void)
2615 struct frame *f = SELECTED_FRAME ();
2616 struct tty_display_info *tty
2617 = ((f)->output_method == output_termcap
2618 ? (f)->terminal->display_info.tty : NULL);
2619 Gpm_Connect connection;
2621 if (!tty)
2622 error ("Gpm-mouse only works in the GNU/Linux console");
2623 if (gpm_tty == tty)
2624 return Qnil; /* Already activated, nothing to do. */
2625 if (gpm_tty)
2626 error ("Gpm-mouse can only be activated for one tty at a time");
2628 connection.eventMask = ~0;
2629 connection.defaultMask = ~GPM_HARD;
2630 connection.maxMod = ~0;
2631 connection.minMod = 0;
2632 gpm_zerobased = 1;
2634 if (Gpm_Open (&connection, 0) < 0)
2635 error ("Gpm-mouse failed to connect to the gpm daemon");
2636 else
2638 gpm_tty = tty;
2639 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2640 to generate SIGIOs. Apparently we need to call reset_sys_modes
2641 before calling init_sys_modes. */
2642 reset_sys_modes (tty);
2643 init_sys_modes (tty);
2644 add_gpm_wait_descriptor (gpm_fd);
2645 return Qnil;
2649 void
2650 close_gpm (int fd)
2652 if (fd >= 0)
2653 delete_gpm_wait_descriptor (fd);
2654 while (Gpm_Close()); /* close all the stack */
2655 gpm_tty = NULL;
2658 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2659 0, 0, 0,
2660 doc: /* Close a connection to Gpm. */)
2661 (void)
2663 struct frame *f = SELECTED_FRAME ();
2664 struct tty_display_info *tty
2665 = ((f)->output_method == output_termcap
2666 ? (f)->terminal->display_info.tty : NULL);
2668 if (!tty || gpm_tty != tty)
2669 return Qnil; /* Not activated on this terminal, nothing to do. */
2671 close_gpm (gpm_fd);
2672 return Qnil;
2674 #endif /* HAVE_GPM */
2677 /***********************************************************************
2678 Menus
2679 ***********************************************************************/
2681 #if !defined (MSDOS)
2683 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2685 However, unlike on MSDOS, where the menu text is drawn directly to
2686 the display video memory, on a TTY we use display_string (see
2687 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2688 the menu items into the frame's 'desired_matrix' glyph matrix, and
2689 then call update_frame_with_menu to deliver the results to the
2690 glass. The previous contents of the screen, in the form of the
2691 current_matrix, is stashed away, and used to restore screen
2692 contents when the menu selection changes or when the final
2693 selection is made and the menu should be popped down.
2695 The idea of this implementation was suggested by Gerd Moellmann. */
2697 #define TTYM_FAILURE -1
2698 #define TTYM_SUCCESS 1
2699 #define TTYM_NO_SELECT 2
2700 #define TTYM_IA_SELECT 3
2701 #define TTYM_NEXT 4
2702 #define TTYM_PREV 5
2704 /* These hold text of the current and the previous menu help messages. */
2705 static const char *menu_help_message, *prev_menu_help_message;
2706 /* Pane number and item number of the menu item which generated the
2707 last menu help message. */
2708 static int menu_help_paneno, menu_help_itemno;
2710 typedef struct tty_menu_struct
2712 int count;
2713 char **text;
2714 struct tty_menu_struct **submenu;
2715 int *panenumber; /* Also used as enabled flag. */
2716 ptrdiff_t allocated;
2717 int panecount;
2718 int width;
2719 const char **help_text;
2720 } tty_menu;
2722 /* Create a brand new menu structure. */
2724 static tty_menu *
2725 tty_menu_create (void)
2727 return xzalloc (sizeof *tty_menu_create ());
2730 /* Allocate some (more) memory for MENU ensuring that there is room for one
2731 more item. */
2733 static void
2734 tty_menu_make_room (tty_menu *menu)
2736 if (menu->allocated == menu->count)
2738 ptrdiff_t allocated = menu->allocated;
2739 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2740 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2741 menu->submenu = xrealloc (menu->submenu,
2742 allocated * sizeof *menu->submenu);
2743 menu->panenumber = xrealloc (menu->panenumber,
2744 allocated * sizeof *menu->panenumber);
2745 menu->help_text = xrealloc (menu->help_text,
2746 allocated * sizeof *menu->help_text);
2747 menu->allocated = allocated;
2751 /* Search the given menu structure for a given pane number. */
2753 static tty_menu *
2754 tty_menu_search_pane (tty_menu *menu, int pane)
2756 int i;
2757 tty_menu *try;
2759 for (i = 0; i < menu->count; i++)
2760 if (menu->submenu[i])
2762 if (pane == menu->panenumber[i])
2763 return menu->submenu[i];
2764 try = tty_menu_search_pane (menu->submenu[i], pane);
2765 if (try)
2766 return try;
2768 return (tty_menu *) 0;
2771 /* Determine how much screen space a given menu needs. */
2773 static void
2774 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2776 int i, h2, w2, maxsubwidth, maxheight;
2778 maxsubwidth = menu->width;
2779 maxheight = menu->count;
2780 for (i = 0; i < menu->count; i++)
2782 if (menu->submenu[i])
2784 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2785 if (w2 > maxsubwidth) maxsubwidth = w2;
2786 if (i + h2 > maxheight) maxheight = i + h2;
2789 *width = maxsubwidth;
2790 *height = maxheight;
2793 static void
2794 mouse_get_xy (int *x, int *y)
2796 struct frame *sf = SELECTED_FRAME ();
2797 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2798 enum scroll_bar_part part_dummy;
2799 Time time_dummy;
2801 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2802 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2803 &lisp_dummy, &part_dummy,
2804 &lmx, &lmy,
2805 &time_dummy);
2806 if (!NILP (lmx))
2808 *x = XINT (lmx);
2809 *y = XINT (lmy);
2813 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2814 (zero-based). */
2816 static void
2817 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2818 int mx, int my, int first_item, bool disp_help)
2820 int i, face, width, enabled, mousehere, row, col;
2821 struct frame *sf = SELECTED_FRAME ();
2822 struct tty_display_info *tty = FRAME_TTY (sf);
2823 /* Don't try to display more menu items than the console can display
2824 using the available screen lines. Exclude the echo area line, as
2825 it will be overwritten by the help-echo anyway. */
2826 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2828 menu_help_message = NULL;
2830 width = menu->width;
2831 col = cursorX (tty);
2832 row = cursorY (tty);
2833 for (i = 0; i < max_items; i++)
2835 int max_width = width + 2; /* +2 for padding blanks on each side */
2836 int j = i + first_item;
2838 if (menu->submenu[j])
2839 max_width += 2; /* for displaying " >" after the item */
2840 enabled
2841 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2842 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2843 face = faces[enabled + mousehere * 2];
2844 /* Display the menu help string for the i-th menu item even if
2845 the menu item is currently disabled. That's what the GUI
2846 code does. */
2847 if (disp_help && enabled + mousehere * 2 >= 2)
2849 menu_help_message = menu->help_text[j];
2850 menu_help_paneno = pn - 1;
2851 menu_help_itemno = j;
2853 /* Take note of the coordinates of the active menu item, to
2854 display the cursor there. */
2855 if (mousehere)
2857 row = y + i;
2858 col = x;
2860 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2861 menu->submenu[j] != NULL);
2863 update_frame_with_menu (sf, row, col);
2866 /* --------------------------- X Menu emulation ---------------------- */
2868 /* Create a new pane and place it on the outer-most level. */
2870 static int
2871 tty_menu_add_pane (tty_menu *menu, const char *txt)
2873 int len;
2875 tty_menu_make_room (menu);
2876 menu->submenu[menu->count] = tty_menu_create ();
2877 menu->text[menu->count] = (char *)txt;
2878 menu->panenumber[menu->count] = ++menu->panecount;
2879 menu->help_text[menu->count] = NULL;
2880 menu->count++;
2882 /* Update the menu width, if necessary. */
2883 len = menu_item_width ((const unsigned char *) txt);
2884 if (len > menu->width)
2885 menu->width = len;
2887 return menu->panecount;
2890 /* Create a new item in a menu pane. */
2892 static bool
2893 tty_menu_add_selection (tty_menu *menu, int pane,
2894 char *txt, bool enable, char const *help_text)
2896 int len;
2898 if (pane)
2900 menu = tty_menu_search_pane (menu, pane);
2901 if (! menu)
2902 return 0;
2904 tty_menu_make_room (menu);
2905 menu->submenu[menu->count] = (tty_menu *) 0;
2906 menu->text[menu->count] = txt;
2907 menu->panenumber[menu->count] = enable;
2908 menu->help_text[menu->count] = help_text;
2909 menu->count++;
2911 /* Update the menu width, if necessary. */
2912 len = menu_item_width ((const unsigned char *) txt);
2913 if (len > menu->width)
2914 menu->width = len;
2916 return 1;
2919 /* Decide where the menu would be placed if requested at (X,Y). */
2921 static void
2922 tty_menu_locate (tty_menu *menu, int x, int y,
2923 int *ulx, int *uly, int *width, int *height)
2925 tty_menu_calc_size (menu, width, height);
2926 *ulx = x + 1;
2927 *uly = y;
2928 *width += 2;
2931 struct tty_menu_state
2933 struct glyph_matrix *screen_behind;
2934 tty_menu *menu;
2935 int pane;
2936 int x, y;
2939 /* Save away the contents of frame F's current frame matrix, and
2940 enable all its rows. Value is a glyph matrix holding the contents
2941 of F's current frame matrix with all its glyph rows enabled. */
2943 static struct glyph_matrix *
2944 save_and_enable_current_matrix (struct frame *f)
2946 int i;
2947 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2948 saved->nrows = f->current_matrix->nrows;
2949 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2951 for (i = 0; i < saved->nrows; ++i)
2953 struct glyph_row *from = f->current_matrix->rows + i;
2954 struct glyph_row *to = saved->rows + i;
2955 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2957 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2958 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2959 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2960 /* Make sure every row is enabled, or else update_frame will not
2961 redraw them. (Rows that are identical to what is already on
2962 screen will not be redrawn anyway.) */
2963 to->enabled_p = true;
2964 to->hash = from->hash;
2967 return saved;
2970 /* Restore the contents of frame F's desired frame matrix from SAVED,
2971 and free memory associated with SAVED. */
2973 static void
2974 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2976 int i;
2978 for (i = 0; i < saved->nrows; ++i)
2980 struct glyph_row *from = saved->rows + i;
2981 struct glyph_row *to = f->desired_matrix->rows + i;
2982 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2984 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2985 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2986 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2987 to->enabled_p = from->enabled_p;
2988 to->hash = from->hash;
2992 static void
2993 free_saved_screen (struct glyph_matrix *saved)
2995 int i;
2997 if (!saved)
2998 return; /* Already freed! */
3000 for (i = 0; i < saved->nrows; ++i)
3002 struct glyph_row *from = saved->rows + i;
3004 xfree (from->glyphs[TEXT_AREA]);
3007 xfree (saved->rows);
3008 xfree (saved);
3011 /* Update the display of frame F from its saved contents. */
3012 static void
3013 screen_update (struct frame *f, struct glyph_matrix *mtx)
3015 restore_desired_matrix (f, mtx);
3016 update_frame_with_menu (f, -1, -1);
3019 typedef enum {
3020 MI_QUIT_MENU = -1,
3021 MI_CONTINUE = 0,
3022 MI_ITEM_SELECTED = 1,
3023 MI_NEXT_ITEM = 2,
3024 MI_PREV_ITEM = 3,
3025 MI_SCROLL_FORWARD = 4,
3026 MI_SCROLL_BACK = 5
3027 } mi_result;
3029 /* Read user input and return X and Y coordinates where that input
3030 puts us. We only consider mouse movement and click events, and
3031 keyboard movement commands; the rest are ignored. */
3032 static mi_result
3033 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3034 bool *first_time)
3036 if (*first_time)
3038 *first_time = false;
3039 sf->mouse_moved = 1;
3041 else
3043 Lisp_Object cmd;
3044 bool usable_input = 1;
3045 mi_result st = MI_CONTINUE;
3046 struct tty_display_info *tty = FRAME_TTY (sf);
3047 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3049 /* Signal the keyboard reading routines we are displaying a menu
3050 on this terminal. */
3051 tty->showing_menu = 1;
3052 /* We want mouse movements be reported by read_menu_command. */
3053 do_mouse_tracking = Qt;
3054 do {
3055 cmd = read_menu_command ();
3056 } while (NILP (cmd));
3057 tty->showing_menu = 0;
3058 do_mouse_tracking = saved_mouse_tracking;
3060 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3061 /* If some input switched frames under our feet, exit the
3062 menu, since the menu faces are no longer valid, and the
3063 menu is no longer relevant anyway. */
3064 || sf != SELECTED_FRAME ())
3065 return MI_QUIT_MENU;
3066 if (EQ (cmd, Qtty_menu_mouse_movement))
3067 mouse_get_xy (x, y);
3068 else if (EQ (cmd, Qtty_menu_next_menu))
3070 usable_input = 0;
3071 st = MI_NEXT_ITEM;
3073 else if (EQ (cmd, Qtty_menu_prev_menu))
3075 usable_input = 0;
3076 st = MI_PREV_ITEM;
3078 else if (EQ (cmd, Qtty_menu_next_item))
3080 if (*y < max_y)
3081 *y += 1;
3082 else
3083 st = MI_SCROLL_FORWARD;
3085 else if (EQ (cmd, Qtty_menu_prev_item))
3087 if (*y > min_y)
3088 *y -= 1;
3089 else
3090 st = MI_SCROLL_BACK;
3092 else if (EQ (cmd, Qtty_menu_select))
3093 st = MI_ITEM_SELECTED;
3094 else if (!EQ (cmd, Qtty_menu_ignore))
3095 usable_input = 0;
3096 if (usable_input)
3097 sf->mouse_moved = 1;
3098 return st;
3100 return MI_CONTINUE;
3103 /* Display menu, wait for user's response, and return that response. */
3104 static int
3105 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3106 int x0, int y0, char **txt,
3107 void (*help_callback)(char const *, int, int),
3108 bool kbd_navigation)
3110 struct tty_menu_state *state;
3111 int statecount, x, y, i;
3112 bool leave, onepane;
3113 int result UNINIT;
3114 int title_faces[4]; /* Face to display the menu title. */
3115 int faces[4], buffers_num_deleted = 0;
3116 struct frame *sf = SELECTED_FRAME ();
3117 struct tty_display_info *tty = FRAME_TTY (sf);
3118 bool first_time;
3119 Lisp_Object selectface;
3120 int first_item = 0;
3121 int col, row;
3122 Lisp_Object prev_inhibit_redisplay = Vinhibit_redisplay;
3123 USE_SAFE_ALLOCA;
3125 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3126 around the display. */
3127 if (x0 <= 0)
3128 x0 = 1;
3129 if (y0 <= 0)
3130 y0 = 1;
3132 SAFE_NALLOCA (state, 1, menu->panecount);
3133 memset (state, 0, sizeof (*state));
3134 faces[0]
3135 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3136 DEFAULT_FACE_ID, 1);
3137 faces[1]
3138 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3139 DEFAULT_FACE_ID, 1);
3140 selectface = intern ("tty-menu-selected-face");
3141 faces[2] = lookup_derived_face (sf, selectface,
3142 faces[0], 1);
3143 faces[3] = lookup_derived_face (sf, selectface,
3144 faces[1], 1);
3146 /* Make sure the menu title is always displayed with
3147 `tty-menu-selected-face', no matter where the mouse pointer is. */
3148 for (i = 0; i < 4; i++)
3149 title_faces[i] = faces[3];
3151 statecount = 1;
3153 /* Don't let the title for the "Buffers" popup menu include a
3154 digit (which is ugly).
3156 This is a terrible kludge, but I think the "Buffers" case is
3157 the only one where the title includes a number, so it doesn't
3158 seem to be necessary to make this more general. */
3159 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3161 menu->text[0][7] = '\0';
3162 buffers_num_deleted = 1;
3165 /* Inhibit redisplay for as long as the menu is active, to avoid
3166 messing the screen if some timer calls sit-for or a similar
3167 function. */
3168 Vinhibit_redisplay = Qt;
3170 /* Force update of the current frame, so that the desired and the
3171 current matrices are identical. */
3172 update_frame_with_menu (sf, -1, -1);
3173 state[0].menu = menu;
3174 state[0].screen_behind = save_and_enable_current_matrix (sf);
3176 /* Display the menu title. We subtract 1 from x0 and y0 because we
3177 want to interpret them as zero-based column and row coordinates,
3178 and also because we want the first item of the menu, not its
3179 title, to appear at x0,y0. */
3180 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3182 /* Turn off the cursor. Otherwise it shows through the menu
3183 panes, which is ugly. */
3184 col = cursorX (tty);
3185 row = cursorY (tty);
3186 tty_hide_cursor (tty);
3188 if (buffers_num_deleted)
3189 menu->text[0][7] = ' ';
3190 onepane = menu->count == 1 && menu->submenu[0];
3191 if (onepane)
3193 menu->width = menu->submenu[0]->width;
3194 state[0].menu = menu->submenu[0];
3196 else
3198 state[0].menu = menu;
3200 state[0].x = x0 - 1;
3201 state[0].y = y0;
3202 state[0].pane = onepane;
3204 x = state[0].x;
3205 y = state[0].y;
3206 first_time = true;
3208 leave = 0;
3209 while (!leave)
3211 mi_result input_status;
3212 int min_y = state[0].y;
3213 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3215 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3216 if (input_status)
3218 leave = 1;
3219 switch (input_status)
3221 case MI_QUIT_MENU:
3222 /* Remove the last help-echo, so that it doesn't
3223 re-appear after "Quit". */
3224 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3225 result = TTYM_NO_SELECT;
3226 break;
3227 case MI_NEXT_ITEM:
3228 if (kbd_navigation)
3229 result = TTYM_NEXT;
3230 else
3231 leave = 0;
3232 break;
3233 case MI_PREV_ITEM:
3234 if (kbd_navigation)
3235 result = TTYM_PREV;
3236 else
3237 leave = 0;
3238 break;
3239 case MI_SCROLL_FORWARD:
3240 if (y - min_y == state[0].menu->count - 1 - first_item)
3242 y = min_y;
3243 first_item = 0;
3245 else
3246 first_item++;
3247 leave = 0;
3248 break;
3249 case MI_SCROLL_BACK:
3250 if (first_item == 0)
3252 y = max_y;
3253 first_item = state[0].menu->count - 1 - (y - min_y);
3255 else
3256 first_item--;
3257 leave = 0;
3258 break;
3259 default:
3260 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3261 break;
3264 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3266 sf->mouse_moved = 0;
3267 result = TTYM_IA_SELECT;
3268 for (i = 0; i < statecount; i++)
3269 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3271 int dy = y - state[i].y + first_item;
3272 if (0 <= dy && dy < state[i].menu->count)
3274 if (!state[i].menu->submenu[dy])
3276 if (state[i].menu->panenumber[dy])
3277 result = TTYM_SUCCESS;
3278 else
3279 result = TTYM_IA_SELECT;
3281 *pane = state[i].pane - 1;
3282 *selidx = dy;
3283 /* We hit some part of a menu, so drop extra menus that
3284 have been opened. That does not include an open and
3285 active submenu. */
3286 if (i != statecount - 2
3287 || state[i].menu->submenu[dy] != state[i + 1].menu)
3288 while (i != statecount - 1)
3290 statecount--;
3291 screen_update (sf, state[statecount].screen_behind);
3292 state[statecount].screen_behind = NULL;
3294 if (i == statecount - 1 && state[i].menu->submenu[dy])
3296 tty_menu_display (state[i].menu,
3297 state[i].x,
3298 state[i].y,
3299 state[i].pane,
3300 faces, x, y, first_item, 1);
3301 state[statecount].menu = state[i].menu->submenu[dy];
3302 state[statecount].pane = state[i].menu->panenumber[dy];
3303 state[statecount].screen_behind
3304 = save_and_enable_current_matrix (sf);
3305 state[statecount].x
3306 = state[i].x + state[i].menu->width + 2;
3307 state[statecount].y = y;
3308 statecount++;
3312 tty_menu_display (state[statecount - 1].menu,
3313 state[statecount - 1].x,
3314 state[statecount - 1].y,
3315 state[statecount - 1].pane,
3316 faces, x, y, first_item, 1);
3317 /* The call to display help-echo below will move the cursor,
3318 so remember its current position as computed by
3319 tty_menu_display. */
3320 col = cursorX (tty);
3321 row = cursorY (tty);
3324 /* Display the help-echo message for the currently-selected menu
3325 item. */
3326 if ((menu_help_message || prev_menu_help_message)
3327 && menu_help_message != prev_menu_help_message)
3329 help_callback (menu_help_message,
3330 menu_help_paneno, menu_help_itemno);
3331 /* Move the cursor to the beginning of the current menu
3332 item, so that screen readers and other accessibility aids
3333 know where the active region is. */
3334 cursor_to (sf, row, col);
3335 prev_menu_help_message = menu_help_message;
3337 /* Both tty_menu_display and help_callback invoke update_end,
3338 which calls tty_show_cursor. Re-hide it, so it doesn't show
3339 through the menus. */
3340 tty_hide_cursor (tty);
3341 fflush_unlocked (tty->output);
3344 sf->mouse_moved = 0;
3345 screen_update (sf, state[0].screen_behind);
3346 while (statecount--)
3347 free_saved_screen (state[statecount].screen_behind);
3348 tty_show_cursor (tty); /* Turn cursor back on. */
3349 fflush_unlocked (tty->output);
3351 /* Clean up any mouse events that are waiting inside Emacs event queue.
3352 These events are likely to be generated before the menu was even
3353 displayed, probably because the user pressed and released the button
3354 (which invoked the menu) too quickly. If we don't remove these events,
3355 Emacs will process them after we return and surprise the user. */
3356 discard_mouse_events ();
3357 if (!kbd_buffer_events_waiting ())
3358 clear_input_pending ();
3359 SAFE_FREE ();
3360 Vinhibit_redisplay = prev_inhibit_redisplay;
3361 return result;
3364 /* Dispose of a menu. */
3366 static void
3367 tty_menu_destroy (tty_menu *menu)
3369 int i;
3370 if (menu->allocated)
3372 for (i = 0; i < menu->count; i++)
3373 if (menu->submenu[i])
3374 tty_menu_destroy (menu->submenu[i]);
3375 xfree (menu->text);
3376 xfree (menu->submenu);
3377 xfree (menu->panenumber);
3378 xfree (menu->help_text);
3380 xfree (menu);
3381 menu_help_message = prev_menu_help_message = NULL;
3384 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3386 PANE is the pane number, and ITEM is the menu item number in
3387 the menu (currently not used). */
3389 static void
3390 tty_menu_help_callback (char const *help_string, int pane, int item)
3392 Lisp_Object *first_item;
3393 Lisp_Object pane_name;
3394 Lisp_Object menu_object;
3396 first_item = XVECTOR (menu_items)->contents;
3397 if (EQ (first_item[0], Qt))
3398 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3399 else if (EQ (first_item[0], Qquote))
3400 /* This shouldn't happen, see xmenu_show. */
3401 pane_name = empty_unibyte_string;
3402 else
3403 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3405 /* (menu-item MENU-NAME PANE-NUMBER) */
3406 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3407 show_help_echo (help_string ? build_string (help_string) : Qnil,
3408 Qnil, menu_object, make_number (item));
3411 static void
3412 tty_pop_down_menu (Lisp_Object arg)
3414 tty_menu *menu = XSAVE_POINTER (arg, 0);
3415 struct buffer *orig_buffer = XSAVE_POINTER (arg, 1);
3417 block_input ();
3418 tty_menu_destroy (menu);
3419 set_buffer_internal (orig_buffer);
3420 unblock_input ();
3423 /* Return the zero-based index of the last menu-bar item on frame F. */
3424 static int
3425 tty_menu_last_menubar_item (struct frame *f)
3427 int i = 0;
3429 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3430 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3432 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3434 while (i < ASIZE (items))
3436 Lisp_Object str;
3438 str = AREF (items, i + 1);
3439 if (NILP (str))
3440 break;
3441 i += 4;
3443 i -= 4; /* Went one too far! */
3445 return i;
3448 /* Find in frame F's menu bar the menu item that is next or previous
3449 to the item at X/Y, and return that item's position in X/Y. WHICH
3450 says which one--next or previous--item to look for. X and Y are
3451 measured in character cells. This should only be called on TTY
3452 frames. */
3453 static void
3454 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3456 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3457 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3459 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3460 int last_i = tty_menu_last_menubar_item (f);
3461 int i, prev_x;
3463 /* This loop assumes a single menu-bar line, and will fail to
3464 find an item if it is not in the first line. Note that
3465 make_lispy_event in keyboard.c makes the same assumption. */
3466 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3468 Lisp_Object pos, str;
3469 int ix;
3471 str = AREF (items, i + 1);
3472 pos = AREF (items, i + 3);
3473 if (NILP (str))
3474 return;
3475 ix = XINT (pos);
3476 if (ix <= *x
3477 /* We use <= so the blank between 2 items on a TTY is
3478 considered part of the previous item. */
3479 && *x <= ix + menu_item_width (SDATA (str)))
3481 /* Found current item. Now compute the X coordinate of
3482 the previous or next item. */
3483 if (which == TTYM_NEXT)
3485 if (i < last_i)
3486 *x = XINT (AREF (items, i + 4 + 3));
3487 else
3488 *x = 0; /* Wrap around to the first item. */
3490 else if (prev_x < 0)
3492 /* Wrap around to the last item. */
3493 *x = XINT (AREF (items, last_i + 3));
3495 else
3496 *x = prev_x;
3497 return;
3499 prev_x = ix;
3504 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3505 Lisp_Object
3506 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3507 Lisp_Object title, const char **error_name)
3509 tty_menu *menu;
3510 int pane, selidx, lpane, status;
3511 Lisp_Object entry, pane_prefix;
3512 char *datap;
3513 int ulx, uly, width, height;
3514 int item_x, item_y;
3515 int dispwidth, dispheight;
3516 int i, j, lines, maxlines;
3517 int maxwidth;
3518 ptrdiff_t specpdl_count;
3520 eassert (FRAME_TERMCAP_P (f));
3522 *error_name = 0;
3523 if (menu_items_n_panes == 0)
3524 return Qnil;
3526 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3528 *error_name = "Empty menu";
3529 return Qnil;
3532 /* Make the menu on that window. */
3533 menu = tty_menu_create ();
3535 /* Don't GC while we prepare and show the menu, because we give the
3536 menu functions pointers to the contents of strings. */
3537 specpdl_count = inhibit_garbage_collection ();
3539 /* Avoid crashes if, e.g., another client will connect while we
3540 are in a menu. */
3541 temporarily_switch_to_single_kboard (f);
3543 /* Adjust coordinates to be root-window-relative. */
3544 item_x = x += f->left_pos;
3545 item_y = y += f->top_pos;
3547 /* Create all the necessary panes and their items. */
3548 USE_SAFE_ALLOCA;
3549 maxwidth = maxlines = lines = i = 0;
3550 lpane = TTYM_FAILURE;
3551 while (i < menu_items_used)
3553 if (EQ (AREF (menu_items, i), Qt))
3555 /* Create a new pane. */
3556 Lisp_Object pane_name, prefix;
3557 const char *pane_string;
3559 maxlines = max (maxlines, lines);
3560 lines = 0;
3561 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3562 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3563 pane_string = (NILP (pane_name)
3564 ? "" : SSDATA (pane_name));
3565 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3566 pane_string++;
3568 lpane = tty_menu_add_pane (menu, pane_string);
3569 if (lpane == TTYM_FAILURE)
3571 tty_menu_destroy (menu);
3572 *error_name = "Can't create pane";
3573 entry = Qnil;
3574 goto tty_menu_end;
3576 i += MENU_ITEMS_PANE_LENGTH;
3578 /* Find the width of the widest item in this pane. */
3579 j = i;
3580 while (j < menu_items_used)
3582 Lisp_Object item;
3583 item = AREF (menu_items, j);
3584 if (EQ (item, Qt))
3585 break;
3586 if (NILP (item))
3588 j++;
3589 continue;
3591 width = SBYTES (item);
3592 if (width > maxwidth)
3593 maxwidth = width;
3595 j += MENU_ITEMS_ITEM_LENGTH;
3598 /* Ignore a nil in the item list.
3599 It's meaningful only for dialog boxes. */
3600 else if (EQ (AREF (menu_items, i), Qquote))
3601 i += 1;
3602 else
3604 /* Create a new item within current pane. */
3605 Lisp_Object item_name, enable, descrip, help;
3606 char *item_data;
3607 char const *help_string;
3609 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3610 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3611 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3612 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3613 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3615 if (!NILP (descrip))
3617 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3618 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3619 for (j = SCHARS (item_name); j < maxwidth; j++)
3620 item_data[j] = ' ';
3621 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3622 item_data[j + SBYTES (descrip)] = 0;
3624 else
3625 item_data = SSDATA (item_name);
3627 if (lpane == TTYM_FAILURE
3628 || (! tty_menu_add_selection (menu, lpane, item_data,
3629 !NILP (enable), help_string)))
3631 tty_menu_destroy (menu);
3632 *error_name = "Can't add selection to menu";
3633 entry = Qnil;
3634 goto tty_menu_end;
3636 i += MENU_ITEMS_ITEM_LENGTH;
3637 lines++;
3641 maxlines = max (maxlines, lines);
3643 /* All set and ready to fly. */
3644 dispwidth = f->text_cols;
3645 dispheight = f->text_lines;
3646 x = min (x, dispwidth);
3647 y = min (y, dispheight);
3648 x = max (x, 1);
3649 y = max (y, 1);
3650 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3651 if (ulx + width > dispwidth)
3653 x -= (ulx + width) - dispwidth;
3654 ulx = dispwidth - width;
3656 if (uly + height > dispheight)
3658 y -= (uly + height) - dispheight;
3659 uly = dispheight - height;
3662 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3664 /* Move the menu away of the echo area, to avoid overwriting the
3665 menu with help echo messages or vice versa. */
3666 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3668 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3669 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3671 else
3673 y -= 2;
3674 uly -= 2;
3678 if (ulx < 0) x -= ulx;
3679 if (uly < 0) y -= uly;
3681 #if 0
3682 /* This code doesn't make sense on a TTY, since it can easily annul
3683 the adjustments above that carefully avoid truncation of the menu
3684 items. I think it was written to fix some problem that only
3685 happens on X11. */
3686 if (! for_click)
3688 /* If position was not given by a mouse click, adjust so upper left
3689 corner of the menu as a whole ends up at given coordinates. This
3690 is what x-popup-menu says in its documentation. */
3691 x += width / 2;
3692 y += 1.5 * height / (maxlines + 2);
3694 #endif
3696 pane = selidx = 0;
3698 /* We save and restore the current buffer because tty_menu_activate
3699 triggers redisplay, which switches buffers at will. */
3700 record_unwind_protect (tty_pop_down_menu,
3701 make_save_ptr_ptr (menu, current_buffer));
3703 specbind (Qoverriding_terminal_local_map,
3704 Fsymbol_value (Qtty_menu_navigation_map));
3705 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3706 tty_menu_help_callback,
3707 menuflags & MENU_KBD_NAVIGATION);
3708 entry = pane_prefix = Qnil;
3710 switch (status)
3712 case TTYM_SUCCESS:
3713 /* Find the item number SELIDX in pane number PANE. */
3714 i = 0;
3715 while (i < menu_items_used)
3717 if (EQ (AREF (menu_items, i), Qt))
3719 if (pane == 0)
3720 pane_prefix
3721 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3722 pane--;
3723 i += MENU_ITEMS_PANE_LENGTH;
3725 else
3727 if (pane == -1)
3729 if (selidx == 0)
3731 entry
3732 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3733 if (menuflags & MENU_KEYMAPS)
3735 entry = Fcons (entry, Qnil);
3736 if (!NILP (pane_prefix))
3737 entry = Fcons (pane_prefix, entry);
3739 break;
3741 selidx--;
3743 i += MENU_ITEMS_ITEM_LENGTH;
3746 break;
3748 case TTYM_NEXT:
3749 case TTYM_PREV:
3750 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3751 entry = Fcons (make_number (item_x), make_number (item_y));
3752 break;
3754 case TTYM_FAILURE:
3755 *error_name = "Can't activate menu";
3756 case TTYM_IA_SELECT:
3757 break;
3758 case TTYM_NO_SELECT:
3759 /* If the selected frame was changed while we displayed a menu,
3760 throw to top level in order to undo any temporary settings
3761 made by TTY menu code. */
3762 if (f != SELECTED_FRAME ())
3763 Ftop_level ();
3764 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3765 the menu was invoked with a mouse event as POSITION). */
3766 if (!(menuflags & MENU_FOR_CLICK))
3767 quit ();
3768 break;
3771 tty_menu_end:
3773 SAFE_FREE ();
3774 unbind_to (specpdl_count, Qnil);
3775 return entry;
3778 #endif /* !MSDOS */
3781 #ifndef MSDOS
3782 /***********************************************************************
3783 Initialization
3784 ***********************************************************************/
3786 /* Initialize the tty-dependent part of frame F. The frame must
3787 already have its device initialized. */
3789 void
3790 create_tty_output (struct frame *f)
3792 struct tty_output *t = xzalloc (sizeof *t);
3794 eassert (FRAME_TERMCAP_P (f));
3796 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3798 f->output_data.tty = t;
3801 /* Delete frame F's face cache, and its tty-dependent part. */
3803 static void
3804 tty_free_frame_resources (struct frame *f)
3806 eassert (FRAME_TERMCAP_P (f));
3807 free_frame_faces (f);
3808 xfree (f->output_data.tty);
3811 #else /* MSDOS */
3813 /* Delete frame F's face cache. */
3815 static void
3816 tty_free_frame_resources (struct frame *f)
3818 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3819 free_frame_faces (f);
3821 #endif /* MSDOS */
3823 /* Reset the hooks in TERMINAL. */
3825 static void
3826 clear_tty_hooks (struct terminal *terminal)
3828 terminal->rif = 0;
3829 terminal->cursor_to_hook = 0;
3830 terminal->raw_cursor_to_hook = 0;
3831 terminal->clear_to_end_hook = 0;
3832 terminal->clear_frame_hook = 0;
3833 terminal->clear_end_of_line_hook = 0;
3834 terminal->ins_del_lines_hook = 0;
3835 terminal->insert_glyphs_hook = 0;
3836 terminal->write_glyphs_hook = 0;
3837 terminal->delete_glyphs_hook = 0;
3838 terminal->ring_bell_hook = 0;
3839 terminal->reset_terminal_modes_hook = 0;
3840 terminal->set_terminal_modes_hook = 0;
3841 terminal->update_begin_hook = 0;
3842 terminal->update_end_hook = 0;
3843 terminal->set_terminal_window_hook = 0;
3844 terminal->mouse_position_hook = 0;
3845 terminal->frame_rehighlight_hook = 0;
3846 terminal->frame_raise_lower_hook = 0;
3847 terminal->fullscreen_hook = 0;
3848 terminal->menu_show_hook = 0;
3849 terminal->set_vertical_scroll_bar_hook = 0;
3850 terminal->set_horizontal_scroll_bar_hook = 0;
3851 terminal->condemn_scroll_bars_hook = 0;
3852 terminal->redeem_scroll_bar_hook = 0;
3853 terminal->judge_scroll_bars_hook = 0;
3854 terminal->read_socket_hook = 0;
3855 terminal->frame_up_to_date_hook = 0;
3857 /* Leave these two set, or suspended frames are not deleted
3858 correctly. */
3859 terminal->delete_frame_hook = &tty_free_frame_resources;
3860 terminal->delete_terminal_hook = &delete_tty;
3863 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3865 static void
3866 set_tty_hooks (struct terminal *terminal)
3868 terminal->cursor_to_hook = &tty_cursor_to;
3869 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3870 terminal->clear_to_end_hook = &tty_clear_to_end;
3871 terminal->clear_frame_hook = &tty_clear_frame;
3872 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3873 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3874 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3875 terminal->write_glyphs_hook = &tty_write_glyphs;
3876 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3877 terminal->ring_bell_hook = &tty_ring_bell;
3878 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3879 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3880 terminal->update_end_hook = &tty_update_end;
3881 #ifdef MSDOS
3882 terminal->menu_show_hook = &x_menu_show;
3883 #else
3884 terminal->menu_show_hook = &tty_menu_show;
3885 #endif
3886 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3887 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3888 terminal->delete_frame_hook = &tty_free_frame_resources;
3889 terminal->delete_terminal_hook = &delete_tty;
3890 /* Other hooks are NULL by default. */
3893 /* If FD is the controlling terminal, drop it. */
3894 static void
3895 dissociate_if_controlling_tty (int fd)
3897 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3898 so dissociate it by invoking setsid. */
3899 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3901 #ifdef TIOCNOTTY
3902 /* setsid failed, presumably because Emacs is already a process
3903 group leader. Fall back on the obsolescent way to dissociate
3904 a controlling tty. */
3905 sigset_t oldset;
3906 block_tty_out_signal (&oldset);
3907 ioctl (fd, TIOCNOTTY, 0);
3908 unblock_tty_out_signal (&oldset);
3909 #endif
3913 /* Create a termcap display on the tty device with the given name and
3914 type.
3916 If NAME is NULL, then use the controlling tty, i.e., DEV_TTY.
3917 Otherwise NAME should be a path to the tty device file,
3918 e.g. "/dev/pts/7".
3920 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3922 If MUST_SUCCEED is true, then all errors are fatal. */
3924 struct terminal *
3925 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3927 struct tty_display_info *tty = NULL;
3928 struct terminal *terminal = NULL;
3929 #ifndef DOS_NT
3930 char *area;
3931 char **address = &area;
3932 int status;
3933 sigset_t oldset;
3934 bool ctty = false; /* True if asked to open controlling tty. */
3935 #endif
3937 if (!terminal_type)
3938 maybe_fatal (must_succeed, 0,
3939 "Unknown terminal type",
3940 "Unknown terminal type");
3942 if (name == NULL)
3943 name = DEV_TTY;
3944 #ifndef DOS_NT
3945 if (!strcmp (name, DEV_TTY))
3946 ctty = 1;
3947 #endif
3949 /* If we already have a terminal on the given device, use that. If
3950 all such terminals are suspended, create a new one instead. */
3951 /* XXX Perhaps this should be made explicit by having init_tty
3952 always create a new terminal and separating terminal and frame
3953 creation on Lisp level. */
3954 terminal = get_named_terminal (name);
3955 if (terminal)
3956 return terminal;
3958 terminal = create_terminal (output_termcap, NULL);
3959 #ifdef MSDOS
3960 if (been_here > 0)
3961 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3962 name, "");
3963 been_here = 1;
3964 tty = &the_only_display_info;
3965 #else
3966 tty = xzalloc (sizeof *tty);
3967 #endif
3968 tty->top_frame = Qnil;
3969 tty->next = tty_list;
3970 tty_list = tty;
3972 terminal->display_info.tty = tty;
3973 tty->terminal = terminal;
3975 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3976 Wcm_clear (tty);
3978 encode_terminal_src_size = 0;
3979 encode_terminal_dst_size = 0;
3982 #ifndef DOS_NT
3983 set_tty_hooks (terminal);
3986 /* Open the terminal device. */
3988 /* If !ctty, don't recognize it as our controlling terminal, and
3989 don't make it the controlling tty if we don't have one now.
3991 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3992 defined on Hurd. On other systems, we need to explicitly
3993 dissociate ourselves from the controlling tty when we want to
3994 open a frame on the same terminal. */
3995 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3996 int fd = emacs_open (name, flags, 0);
3997 tty->input = tty->output
3998 = ((fd < 0 || ! isatty (fd))
3999 ? NULL
4000 : fdopen (fd, "w+"));
4002 if (! tty->input)
4004 char const *diagnostic
4005 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
4006 emacs_close (fd);
4007 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4010 tty->name = xstrdup (name);
4011 terminal->name = xstrdup (name);
4013 if (!O_IGNORE_CTTY && !ctty)
4014 dissociate_if_controlling_tty (fd);
4017 tty->type = xstrdup (terminal_type);
4019 add_keyboard_wait_descriptor (fileno (tty->input));
4021 Wcm_clear (tty);
4023 /* On some systems, tgetent tries to access the controlling
4024 terminal. */
4025 block_tty_out_signal (&oldset);
4026 status = tgetent (tty->termcap_term_buffer, terminal_type);
4027 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4028 emacs_abort ();
4029 unblock_tty_out_signal (&oldset);
4031 if (status < 0)
4033 #ifdef TERMINFO
4034 maybe_fatal (must_succeed, terminal,
4035 "Cannot open terminfo database file",
4036 "Cannot open terminfo database file");
4037 #else
4038 maybe_fatal (must_succeed, terminal,
4039 "Cannot open termcap database file",
4040 "Cannot open termcap database file");
4041 #endif
4043 if (status == 0)
4045 maybe_fatal (must_succeed, terminal,
4046 "Terminal type %s is not defined",
4047 "Terminal type %s is not defined.\n\
4048 If that is not the actual type of terminal you have,\n\
4049 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4050 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4051 #ifdef TERMINFO
4052 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4053 #else
4054 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4055 #endif
4056 terminal_type);
4059 area = tty->termcap_strings_buffer;
4060 tty->TS_ins_line = tgetstr ("al", address);
4061 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4062 tty->TS_bell = tgetstr ("bl", address);
4063 BackTab (tty) = tgetstr ("bt", address);
4064 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4065 tty->TS_clr_line = tgetstr ("ce", address);
4066 tty->TS_clr_frame = tgetstr ("cl", address);
4067 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4068 AbsPosition (tty) = tgetstr ("cm", address);
4069 CR (tty) = tgetstr ("cr", address);
4070 tty->TS_set_scroll_region = tgetstr ("cs", address);
4071 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4072 RowPosition (tty) = tgetstr ("cv", address);
4073 tty->TS_del_char = tgetstr ("dc", address);
4074 tty->TS_del_multi_chars = tgetstr ("DC", address);
4075 tty->TS_del_line = tgetstr ("dl", address);
4076 tty->TS_del_multi_lines = tgetstr ("DL", address);
4077 tty->TS_delete_mode = tgetstr ("dm", address);
4078 tty->TS_end_delete_mode = tgetstr ("ed", address);
4079 tty->TS_end_insert_mode = tgetstr ("ei", address);
4080 Home (tty) = tgetstr ("ho", address);
4081 tty->TS_ins_char = tgetstr ("ic", address);
4082 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4083 tty->TS_insert_mode = tgetstr ("im", address);
4084 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4085 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4086 tty->TS_keypad_mode = tgetstr ("ks", address);
4087 LastLine (tty) = tgetstr ("ll", address);
4088 Right (tty) = tgetstr ("nd", address);
4089 Down (tty) = tgetstr ("do", address);
4090 if (!Down (tty))
4091 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4092 if (tgetflag ("bs"))
4093 Left (tty) = "\b"; /* Can't possibly be longer! */
4094 else /* (Actually, "bs" is obsolete...) */
4095 Left (tty) = tgetstr ("le", address);
4096 if (!Left (tty))
4097 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4098 tty->TS_pad_char = tgetstr ("pc", address);
4099 tty->TS_repeat = tgetstr ("rp", address);
4100 tty->TS_end_standout_mode = tgetstr ("se", address);
4101 tty->TS_fwd_scroll = tgetstr ("sf", address);
4102 tty->TS_standout_mode = tgetstr ("so", address);
4103 tty->TS_rev_scroll = tgetstr ("sr", address);
4104 tty->Wcm->cm_tab = tgetstr ("ta", address);
4105 tty->TS_end_termcap_modes = tgetstr ("te", address);
4106 tty->TS_termcap_modes = tgetstr ("ti", address);
4107 Up (tty) = tgetstr ("up", address);
4108 tty->TS_visible_bell = tgetstr ("vb", address);
4109 tty->TS_cursor_normal = tgetstr ("ve", address);
4110 tty->TS_cursor_visible = tgetstr ("vs", address);
4111 tty->TS_cursor_invisible = tgetstr ("vi", address);
4112 tty->TS_set_window = tgetstr ("wi", address);
4114 tty->TS_enter_underline_mode = tgetstr ("us", address);
4115 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4116 tty->TS_enter_bold_mode = tgetstr ("md", address);
4117 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4118 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4119 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4120 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4121 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4122 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4124 MultiUp (tty) = tgetstr ("UP", address);
4125 MultiDown (tty) = tgetstr ("DO", address);
4126 MultiLeft (tty) = tgetstr ("LE", address);
4127 MultiRight (tty) = tgetstr ("RI", address);
4129 /* SVr4/ANSI color support. If "op" isn't available, don't support
4130 color because we can't switch back to the default foreground and
4131 background. */
4132 tty->TS_orig_pair = tgetstr ("op", address);
4133 if (tty->TS_orig_pair)
4135 tty->TS_set_foreground = tgetstr ("AF", address);
4136 tty->TS_set_background = tgetstr ("AB", address);
4137 if (!tty->TS_set_foreground)
4139 /* SVr4. */
4140 tty->TS_set_foreground = tgetstr ("Sf", address);
4141 tty->TS_set_background = tgetstr ("Sb", address);
4144 tty->TN_max_colors = tgetnum ("Co");
4146 #ifdef TERMINFO
4147 /* Non-standard support for 24-bit colors. */
4149 const char *fg = tigetstr ("setf24");
4150 const char *bg = tigetstr ("setb24");
4151 if (fg && bg
4152 && fg != (char *) (intptr_t) -1
4153 && bg != (char *) (intptr_t) -1)
4155 tty->TS_set_foreground = fg;
4156 tty->TS_set_background = bg;
4157 tty->TN_max_colors = 16777216;
4160 #endif
4162 tty->TN_no_color_video = tgetnum ("NC");
4163 if (tty->TN_no_color_video == -1)
4164 tty->TN_no_color_video = 0;
4167 tty_default_color_capabilities (tty, 1);
4169 MagicWrap (tty) = tgetflag ("xn");
4170 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4171 the former flag imply the latter. */
4172 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4173 tty->memory_below_frame = tgetflag ("db");
4174 tty->TF_hazeltine = tgetflag ("hz");
4175 tty->must_write_spaces = tgetflag ("in");
4176 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4177 tty->TF_insmode_motion = tgetflag ("mi");
4178 tty->TF_standout_motion = tgetflag ("ms");
4179 tty->TF_underscore = tgetflag ("ul");
4180 tty->TF_teleray = tgetflag ("xt");
4182 #else /* DOS_NT */
4183 #ifdef WINDOWSNT
4185 struct frame *f = XFRAME (selected_frame);
4186 int height, width;
4188 initialize_w32_display (terminal, &width, &height);
4190 FrameRows (tty) = height;
4191 FrameCols (tty) = width;
4192 tty->specified_window = height;
4194 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4195 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4196 tty->char_ins_del_ok = 1;
4197 baud_rate = 19200;
4199 #else /* MSDOS */
4201 int height, width;
4202 if (strcmp (terminal_type, "internal") == 0)
4203 terminal->type = output_msdos_raw;
4204 initialize_msdos_display (terminal);
4206 get_tty_size (fileno (tty->input), &width, &height);
4207 FrameCols (tty) = width;
4208 FrameRows (tty) = height;
4209 tty->char_ins_del_ok = 0;
4210 init_baud_rate (fileno (tty->input));
4212 #endif /* MSDOS */
4213 tty->output = stdout;
4214 tty->input = stdin;
4215 /* The following two are inaccessible from w32console.c. */
4216 terminal->delete_frame_hook = &tty_free_frame_resources;
4217 terminal->delete_terminal_hook = &delete_tty;
4219 tty->name = xstrdup (name);
4220 terminal->name = xstrdup (name);
4221 tty->type = xstrdup (terminal_type);
4223 add_keyboard_wait_descriptor (0);
4225 tty->delete_in_insert_mode = 1;
4227 UseTabs (tty) = 0;
4228 tty->scroll_region_ok = 0;
4230 /* Seems to insert lines when it's not supposed to, messing up the
4231 display. In doing a trace, it didn't seem to be called much, so I
4232 don't think we're losing anything by turning it off. */
4233 tty->line_ins_del_ok = 0;
4235 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4236 #endif /* DOS_NT */
4238 #ifdef HAVE_GPM
4239 terminal->mouse_position_hook = term_mouse_position;
4240 tty->mouse_highlight.mouse_face_window = Qnil;
4241 #endif
4243 terminal->kboard = allocate_kboard (Qnil);
4244 terminal->kboard->reference_count++;
4245 /* Don't let the initial kboard remain current longer than necessary.
4246 That would cause problems if a file loaded on startup tries to
4247 prompt in the mini-buffer. */
4248 if (current_kboard == initial_kboard)
4249 current_kboard = terminal->kboard;
4250 #ifndef DOS_NT
4251 term_get_fkeys (address, terminal->kboard);
4253 /* Get frame size from system, or else from termcap. */
4255 int height, width;
4256 get_tty_size (fileno (tty->input), &width, &height);
4257 FrameCols (tty) = width;
4258 FrameRows (tty) = height;
4261 if (FrameCols (tty) <= 0)
4262 FrameCols (tty) = tgetnum ("co");
4263 if (FrameRows (tty) <= 0)
4264 FrameRows (tty) = tgetnum ("li");
4266 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4267 maybe_fatal (must_succeed, terminal,
4268 "Screen size %dx%d is too small",
4269 "Screen size %dx%d is too small",
4270 FrameCols (tty), FrameRows (tty));
4272 TabWidth (tty) = tgetnum ("tw");
4274 if (!tty->TS_bell)
4275 tty->TS_bell = "\07";
4277 if (!tty->TS_fwd_scroll)
4278 tty->TS_fwd_scroll = Down (tty);
4280 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4282 if (TabWidth (tty) < 0)
4283 TabWidth (tty) = 8;
4285 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4286 and newer termcap doc does not seem to say there is a default.
4287 if (!tty->Wcm->cm_tab)
4288 tty->Wcm->cm_tab = "\t";
4291 /* We don't support standout modes that use `magic cookies', so
4292 turn off any that do. */
4293 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4295 tty->TS_standout_mode = 0;
4296 tty->TS_end_standout_mode = 0;
4298 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4300 tty->TS_enter_underline_mode = 0;
4301 tty->TS_exit_underline_mode = 0;
4304 /* If there's no standout mode, try to use underlining instead. */
4305 if (tty->TS_standout_mode == 0)
4307 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4308 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4311 /* If no `se' string, try using a `me' string instead.
4312 If that fails, we can't use standout mode at all. */
4313 if (tty->TS_end_standout_mode == 0)
4315 char *s = tgetstr ("me", address);
4316 if (s != 0)
4317 tty->TS_end_standout_mode = s;
4318 else
4319 tty->TS_standout_mode = 0;
4322 if (tty->TF_teleray)
4324 tty->Wcm->cm_tab = 0;
4325 /* We can't support standout mode, because it uses magic cookies. */
4326 tty->TS_standout_mode = 0;
4327 /* But that means we cannot rely on ^M to go to column zero! */
4328 CR (tty) = 0;
4329 /* LF can't be trusted either -- can alter hpos. */
4330 /* If move at column 0 thru a line with TS_standout_mode. */
4331 Down (tty) = 0;
4334 tty->specified_window = FrameRows (tty);
4336 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4338 maybe_fatal (must_succeed, terminal,
4339 "Terminal type \"%s\" is not powerful enough to run Emacs",
4340 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4341 It lacks the ability to position the cursor.\n\
4342 If that is not the actual type of terminal you have,\n\
4343 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4344 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4345 # ifdef TERMINFO
4346 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4347 # else /* TERMCAP */
4348 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4349 # endif /* TERMINFO */
4350 terminal_type);
4353 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4354 maybe_fatal (must_succeed, terminal,
4355 "Could not determine the frame size",
4356 "Could not determine the frame size");
4358 tty->delete_in_insert_mode
4359 = tty->TS_delete_mode && tty->TS_insert_mode
4360 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4362 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4364 tty->scroll_region_ok
4365 = (tty->Wcm->cm_abs
4366 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4368 tty->line_ins_del_ok
4369 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4370 && (tty->TS_del_line || tty->TS_del_multi_lines))
4371 || (tty->scroll_region_ok
4372 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4374 tty->char_ins_del_ok
4375 = ((tty->TS_ins_char || tty->TS_insert_mode
4376 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4377 && (tty->TS_del_char || tty->TS_del_multi_chars));
4379 init_baud_rate (fileno (tty->input));
4381 #endif /* not DOS_NT */
4383 /* Init system terminal modes (RAW or CBREAK, etc.). */
4384 init_sys_modes (tty);
4386 return terminal;
4390 static void
4391 vfatal (const char *str, va_list ap)
4393 fprintf (stderr, "emacs: ");
4394 vfprintf (stderr, str, ap);
4395 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4396 fprintf (stderr, "\n");
4397 fflush (stderr);
4398 exit (1);
4402 /* Auxiliary error-handling function for init_tty.
4403 Delete TERMINAL, then call error or fatal with str1 or str2,
4404 respectively, according to whether MUST_SUCCEED is true. */
4406 static void
4407 maybe_fatal (bool must_succeed, struct terminal *terminal,
4408 const char *str1, const char *str2, ...)
4410 va_list ap;
4411 va_start (ap, str2);
4412 if (terminal)
4413 delete_tty (terminal);
4415 if (must_succeed)
4416 vfatal (str2, ap);
4417 else
4418 verror (str1, ap);
4421 void
4422 fatal (const char *str, ...)
4424 va_list ap;
4425 va_start (ap, str);
4426 vfatal (str, ap);
4431 /* Delete the given tty terminal, closing all frames on it. */
4433 static void
4434 delete_tty (struct terminal *terminal)
4436 struct tty_display_info *tty;
4438 /* Protect against recursive calls. delete_frame in
4439 delete_terminal calls us back when it deletes our last frame. */
4440 if (!terminal->name)
4441 return;
4443 eassert (terminal->type == output_termcap);
4445 tty = terminal->display_info.tty;
4447 if (tty == tty_list)
4448 tty_list = tty->next;
4449 else
4451 struct tty_display_info *p;
4452 for (p = tty_list; p && p->next != tty; p = p->next)
4455 if (! p)
4456 /* This should not happen. */
4457 emacs_abort ();
4459 p->next = tty->next;
4460 tty->next = 0;
4463 /* reset_sys_modes needs a valid device, so this call needs to be
4464 before delete_terminal. */
4465 reset_sys_modes (tty);
4467 delete_terminal (terminal);
4469 xfree (tty->name);
4470 xfree (tty->type);
4472 if (tty->input)
4474 delete_keyboard_wait_descriptor (fileno (tty->input));
4475 if (tty->input != stdin)
4476 fclose (tty->input);
4478 if (tty->output && tty->output != stdout && tty->output != tty->input)
4479 fclose (tty->output);
4480 if (tty->termscript)
4481 fclose (tty->termscript);
4483 xfree (tty->old_tty);
4484 xfree (tty->Wcm);
4485 xfree (tty);
4488 void
4489 syms_of_term (void)
4491 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4492 doc: /* Non-nil means the system uses terminfo rather than termcap.
4493 This variable can be used by terminal emulator packages. */);
4494 #ifdef TERMINFO
4495 system_uses_terminfo = 1;
4496 #else
4497 system_uses_terminfo = 0;
4498 #endif
4500 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4501 doc: /* Functions run after suspending a tty.
4502 The functions are run with one argument, the terminal object to be suspended.
4503 See `suspend-tty'. */);
4504 Vsuspend_tty_functions = Qnil;
4507 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4508 doc: /* Functions run after resuming a tty.
4509 The functions are run with one argument, the terminal object that was revived.
4510 See `resume-tty'. */);
4511 Vresume_tty_functions = Qnil;
4513 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4514 doc: /* Non-nil means to make the cursor very visible.
4515 This only has an effect when running in a text terminal.
4516 What means \"very visible\" is up to your terminal. It may make the cursor
4517 bigger, or it may make it blink, or it may do nothing at all. */);
4518 visible_cursor = 1;
4520 defsubr (&Stty_display_color_p);
4521 defsubr (&Stty_display_color_cells);
4522 defsubr (&Stty_no_underline);
4523 defsubr (&Stty_type);
4524 defsubr (&Scontrolling_tty_p);
4525 defsubr (&Stty_top_frame);
4526 defsubr (&Ssuspend_tty);
4527 defsubr (&Sresume_tty);
4528 #ifdef HAVE_GPM
4529 defsubr (&Sgpm_mouse_start);
4530 defsubr (&Sgpm_mouse_stop);
4531 #endif /* HAVE_GPM */
4533 #ifndef DOS_NT
4534 default_orig_pair = NULL;
4535 default_set_foreground = NULL;
4536 default_set_background = NULL;
4537 #endif /* !DOS_NT */
4539 encode_terminal_src = NULL;
4540 encode_terminal_dst = NULL;
4542 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4543 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4545 #ifndef MSDOS
4546 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4547 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4548 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4549 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4550 DEFSYM (Qtty_menu_select, "tty-menu-select");
4551 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4552 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4553 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4554 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4555 #endif