Merge from trunk.
[emacs.git] / src / term.c
blob116a2e6bba1f378f44248da4bcf72e3d86f8e99a
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2013 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #include "systty.h"
48 #include "intervals.h"
49 #ifdef MSDOS
50 #include "msdos.h"
51 static int been_here = -1;
52 #endif
54 #include "cm.h"
55 #ifdef HAVE_X_WINDOWS
56 #include "xterm.h"
57 #endif
59 #include "menu.h"
61 /* The name of the default console device. */
62 #ifdef WINDOWSNT
63 #define DEV_TTY "CONOUT$"
64 #include "w32term.h"
65 #else
66 #define DEV_TTY "/dev/tty"
67 #endif
69 static void tty_set_scroll_region (struct frame *f, int start, int stop);
70 static void turn_on_face (struct frame *, int face_id);
71 static void turn_off_face (struct frame *, int face_id);
72 static void tty_turn_off_highlight (struct tty_display_info *);
73 static void tty_show_cursor (struct tty_display_info *);
74 static void tty_hide_cursor (struct tty_display_info *);
75 static void tty_background_highlight (struct tty_display_info *tty);
76 static struct terminal *get_tty_terminal (Lisp_Object, bool);
77 static void clear_tty_hooks (struct terminal *terminal);
78 static void set_tty_hooks (struct terminal *terminal);
79 static void dissociate_if_controlling_tty (int fd);
80 static void delete_tty (struct terminal *);
81 static _Noreturn void maybe_fatal (bool, struct terminal *,
82 const char *, const char *, ...)
83 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
84 static _Noreturn void vfatal (const char *str, va_list ap)
85 ATTRIBUTE_FORMAT_PRINTF (1, 0);
88 #define OUTPUT(tty, a) \
89 emacs_tputs ((tty), a, \
90 FRAME_LINES (XFRAME (selected_frame)) - curY (tty), \
91 cmputc)
93 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
94 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
96 #define OUTPUT_IF(tty, a) \
97 do { \
98 if (a) \
99 OUTPUT (tty, a); \
100 } while (0)
102 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
104 /* Display space properties */
106 /* Chain of all tty device parameters. */
107 struct tty_display_info *tty_list;
109 /* Meaning of bits in no_color_video. Each bit set means that the
110 corresponding attribute cannot be combined with colors. */
112 enum no_color_bit
114 NC_STANDOUT = 1 << 0,
115 NC_UNDERLINE = 1 << 1,
116 NC_REVERSE = 1 << 2,
117 NC_ITALIC = 1 << 3,
118 NC_DIM = 1 << 4,
119 NC_BOLD = 1 << 5,
120 NC_INVIS = 1 << 6,
121 NC_PROTECT = 1 << 7
124 /* internal state */
126 /* The largest frame width in any call to calculate_costs. */
128 static int max_frame_cols;
132 #ifdef HAVE_GPM
133 #include <sys/fcntl.h>
135 /* The device for which we have enabled gpm support (or NULL). */
136 struct tty_display_info *gpm_tty = NULL;
138 /* Last recorded mouse coordinates. */
139 static int last_mouse_x, last_mouse_y;
140 #endif /* HAVE_GPM */
142 /* Ring the bell on a tty. */
144 static void
145 tty_ring_bell (struct frame *f)
147 struct tty_display_info *tty = FRAME_TTY (f);
149 if (tty->output)
151 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
152 ? tty->TS_visible_bell
153 : tty->TS_bell));
154 fflush (tty->output);
158 /* Set up termcap modes for Emacs. */
160 static void
161 tty_set_terminal_modes (struct terminal *terminal)
163 struct tty_display_info *tty = terminal->display_info.tty;
165 if (tty->output)
167 if (tty->TS_termcap_modes)
168 OUTPUT (tty, tty->TS_termcap_modes);
169 else
171 /* Output enough newlines to scroll all the old screen contents
172 off the screen, so it won't be overwritten and lost. */
173 int i;
174 current_tty = tty;
175 for (i = 0; i < FRAME_LINES (XFRAME (selected_frame)); i++)
176 cmputc ('\n');
179 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
180 OUTPUT_IF (tty, tty->TS_keypad_mode);
181 losecursor (tty);
182 fflush (tty->output);
186 /* Reset termcap modes before exiting Emacs. */
188 static void
189 tty_reset_terminal_modes (struct terminal *terminal)
191 struct tty_display_info *tty = terminal->display_info.tty;
193 if (tty->output)
195 tty_turn_off_highlight (tty);
196 tty_turn_off_insert (tty);
197 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
198 OUTPUT_IF (tty, tty->TS_cursor_normal);
199 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
200 OUTPUT_IF (tty, tty->TS_orig_pair);
201 /* Output raw CR so kernel can track the cursor hpos. */
202 current_tty = tty;
203 cmputc ('\r');
204 fflush (tty->output);
208 /* Flag the end of a display update on a termcap terminal. */
210 static void
211 tty_update_end (struct frame *f)
213 struct tty_display_info *tty = FRAME_TTY (f);
215 if (!XWINDOW (selected_window)->cursor_off_p)
216 tty_show_cursor (tty);
217 tty_turn_off_insert (tty);
218 tty_background_highlight (tty);
221 /* The implementation of set_terminal_window for termcap frames. */
223 static void
224 tty_set_terminal_window (struct frame *f, int size)
226 struct tty_display_info *tty = FRAME_TTY (f);
228 tty->specified_window = size ? size : FRAME_LINES (f);
229 if (FRAME_SCROLL_REGION_OK (f))
230 tty_set_scroll_region (f, 0, tty->specified_window);
233 static void
234 tty_set_scroll_region (struct frame *f, int start, int stop)
236 char *buf;
237 struct tty_display_info *tty = FRAME_TTY (f);
239 if (tty->TS_set_scroll_region)
240 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
241 else if (tty->TS_set_scroll_region_1)
242 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
243 FRAME_LINES (f), start,
244 FRAME_LINES (f) - stop,
245 FRAME_LINES (f));
246 else
247 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
249 OUTPUT (tty, buf);
250 xfree (buf);
251 losecursor (tty);
255 static void
256 tty_turn_on_insert (struct tty_display_info *tty)
258 if (!tty->insert_mode)
259 OUTPUT (tty, tty->TS_insert_mode);
260 tty->insert_mode = 1;
263 void
264 tty_turn_off_insert (struct tty_display_info *tty)
266 if (tty->insert_mode)
267 OUTPUT (tty, tty->TS_end_insert_mode);
268 tty->insert_mode = 0;
271 /* Handle highlighting. */
273 static void
274 tty_turn_off_highlight (struct tty_display_info *tty)
276 if (tty->standout_mode)
277 OUTPUT_IF (tty, tty->TS_end_standout_mode);
278 tty->standout_mode = 0;
281 static void
282 tty_turn_on_highlight (struct tty_display_info *tty)
284 if (!tty->standout_mode)
285 OUTPUT_IF (tty, tty->TS_standout_mode);
286 tty->standout_mode = 1;
289 static void
290 tty_toggle_highlight (struct tty_display_info *tty)
292 if (tty->standout_mode)
293 tty_turn_off_highlight (tty);
294 else
295 tty_turn_on_highlight (tty);
299 /* Make cursor invisible. */
301 static void
302 tty_hide_cursor (struct tty_display_info *tty)
304 if (tty->cursor_hidden == 0)
306 tty->cursor_hidden = 1;
307 #ifdef WINDOWSNT
308 w32con_hide_cursor ();
309 #else
310 OUTPUT_IF (tty, tty->TS_cursor_invisible);
311 #endif
316 /* Ensure that cursor is visible. */
318 static void
319 tty_show_cursor (struct tty_display_info *tty)
321 if (tty->cursor_hidden)
323 tty->cursor_hidden = 0;
324 #ifdef WINDOWSNT
325 w32con_show_cursor ();
326 #else
327 OUTPUT_IF (tty, tty->TS_cursor_normal);
328 if (visible_cursor)
329 OUTPUT_IF (tty, tty->TS_cursor_visible);
330 #endif
335 /* Set standout mode to the state it should be in for
336 empty space inside windows. What this is,
337 depends on the user option inverse-video. */
339 static void
340 tty_background_highlight (struct tty_display_info *tty)
342 if (inverse_video)
343 tty_turn_on_highlight (tty);
344 else
345 tty_turn_off_highlight (tty);
348 /* Set standout mode to the mode specified for the text to be output. */
350 static void
351 tty_highlight_if_desired (struct tty_display_info *tty)
353 if (inverse_video)
354 tty_turn_on_highlight (tty);
355 else
356 tty_turn_off_highlight (tty);
360 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
361 frame-relative coordinates. */
363 static void
364 tty_cursor_to (struct frame *f, int vpos, int hpos)
366 struct tty_display_info *tty = FRAME_TTY (f);
368 /* Detect the case where we are called from reset_sys_modes
369 and the costs have never been calculated. Do nothing. */
370 if (! tty->costs_set)
371 return;
373 if (curY (tty) == vpos
374 && curX (tty) == hpos)
375 return;
376 if (!tty->TF_standout_motion)
377 tty_background_highlight (tty);
378 if (!tty->TF_insmode_motion)
379 tty_turn_off_insert (tty);
380 cmgoto (tty, vpos, hpos);
383 /* Similar but don't take any account of the wasted characters. */
385 static void
386 tty_raw_cursor_to (struct frame *f, int row, int col)
388 struct tty_display_info *tty = FRAME_TTY (f);
390 if (curY (tty) == row
391 && curX (tty) == col)
392 return;
393 if (!tty->TF_standout_motion)
394 tty_background_highlight (tty);
395 if (!tty->TF_insmode_motion)
396 tty_turn_off_insert (tty);
397 cmgoto (tty, row, col);
400 /* Erase operations */
402 /* Clear from cursor to end of frame on a termcap device. */
404 static void
405 tty_clear_to_end (struct frame *f)
407 register int i;
408 struct tty_display_info *tty = FRAME_TTY (f);
410 if (tty->TS_clr_to_bottom)
412 tty_background_highlight (tty);
413 OUTPUT (tty, tty->TS_clr_to_bottom);
415 else
417 for (i = curY (tty); i < FRAME_LINES (f); i++)
419 cursor_to (f, i, 0);
420 clear_end_of_line (f, FRAME_COLS (f));
425 /* Clear an entire termcap frame. */
427 static void
428 tty_clear_frame (struct frame *f)
430 struct tty_display_info *tty = FRAME_TTY (f);
432 if (tty->TS_clr_frame)
434 tty_background_highlight (tty);
435 OUTPUT (tty, tty->TS_clr_frame);
436 cmat (tty, 0, 0);
438 else
440 cursor_to (f, 0, 0);
441 clear_to_end (f);
445 /* An implementation of clear_end_of_line for termcap frames.
447 Note that the cursor may be moved, on terminals lacking a `ce' string. */
449 static void
450 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
452 register int i;
453 struct tty_display_info *tty = FRAME_TTY (f);
455 /* Detect the case where we are called from reset_sys_modes
456 and the costs have never been calculated. Do nothing. */
457 if (! tty->costs_set)
458 return;
460 if (curX (tty) >= first_unused_hpos)
461 return;
462 tty_background_highlight (tty);
463 if (tty->TS_clr_line)
465 OUTPUT1 (tty, tty->TS_clr_line);
467 else
468 { /* have to do it the hard way */
469 tty_turn_off_insert (tty);
471 /* Do not write in last row last col with Auto-wrap on. */
472 if (AutoWrap (tty)
473 && curY (tty) == FrameRows (tty) - 1
474 && first_unused_hpos == FrameCols (tty))
475 first_unused_hpos--;
477 for (i = curX (tty); i < first_unused_hpos; i++)
479 if (tty->termscript)
480 fputc (' ', tty->termscript);
481 fputc (' ', tty->output);
483 cmplus (tty, first_unused_hpos - curX (tty));
487 /* Buffers to store the source and result of code conversion for terminal. */
488 static unsigned char *encode_terminal_src;
489 static unsigned char *encode_terminal_dst;
490 /* Allocated sizes of the above buffers. */
491 static ptrdiff_t encode_terminal_src_size;
492 static ptrdiff_t encode_terminal_dst_size;
494 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
495 Set CODING->produced to the byte-length of the resulting byte
496 sequence, and return a pointer to that byte sequence. */
498 unsigned char *
499 encode_terminal_code (struct glyph *src, int src_len, struct coding_system *coding)
501 struct glyph *src_end = src + src_len;
502 unsigned char *buf;
503 ptrdiff_t nchars, nbytes, required;
504 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
505 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
506 Lisp_Object charset_list;
508 /* Allocate sufficient size of buffer to store all characters in
509 multibyte-form. But, it may be enlarged on demand if
510 Vglyph_table contains a string or a composite glyph is
511 encountered. */
512 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
513 memory_full (SIZE_MAX);
514 required = src_len;
515 required *= MAX_MULTIBYTE_LENGTH;
516 if (encode_terminal_src_size < required)
518 encode_terminal_src = xrealloc (encode_terminal_src, required);
519 encode_terminal_src_size = required;
522 charset_list = coding_charset_list (coding);
524 buf = encode_terminal_src;
525 nchars = 0;
526 while (src < src_end)
528 if (src->type == COMPOSITE_GLYPH)
530 struct composition *cmp IF_LINT (= NULL);
531 Lisp_Object gstring IF_LINT (= Qnil);
532 int i;
534 nbytes = buf - encode_terminal_src;
535 if (src->u.cmp.automatic)
537 gstring = composition_gstring_from_id (src->u.cmp.id);
538 required = src->slice.cmp.to - src->slice.cmp.from + 1;
540 else
542 cmp = composition_table[src->u.cmp.id];
543 required = cmp->glyph_len;
544 required *= MAX_MULTIBYTE_LENGTH;
547 if (encode_terminal_src_size - nbytes < required)
549 encode_terminal_src =
550 xpalloc (encode_terminal_src, &encode_terminal_src_size,
551 required - (encode_terminal_src_size - nbytes),
552 -1, 1);
553 buf = encode_terminal_src + nbytes;
556 if (src->u.cmp.automatic)
557 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
559 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
560 int c = LGLYPH_CHAR (g);
562 if (! char_charset (c, charset_list, NULL))
563 c = '?';
564 buf += CHAR_STRING (c, buf);
565 nchars++;
567 else
568 for (i = 0; i < cmp->glyph_len; i++)
570 int c = COMPOSITION_GLYPH (cmp, i);
572 /* TAB in a composition means display glyphs with
573 padding space on the left or right. */
574 if (c == '\t')
575 continue;
576 if (char_charset (c, charset_list, NULL))
578 if (CHAR_WIDTH (c) == 0
579 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
580 /* Should be left-padded */
582 buf += CHAR_STRING (' ', buf);
583 nchars++;
586 else
587 c = '?';
588 buf += CHAR_STRING (c, buf);
589 nchars++;
592 /* We must skip glyphs to be padded for a wide character. */
593 else if (! CHAR_GLYPH_PADDING_P (*src))
595 GLYPH g;
596 int c IF_LINT (= 0);
597 Lisp_Object string;
599 string = Qnil;
600 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
602 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
604 /* This glyph doesn't have an entry in Vglyph_table. */
605 c = src->u.ch;
607 else
609 /* This glyph has an entry in Vglyph_table,
610 so process any alias before testing for simpleness. */
611 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
613 if (GLYPH_SIMPLE_P (tbase, tlen, g))
614 /* We set the multi-byte form of a character in G
615 (that should be an ASCII character) at WORKBUF. */
616 c = GLYPH_CHAR (g);
617 else
618 /* We have a string in Vglyph_table. */
619 string = tbase[GLYPH_CHAR (g)];
622 if (NILP (string))
624 nbytes = buf - encode_terminal_src;
625 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
627 encode_terminal_src =
628 xpalloc (encode_terminal_src, &encode_terminal_src_size,
629 MAX_MULTIBYTE_LENGTH, -1, 1);
630 buf = encode_terminal_src + nbytes;
632 if (CHAR_BYTE8_P (c)
633 || char_charset (c, charset_list, NULL))
635 /* Store the multibyte form of C at BUF. */
636 buf += CHAR_STRING (c, buf);
637 nchars++;
639 else
641 /* C is not encodable. */
642 *buf++ = '?';
643 nchars++;
644 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
646 *buf++ = '?';
647 nchars++;
648 src++;
652 else
654 if (! STRING_MULTIBYTE (string))
655 string = string_to_multibyte (string);
656 nbytes = buf - encode_terminal_src;
657 if (encode_terminal_src_size - nbytes < SBYTES (string))
659 encode_terminal_src =
660 xpalloc (encode_terminal_src, &encode_terminal_src_size,
661 (SBYTES (string)
662 - (encode_terminal_src_size - nbytes)),
663 -1, 1);
664 buf = encode_terminal_src + nbytes;
666 memcpy (buf, SDATA (string), SBYTES (string));
667 buf += SBYTES (string);
668 nchars += SCHARS (string);
671 src++;
674 if (nchars == 0)
676 coding->produced = 0;
677 return NULL;
680 nbytes = buf - encode_terminal_src;
681 coding->source = encode_terminal_src;
682 if (encode_terminal_dst_size == 0)
684 encode_terminal_dst = xrealloc (encode_terminal_dst,
685 encode_terminal_src_size);
686 encode_terminal_dst_size = encode_terminal_src_size;
688 coding->destination = encode_terminal_dst;
689 coding->dst_bytes = encode_terminal_dst_size;
690 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
691 /* coding->destination may have been reallocated. */
692 encode_terminal_dst = coding->destination;
693 encode_terminal_dst_size = coding->dst_bytes;
695 return (encode_terminal_dst);
700 /* An implementation of write_glyphs for termcap frames. */
702 static void
703 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
705 unsigned char *conversion_buffer;
706 struct coding_system *coding;
707 int n, stringlen;
709 struct tty_display_info *tty = FRAME_TTY (f);
711 tty_turn_off_insert (tty);
712 tty_hide_cursor (tty);
714 /* Don't dare write in last column of bottom line, if Auto-Wrap,
715 since that would scroll the whole frame on some terminals. */
717 if (AutoWrap (tty)
718 && curY (tty) + 1 == FRAME_LINES (f)
719 && (curX (tty) + len) == FRAME_COLS (f))
720 len --;
721 if (len <= 0)
722 return;
724 cmplus (tty, len);
726 /* If terminal_coding does any conversion, use it, otherwise use
727 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
728 because it always return 1 if the member src_multibyte is 1. */
729 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
730 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
731 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
732 the tail. */
733 coding->mode &= ~CODING_MODE_LAST_BLOCK;
735 for (stringlen = len; stringlen != 0; stringlen -= n)
737 /* Identify a run of glyphs with the same face. */
738 int face_id = string->face_id;
740 for (n = 1; n < stringlen; ++n)
741 if (string[n].face_id != face_id)
742 break;
744 /* Turn appearance modes of the face of the run on. */
745 tty_highlight_if_desired (tty);
746 turn_on_face (f, face_id);
748 if (n == stringlen)
749 /* This is the last run. */
750 coding->mode |= CODING_MODE_LAST_BLOCK;
751 conversion_buffer = encode_terminal_code (string, n, coding);
752 if (coding->produced > 0)
754 block_input ();
755 fwrite (conversion_buffer, 1, coding->produced, tty->output);
756 if (ferror (tty->output))
757 clearerr (tty->output);
758 if (tty->termscript)
759 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
760 unblock_input ();
762 string += n;
764 /* Turn appearance modes off. */
765 turn_off_face (f, face_id);
766 tty_turn_off_highlight (tty);
769 cmcheckmagic (tty);
772 #ifdef HAVE_GPM /* Only used by GPM code. */
774 static void
775 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
776 register int len, register int face_id)
778 unsigned char *conversion_buffer;
779 struct coding_system *coding;
781 struct tty_display_info *tty = FRAME_TTY (f);
783 tty_turn_off_insert (tty);
784 tty_hide_cursor (tty);
786 /* Don't dare write in last column of bottom line, if Auto-Wrap,
787 since that would scroll the whole frame on some terminals. */
789 if (AutoWrap (tty)
790 && curY (tty) + 1 == FRAME_LINES (f)
791 && (curX (tty) + len) == FRAME_COLS (f))
792 len --;
793 if (len <= 0)
794 return;
796 cmplus (tty, len);
798 /* If terminal_coding does any conversion, use it, otherwise use
799 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
800 because it always return 1 if the member src_multibyte is 1. */
801 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
802 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
803 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
804 the tail. */
805 coding->mode &= ~CODING_MODE_LAST_BLOCK;
807 /* Turn appearance modes of the face. */
808 tty_highlight_if_desired (tty);
809 turn_on_face (f, face_id);
811 coding->mode |= CODING_MODE_LAST_BLOCK;
812 conversion_buffer = encode_terminal_code (string, len, coding);
813 if (coding->produced > 0)
815 block_input ();
816 fwrite (conversion_buffer, 1, coding->produced, tty->output);
817 if (ferror (tty->output))
818 clearerr (tty->output);
819 if (tty->termscript)
820 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
821 unblock_input ();
824 /* Turn appearance modes off. */
825 turn_off_face (f, face_id);
826 tty_turn_off_highlight (tty);
828 cmcheckmagic (tty);
830 #endif
832 /* An implementation of insert_glyphs for termcap frames. */
834 static void
835 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
837 char *buf;
838 struct glyph *glyph = NULL;
839 unsigned char *conversion_buffer;
840 unsigned char space[1];
841 struct coding_system *coding;
843 struct tty_display_info *tty = FRAME_TTY (f);
845 if (tty->TS_ins_multi_chars)
847 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
848 OUTPUT1 (tty, buf);
849 xfree (buf);
850 if (start)
851 write_glyphs (f, start, len);
852 return;
855 tty_turn_on_insert (tty);
856 cmplus (tty, len);
858 if (! start)
859 space[0] = SPACEGLYPH;
861 /* If terminal_coding does any conversion, use it, otherwise use
862 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
863 because it always return 1 if the member src_multibyte is 1. */
864 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
865 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
866 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
867 the tail. */
868 coding->mode &= ~CODING_MODE_LAST_BLOCK;
870 while (len-- > 0)
872 OUTPUT1_IF (tty, tty->TS_ins_char);
873 if (!start)
875 conversion_buffer = space;
876 coding->produced = 1;
878 else
880 tty_highlight_if_desired (tty);
881 turn_on_face (f, start->face_id);
882 glyph = start;
883 ++start;
884 /* We must open sufficient space for a character which
885 occupies more than one column. */
886 while (len && CHAR_GLYPH_PADDING_P (*start))
888 OUTPUT1_IF (tty, tty->TS_ins_char);
889 start++, len--;
892 if (len <= 0)
893 /* This is the last glyph. */
894 coding->mode |= CODING_MODE_LAST_BLOCK;
896 conversion_buffer = encode_terminal_code (glyph, 1, coding);
899 if (coding->produced > 0)
901 block_input ();
902 fwrite (conversion_buffer, 1, coding->produced, tty->output);
903 if (ferror (tty->output))
904 clearerr (tty->output);
905 if (tty->termscript)
906 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
907 unblock_input ();
910 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
911 if (start)
913 turn_off_face (f, glyph->face_id);
914 tty_turn_off_highlight (tty);
918 cmcheckmagic (tty);
921 /* An implementation of delete_glyphs for termcap frames. */
923 static void
924 tty_delete_glyphs (struct frame *f, int n)
926 char *buf;
927 register int i;
929 struct tty_display_info *tty = FRAME_TTY (f);
931 if (tty->delete_in_insert_mode)
933 tty_turn_on_insert (tty);
935 else
937 tty_turn_off_insert (tty);
938 OUTPUT_IF (tty, tty->TS_delete_mode);
941 if (tty->TS_del_multi_chars)
943 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
944 OUTPUT1 (tty, buf);
945 xfree (buf);
947 else
948 for (i = 0; i < n; i++)
949 OUTPUT1 (tty, tty->TS_del_char);
950 if (!tty->delete_in_insert_mode)
951 OUTPUT_IF (tty, tty->TS_end_delete_mode);
954 /* An implementation of ins_del_lines for termcap frames. */
956 static void
957 tty_ins_del_lines (struct frame *f, int vpos, int n)
959 struct tty_display_info *tty = FRAME_TTY (f);
960 const char *multi =
961 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
962 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
963 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
965 int i = eabs (n);
966 char *buf;
968 /* If the lines below the insertion are being pushed
969 into the end of the window, this is the same as clearing;
970 and we know the lines are already clear, since the matching
971 deletion has already been done. So can ignore this. */
972 /* If the lines below the deletion are blank lines coming
973 out of the end of the window, don't bother,
974 as there will be a matching inslines later that will flush them. */
975 if (FRAME_SCROLL_REGION_OK (f)
976 && vpos + i >= tty->specified_window)
977 return;
978 if (!FRAME_MEMORY_BELOW_FRAME (f)
979 && vpos + i >= FRAME_LINES (f))
980 return;
982 if (multi)
984 raw_cursor_to (f, vpos, 0);
985 tty_background_highlight (tty);
986 buf = tparam (multi, 0, 0, i, 0, 0, 0);
987 OUTPUT (tty, buf);
988 xfree (buf);
990 else if (single)
992 raw_cursor_to (f, vpos, 0);
993 tty_background_highlight (tty);
994 while (--i >= 0)
995 OUTPUT (tty, single);
996 if (tty->TF_teleray)
997 curX (tty) = 0;
999 else
1001 tty_set_scroll_region (f, vpos, tty->specified_window);
1002 if (n < 0)
1003 raw_cursor_to (f, tty->specified_window - 1, 0);
1004 else
1005 raw_cursor_to (f, vpos, 0);
1006 tty_background_highlight (tty);
1007 while (--i >= 0)
1008 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1009 tty_set_scroll_region (f, 0, tty->specified_window);
1012 if (!FRAME_SCROLL_REGION_OK (f)
1013 && FRAME_MEMORY_BELOW_FRAME (f)
1014 && n < 0)
1016 cursor_to (f, FRAME_LINES (f) + n, 0);
1017 clear_to_end (f);
1021 /* Compute cost of sending "str", in characters,
1022 not counting any line-dependent padding. */
1025 string_cost (const char *str)
1027 cost = 0;
1028 if (str)
1029 tputs (str, 0, evalcost);
1030 return cost;
1033 /* Compute cost of sending "str", in characters,
1034 counting any line-dependent padding at one line. */
1036 static int
1037 string_cost_one_line (const char *str)
1039 cost = 0;
1040 if (str)
1041 tputs (str, 1, evalcost);
1042 return cost;
1045 /* Compute per line amount of line-dependent padding,
1046 in tenths of characters. */
1049 per_line_cost (const char *str)
1051 cost = 0;
1052 if (str)
1053 tputs (str, 0, evalcost);
1054 cost = - cost;
1055 if (str)
1056 tputs (str, 10, evalcost);
1057 return cost;
1060 /* char_ins_del_cost[n] is cost of inserting N characters.
1061 char_ins_del_cost[-n] is cost of deleting N characters.
1062 The length of this vector is based on max_frame_cols. */
1064 int *char_ins_del_vector;
1066 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1068 /* ARGSUSED */
1069 static void
1070 calculate_ins_del_char_costs (struct frame *f)
1072 struct tty_display_info *tty = FRAME_TTY (f);
1073 int ins_startup_cost, del_startup_cost;
1074 int ins_cost_per_char, del_cost_per_char;
1075 register int i;
1076 register int *p;
1078 if (tty->TS_ins_multi_chars)
1080 ins_cost_per_char = 0;
1081 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1083 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1084 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1086 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1087 + string_cost (tty->TS_end_insert_mode))) / 100;
1088 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1089 + string_cost_one_line (tty->TS_pad_inserted_char));
1091 else
1093 ins_startup_cost = 9999;
1094 ins_cost_per_char = 0;
1097 if (tty->TS_del_multi_chars)
1099 del_cost_per_char = 0;
1100 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1102 else if (tty->TS_del_char)
1104 del_startup_cost = (string_cost (tty->TS_delete_mode)
1105 + string_cost (tty->TS_end_delete_mode));
1106 if (tty->delete_in_insert_mode)
1107 del_startup_cost /= 2;
1108 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1110 else
1112 del_startup_cost = 9999;
1113 del_cost_per_char = 0;
1116 /* Delete costs are at negative offsets */
1117 p = &char_ins_del_cost (f)[0];
1118 for (i = FRAME_COLS (f); --i >= 0;)
1119 *--p = (del_startup_cost += del_cost_per_char);
1121 /* Doing nothing is free */
1122 p = &char_ins_del_cost (f)[0];
1123 *p++ = 0;
1125 /* Insert costs are at positive offsets */
1126 for (i = FRAME_COLS (f); --i >= 0;)
1127 *p++ = (ins_startup_cost += ins_cost_per_char);
1130 void
1131 calculate_costs (struct frame *frame)
1133 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1135 if (FRAME_TERMCAP_P (frame))
1137 struct tty_display_info *tty = FRAME_TTY (frame);
1138 register const char *f = (tty->TS_set_scroll_region
1139 ? tty->TS_set_scroll_region
1140 : tty->TS_set_scroll_region_1);
1142 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1144 tty->costs_set = 1;
1146 /* These variables are only used for terminal stuff. They are
1147 allocated once for the terminal frame of X-windows emacs, but not
1148 used afterwards.
1150 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1151 X turns off char_ins_del_ok. */
1153 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1154 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1155 < max_frame_cols)
1156 memory_full (SIZE_MAX);
1158 char_ins_del_vector =
1159 xrealloc (char_ins_del_vector,
1160 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1162 memset (char_ins_del_vector, 0,
1163 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1166 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1167 do_line_insertion_deletion_costs (frame,
1168 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1169 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1170 f, f, 1);
1171 else
1172 do_line_insertion_deletion_costs (frame,
1173 tty->TS_ins_line, tty->TS_ins_multi_lines,
1174 tty->TS_del_line, tty->TS_del_multi_lines,
1175 0, 0, 1);
1177 calculate_ins_del_char_costs (frame);
1179 /* Don't use TS_repeat if its padding is worse than sending the chars */
1180 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1181 tty->RPov = string_cost (tty->TS_repeat);
1182 else
1183 tty->RPov = FRAME_COLS (frame) * 2;
1185 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1189 struct fkey_table {
1190 const char *cap, *name;
1193 /* Termcap capability names that correspond directly to X keysyms.
1194 Some of these (marked "terminfo") aren't supplied by old-style
1195 (Berkeley) termcap entries. They're listed in X keysym order;
1196 except we put the keypad keys first, so that if they clash with
1197 other keys (as on the IBM PC keyboard) they get overridden.
1200 static const struct fkey_table keys[] =
1202 {"kh", "home"}, /* termcap */
1203 {"kl", "left"}, /* termcap */
1204 {"ku", "up"}, /* termcap */
1205 {"kr", "right"}, /* termcap */
1206 {"kd", "down"}, /* termcap */
1207 {"%8", "prior"}, /* terminfo */
1208 {"%5", "next"}, /* terminfo */
1209 {"@7", "end"}, /* terminfo */
1210 {"@1", "begin"}, /* terminfo */
1211 {"*6", "select"}, /* terminfo */
1212 {"%9", "print"}, /* terminfo */
1213 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1215 * "insert" --- see below
1217 {"&8", "undo"}, /* terminfo */
1218 {"%0", "redo"}, /* terminfo */
1219 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1220 {"@0", "find"}, /* terminfo */
1221 {"@2", "cancel"}, /* terminfo */
1222 {"%1", "help"}, /* terminfo */
1224 * "break" goes here, but can't be reliably intercepted with termcap
1226 {"&4", "reset"}, /* terminfo --- actually `restart' */
1228 * "system" and "user" --- no termcaps
1230 {"kE", "clearline"}, /* terminfo */
1231 {"kA", "insertline"}, /* terminfo */
1232 {"kL", "deleteline"}, /* terminfo */
1233 {"kI", "insertchar"}, /* terminfo */
1234 {"kD", "deletechar"}, /* terminfo */
1235 {"kB", "backtab"}, /* terminfo */
1237 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1239 {"@8", "kp-enter"}, /* terminfo */
1241 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1242 * "kp-multiply", "kp-add", "kp-separator",
1243 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1244 * --- no termcaps for any of these.
1246 {"K4", "kp-1"}, /* terminfo */
1248 * "kp-2" --- no termcap
1250 {"K5", "kp-3"}, /* terminfo */
1252 * "kp-4" --- no termcap
1254 {"K2", "kp-5"}, /* terminfo */
1256 * "kp-6" --- no termcap
1258 {"K1", "kp-7"}, /* terminfo */
1260 * "kp-8" --- no termcap
1262 {"K3", "kp-9"}, /* terminfo */
1264 * "kp-equal" --- no termcap
1266 {"k1", "f1"},
1267 {"k2", "f2"},
1268 {"k3", "f3"},
1269 {"k4", "f4"},
1270 {"k5", "f5"},
1271 {"k6", "f6"},
1272 {"k7", "f7"},
1273 {"k8", "f8"},
1274 {"k9", "f9"},
1276 {"&0", "S-cancel"}, /*shifted cancel key*/
1277 {"&9", "S-begin"}, /*shifted begin key*/
1278 {"*0", "S-find"}, /*shifted find key*/
1279 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1280 {"*4", "S-delete"}, /*shifted delete-character key*/
1281 {"*7", "S-end"}, /*shifted end key*/
1282 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1283 {"#1", "S-help"}, /*shifted help key*/
1284 {"#2", "S-home"}, /*shifted home key*/
1285 {"#3", "S-insert"}, /*shifted insert-character key*/
1286 {"#4", "S-left"}, /*shifted left-arrow key*/
1287 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1288 {"%c", "S-next"}, /*shifted next key*/
1289 {"%e", "S-prior"}, /*shifted previous key*/
1290 {"%f", "S-print"}, /*shifted print key*/
1291 {"%g", "S-redo"}, /*shifted redo key*/
1292 {"%i", "S-right"}, /*shifted right-arrow key*/
1293 {"!3", "S-undo"} /*shifted undo key*/
1296 #ifndef DOS_NT
1297 static char **term_get_fkeys_address;
1298 static KBOARD *term_get_fkeys_kboard;
1299 static Lisp_Object term_get_fkeys_1 (void);
1301 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1302 This function scans the termcap function key sequence entries, and
1303 adds entries to Vinput_decode_map for each function key it finds. */
1305 static void
1306 term_get_fkeys (char **address, KBOARD *kboard)
1308 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1309 errors during the call. The only errors should be from Fdefine_key
1310 when given a key sequence containing an invalid prefix key. If the
1311 termcap defines function keys which use a prefix that is already bound
1312 to a command by the default bindings, we should silently ignore that
1313 function key specification, rather than giving the user an error and
1314 refusing to run at all on such a terminal. */
1316 term_get_fkeys_address = address;
1317 term_get_fkeys_kboard = kboard;
1318 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1321 static Lisp_Object
1322 term_get_fkeys_1 (void)
1324 int i;
1326 char **address = term_get_fkeys_address;
1327 KBOARD *kboard = term_get_fkeys_kboard;
1329 /* This can happen if CANNOT_DUMP or with strange options. */
1330 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1331 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1333 for (i = 0; i < (sizeof (keys) / sizeof (keys[0])); i++)
1335 char *sequence = tgetstr (keys[i].cap, address);
1336 if (sequence)
1337 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1338 Fmake_vector (make_number (1),
1339 intern (keys[i].name)));
1342 /* The uses of the "k0" capability are inconsistent; sometimes it
1343 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1344 We will attempt to politely accommodate both systems by testing for
1345 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1348 const char *k_semi = tgetstr ("k;", address);
1349 const char *k0 = tgetstr ("k0", address);
1350 const char *k0_name = "f10";
1352 if (k_semi)
1354 if (k0)
1355 /* Define f0 first, so that f10 takes precedence in case the
1356 key sequences happens to be the same. */
1357 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1358 Fmake_vector (make_number (1), intern ("f0")));
1359 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1360 Fmake_vector (make_number (1), intern ("f10")));
1362 else if (k0)
1363 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1364 Fmake_vector (make_number (1), intern (k0_name)));
1367 /* Set up cookies for numbered function keys above f10. */
1369 char fcap[3], fkey[4];
1371 fcap[0] = 'F'; fcap[2] = '\0';
1372 for (i = 11; i < 64; i++)
1374 if (i <= 19)
1375 fcap[1] = '1' + i - 11;
1376 else if (i <= 45)
1377 fcap[1] = 'A' + i - 20;
1378 else
1379 fcap[1] = 'a' + i - 46;
1382 char *sequence = tgetstr (fcap, address);
1383 if (sequence)
1385 sprintf (fkey, "f%d", i);
1386 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1387 Fmake_vector (make_number (1),
1388 intern (fkey)));
1395 * Various mappings to try and get a better fit.
1398 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1399 if (!tgetstr (cap1, address)) \
1401 char *sequence = tgetstr (cap2, address); \
1402 if (sequence) \
1403 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1404 Fmake_vector (make_number (1), \
1405 intern (sym))); \
1408 /* if there's no key_next keycap, map key_npage to `next' keysym */
1409 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1410 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1411 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1412 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1413 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1414 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1415 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1417 /* IBM has their own non-standard dialect of terminfo.
1418 If the standard name isn't found, try the IBM name. */
1419 CONDITIONAL_REASSIGN ("kB", "KO", "backtab");
1420 CONDITIONAL_REASSIGN ("@4", "kJ", "execute"); /* actually "action" */
1421 CONDITIONAL_REASSIGN ("@4", "kc", "execute"); /* actually "command" */
1422 CONDITIONAL_REASSIGN ("%7", "ki", "menu");
1423 CONDITIONAL_REASSIGN ("@7", "kw", "end");
1424 CONDITIONAL_REASSIGN ("F1", "k<", "f11");
1425 CONDITIONAL_REASSIGN ("F2", "k>", "f12");
1426 CONDITIONAL_REASSIGN ("%1", "kq", "help");
1427 CONDITIONAL_REASSIGN ("*6", "kU", "select");
1428 #undef CONDITIONAL_REASSIGN
1431 return Qnil;
1433 #endif /* not DOS_NT */
1436 /***********************************************************************
1437 Character Display Information
1438 ***********************************************************************/
1439 static void append_glyph (struct it *);
1440 static void append_composite_glyph (struct it *);
1441 static void produce_composite_glyph (struct it *);
1442 static void append_glyphless_glyph (struct it *, int, const char *);
1443 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1445 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1446 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1447 the character for which to produce glyphs; IT->face_id contains the
1448 character's face. Padding glyphs are appended if IT->c has a
1449 IT->pixel_width > 1. */
1451 static void
1452 append_glyph (struct it *it)
1454 struct glyph *glyph, *end;
1455 int i;
1457 eassert (it->glyph_row);
1458 glyph = (it->glyph_row->glyphs[it->area]
1459 + it->glyph_row->used[it->area]);
1460 end = it->glyph_row->glyphs[1 + it->area];
1462 /* If the glyph row is reversed, we need to prepend the glyph rather
1463 than append it. */
1464 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1466 struct glyph *g;
1467 int move_by = it->pixel_width;
1469 /* Make room for the new glyphs. */
1470 if (move_by > end - glyph) /* don't overstep end of this area */
1471 move_by = end - glyph;
1472 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1473 g[move_by] = *g;
1474 glyph = it->glyph_row->glyphs[it->area];
1475 end = glyph + move_by;
1478 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1479 right, even in the REVERSED_P case, since (a) all of its u.ch are
1480 identical, and (b) the PADDING_P flag needs to be set for the
1481 leftmost one, because we write to the terminal left-to-right. */
1482 for (i = 0;
1483 i < it->pixel_width && glyph < end;
1484 ++i)
1486 glyph->type = CHAR_GLYPH;
1487 glyph->pixel_width = 1;
1488 glyph->u.ch = it->char_to_display;
1489 glyph->face_id = it->face_id;
1490 glyph->padding_p = i > 0;
1491 glyph->charpos = CHARPOS (it->position);
1492 glyph->object = it->object;
1493 if (it->bidi_p)
1495 glyph->resolved_level = it->bidi_it.resolved_level;
1496 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1497 emacs_abort ();
1498 glyph->bidi_type = it->bidi_it.type;
1500 else
1502 glyph->resolved_level = 0;
1503 glyph->bidi_type = UNKNOWN_BT;
1506 ++it->glyph_row->used[it->area];
1507 ++glyph;
1511 /* For external use. */
1512 void
1513 tty_append_glyph (struct it *it)
1515 append_glyph (it);
1519 /* Produce glyphs for the display element described by IT. *IT
1520 specifies what we want to produce a glyph for (character, image, ...),
1521 and where in the glyph matrix we currently are (glyph row and hpos).
1522 produce_glyphs fills in output fields of *IT with information such as the
1523 pixel width and height of a character, and maybe output actual glyphs at
1524 the same time if IT->glyph_row is non-null. For an overview, see
1525 the explanation in dispextern.h, before the definition of the
1526 display_element_type enumeration.
1528 produce_glyphs also stores the result of glyph width, ascent
1529 etc. computations in *IT.
1531 IT->glyph_row may be null, in which case produce_glyphs does not
1532 actually fill in the glyphs. This is used in the move_* functions
1533 in xdisp.c for text width and height computations.
1535 Callers usually don't call produce_glyphs directly;
1536 instead they use the macro PRODUCE_GLYPHS. */
1538 void
1539 produce_glyphs (struct it *it)
1541 /* If a hook is installed, let it do the work. */
1543 /* Nothing but characters are supported on terminal frames. */
1544 eassert (it->what == IT_CHARACTER
1545 || it->what == IT_COMPOSITION
1546 || it->what == IT_STRETCH
1547 || it->what == IT_GLYPHLESS);
1549 if (it->what == IT_STRETCH)
1551 produce_stretch_glyph (it);
1552 goto done;
1555 if (it->what == IT_COMPOSITION)
1557 produce_composite_glyph (it);
1558 goto done;
1561 if (it->what == IT_GLYPHLESS)
1563 produce_glyphless_glyph (it, Qnil);
1564 goto done;
1567 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1569 it->pixel_width = it->nglyphs = 1;
1570 if (it->glyph_row)
1571 append_glyph (it);
1573 else if (it->char_to_display == '\n')
1574 it->pixel_width = it->nglyphs = 0;
1575 else if (it->char_to_display == '\t')
1577 int absolute_x = (it->current_x
1578 + it->continuation_lines_width);
1579 int next_tab_x
1580 = (((1 + absolute_x + it->tab_width - 1)
1581 / it->tab_width)
1582 * it->tab_width);
1583 int nspaces;
1585 /* If part of the TAB has been displayed on the previous line
1586 which is continued now, continuation_lines_width will have
1587 been incremented already by the part that fitted on the
1588 continued line. So, we will get the right number of spaces
1589 here. */
1590 nspaces = next_tab_x - absolute_x;
1592 if (it->glyph_row)
1594 int n = nspaces;
1596 it->char_to_display = ' ';
1597 it->pixel_width = it->len = 1;
1599 while (n--)
1600 append_glyph (it);
1603 it->pixel_width = nspaces;
1604 it->nglyphs = nspaces;
1606 else if (CHAR_BYTE8_P (it->char_to_display))
1608 /* Coming here means that we must send the raw 8-bit byte as is
1609 to the terminal. Although there's no way to know how many
1610 columns it occupies on a screen, it is a good assumption that
1611 a single byte code has 1-column width. */
1612 it->pixel_width = it->nglyphs = 1;
1613 if (it->glyph_row)
1614 append_glyph (it);
1616 else
1618 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1620 if (char_charset (it->char_to_display, charset_list, NULL))
1622 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1623 it->nglyphs = it->pixel_width;
1624 if (it->glyph_row)
1625 append_glyph (it);
1627 else
1629 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1631 eassert (it->what == IT_GLYPHLESS);
1632 produce_glyphless_glyph (it, acronym);
1636 done:
1637 /* Advance current_x by the pixel width as a convenience for
1638 the caller. */
1639 if (it->area == TEXT_AREA)
1640 it->current_x += it->pixel_width;
1641 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1642 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1645 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1646 Called from produce_composite_glyph for terminal frames if
1647 IT->glyph_row != NULL. IT->face_id contains the character's
1648 face. */
1650 static void
1651 append_composite_glyph (struct it *it)
1653 struct glyph *glyph;
1655 eassert (it->glyph_row);
1656 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1657 if (glyph < it->glyph_row->glyphs[1 + it->area])
1659 /* If the glyph row is reversed, we need to prepend the glyph
1660 rather than append it. */
1661 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1663 struct glyph *g;
1665 /* Make room for the new glyph. */
1666 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1667 g[1] = *g;
1668 glyph = it->glyph_row->glyphs[it->area];
1670 glyph->type = COMPOSITE_GLYPH;
1671 glyph->pixel_width = it->pixel_width;
1672 glyph->u.cmp.id = it->cmp_it.id;
1673 if (it->cmp_it.ch < 0)
1675 glyph->u.cmp.automatic = 0;
1676 glyph->u.cmp.id = it->cmp_it.id;
1678 else
1680 glyph->u.cmp.automatic = 1;
1681 glyph->u.cmp.id = it->cmp_it.id;
1682 glyph->slice.cmp.from = it->cmp_it.from;
1683 glyph->slice.cmp.to = it->cmp_it.to - 1;
1686 glyph->face_id = it->face_id;
1687 glyph->padding_p = 0;
1688 glyph->charpos = CHARPOS (it->position);
1689 glyph->object = it->object;
1690 if (it->bidi_p)
1692 glyph->resolved_level = it->bidi_it.resolved_level;
1693 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1694 emacs_abort ();
1695 glyph->bidi_type = it->bidi_it.type;
1697 else
1699 glyph->resolved_level = 0;
1700 glyph->bidi_type = UNKNOWN_BT;
1703 ++it->glyph_row->used[it->area];
1704 ++glyph;
1709 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1710 the composition. We simply produces components of the composition
1711 assuming that the terminal has a capability to layout/render it
1712 correctly. */
1714 static void
1715 produce_composite_glyph (struct it *it)
1717 if (it->cmp_it.ch < 0)
1719 struct composition *cmp = composition_table[it->cmp_it.id];
1721 it->pixel_width = cmp->width;
1723 else
1725 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1727 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1728 it->cmp_it.to, NULL);
1730 it->nglyphs = 1;
1731 if (it->glyph_row)
1732 append_composite_glyph (it);
1736 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1737 is a face ID to be used for the glyph. What is actually appended
1738 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1739 comes from it->nglyphs bytes). */
1741 static void
1742 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1744 struct glyph *glyph, *end;
1745 int i;
1747 eassert (it->glyph_row);
1748 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1749 end = it->glyph_row->glyphs[1 + it->area];
1751 /* If the glyph row is reversed, we need to prepend the glyph rather
1752 than append it. */
1753 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1755 struct glyph *g;
1756 int move_by = it->pixel_width;
1758 /* Make room for the new glyphs. */
1759 if (move_by > end - glyph) /* don't overstep end of this area */
1760 move_by = end - glyph;
1761 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1762 g[move_by] = *g;
1763 glyph = it->glyph_row->glyphs[it->area];
1764 end = glyph + move_by;
1767 if (glyph >= end)
1768 return;
1769 glyph->type = CHAR_GLYPH;
1770 glyph->pixel_width = 1;
1771 glyph->face_id = face_id;
1772 glyph->padding_p = 0;
1773 glyph->charpos = CHARPOS (it->position);
1774 glyph->object = it->object;
1775 if (it->bidi_p)
1777 glyph->resolved_level = it->bidi_it.resolved_level;
1778 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1779 emacs_abort ();
1780 glyph->bidi_type = it->bidi_it.type;
1782 else
1784 glyph->resolved_level = 0;
1785 glyph->bidi_type = UNKNOWN_BT;
1788 /* BIDI Note: we put the glyphs of characters left to right, even in
1789 the REVERSED_P case because we write to the terminal
1790 left-to-right. */
1791 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1793 if (i > 0)
1794 glyph[0] = glyph[-1];
1795 glyph->u.ch = str[i];
1796 ++it->glyph_row->used[it->area];
1797 ++glyph;
1801 /* Produce glyphs for a glyphless character for iterator IT.
1802 IT->glyphless_method specifies which method to use for displaying
1803 the character. See the description of enum
1804 glyphless_display_method in dispextern.h for the details.
1806 ACRONYM, if non-nil, is an acronym string for the character.
1808 The glyphs actually produced are of type CHAR_GLYPH. */
1810 static void
1811 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1813 int len, face_id = merge_glyphless_glyph_face (it);
1814 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1815 char const *str = " ";
1817 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1819 /* As there's no way to produce a thin space, we produce a space
1820 of canonical width. */
1821 len = 1;
1823 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1825 len = CHAR_WIDTH (it->c);
1826 if (len == 0)
1827 len = 1;
1828 else if (len > 4)
1829 len = 4;
1830 len = sprintf (buf, "[%.*s]", len, str);
1831 str = buf;
1833 else
1835 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1837 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1838 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1839 if (CONSP (acronym))
1840 acronym = XCDR (acronym);
1841 buf[0] = '[';
1842 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1843 for (len = 0; len < 6 && str[len] && ASCII_BYTE_P (str[len]); len++)
1844 buf[1 + len] = str[len];
1845 buf[1 + len] = ']';
1846 len += 2;
1848 else
1850 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1851 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1852 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1853 : sprintf (buf, "\\x%06X", it->c));
1855 str = buf;
1858 it->pixel_width = len;
1859 it->nglyphs = len;
1860 if (it->glyph_row)
1861 append_glyphless_glyph (it, face_id, str);
1865 /***********************************************************************
1866 Faces
1867 ***********************************************************************/
1869 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1870 one of the enumerators from enum no_color_bit, or a bit set built
1871 from them. Some display attributes may not be used together with
1872 color; the termcap capability `NC' specifies which ones. */
1874 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1875 (tty->TN_max_colors > 0 \
1876 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1877 : 1)
1879 /* Turn appearances of face FACE_ID on tty frame F on.
1880 FACE_ID is a realized face ID number, in the face cache. */
1882 static void
1883 turn_on_face (struct frame *f, int face_id)
1885 struct face *face = FACE_FROM_ID (f, face_id);
1886 long fg = face->foreground;
1887 long bg = face->background;
1888 struct tty_display_info *tty = FRAME_TTY (f);
1890 /* Do this first because TS_end_standout_mode may be the same
1891 as TS_exit_attribute_mode, which turns all appearances off. */
1892 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE))
1894 if (tty->TN_max_colors > 0)
1896 if (fg >= 0 && bg >= 0)
1898 /* If the terminal supports colors, we can set them
1899 below without using reverse video. The face's fg
1900 and bg colors are set as they should appear on
1901 the screen, i.e. they take the inverse-video'ness
1902 of the face already into account. */
1904 else if (inverse_video)
1906 if (fg == FACE_TTY_DEFAULT_FG_COLOR
1907 || bg == FACE_TTY_DEFAULT_BG_COLOR)
1908 tty_toggle_highlight (tty);
1910 else
1912 if (fg == FACE_TTY_DEFAULT_BG_COLOR
1913 || bg == FACE_TTY_DEFAULT_FG_COLOR)
1914 tty_toggle_highlight (tty);
1917 else
1919 /* If we can't display colors, use reverse video
1920 if the face specifies that. */
1921 if (inverse_video)
1923 if (fg == FACE_TTY_DEFAULT_FG_COLOR
1924 || bg == FACE_TTY_DEFAULT_BG_COLOR)
1925 tty_toggle_highlight (tty);
1927 else
1929 if (fg == FACE_TTY_DEFAULT_BG_COLOR
1930 || bg == FACE_TTY_DEFAULT_FG_COLOR)
1931 tty_toggle_highlight (tty);
1936 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1937 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1939 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1941 if (tty->TS_enter_italic_mode)
1942 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1943 else
1944 /* Italics mode is unavailable on many terminals. In that
1945 case, map slant to dimmed text; we want italic text to
1946 appear different and dimming is not otherwise used. */
1947 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1950 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1951 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1953 if (tty->TN_max_colors > 0)
1955 const char *ts;
1956 char *p;
1958 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1959 if (fg >= 0 && ts)
1961 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1962 OUTPUT (tty, p);
1963 xfree (p);
1966 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1967 if (bg >= 0 && ts)
1969 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1970 OUTPUT (tty, p);
1971 xfree (p);
1977 /* Turn off appearances of face FACE_ID on tty frame F. */
1979 static void
1980 turn_off_face (struct frame *f, int face_id)
1982 struct face *face = FACE_FROM_ID (f, face_id);
1983 struct tty_display_info *tty = FRAME_TTY (f);
1985 eassert (face != NULL);
1987 if (tty->TS_exit_attribute_mode)
1989 /* Capability "me" will turn off appearance modes double-bright,
1990 half-bright, reverse-video, standout, underline. It may or
1991 may not turn off alt-char-mode. */
1992 if (face->tty_bold_p
1993 || face->tty_italic_p
1994 || face->tty_reverse_p
1995 || face->tty_underline_p)
1997 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1998 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1999 tty->standout_mode = 0;
2002 else
2004 /* If we don't have "me" we can only have those appearances
2005 that have exit sequences defined. */
2006 if (face->tty_underline_p)
2007 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
2010 /* Switch back to default colors. */
2011 if (tty->TN_max_colors > 0
2012 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
2013 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
2014 || (face->background != FACE_TTY_DEFAULT_COLOR
2015 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
2016 OUTPUT1_IF (tty, tty->TS_orig_pair);
2020 /* Return true if the terminal on frame F supports all of the
2021 capabilities in CAPS simultaneously, with foreground and background
2022 colors FG and BG. */
2024 bool
2025 tty_capable_p (struct tty_display_info *tty, unsigned int caps,
2026 unsigned long fg, unsigned long bg)
2028 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2029 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2030 return 0;
2032 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2033 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2034 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2035 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2036 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2038 /* We can do it! */
2039 return 1;
2042 /* Return non-zero if the terminal is capable to display colors. */
2044 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2045 0, 1, 0,
2046 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2048 TERMINAL can be a terminal object, a frame, or nil (meaning the
2049 selected frame's terminal). This function always returns nil if
2050 TERMINAL does not refer to a text terminal. */)
2051 (Lisp_Object terminal)
2053 struct terminal *t = get_tty_terminal (terminal, 0);
2054 if (!t)
2055 return Qnil;
2056 else
2057 return t->display_info.tty->TN_max_colors > 0 ? Qt : Qnil;
2060 /* Return the number of supported colors. */
2061 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2062 Stty_display_color_cells, 0, 1, 0,
2063 doc: /* Return the number of colors supported by the tty device TERMINAL.
2065 TERMINAL can be a terminal object, a frame, or nil (meaning the
2066 selected frame's terminal). This function always returns 0 if
2067 TERMINAL does not refer to a text terminal. */)
2068 (Lisp_Object terminal)
2070 struct terminal *t = get_tty_terminal (terminal, 0);
2071 if (!t)
2072 return make_number (0);
2073 else
2074 return make_number (t->display_info.tty->TN_max_colors);
2077 #ifndef DOS_NT
2079 /* Declare here rather than in the function, as in the rest of Emacs,
2080 to work around an HPUX compiler bug (?). See
2081 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2082 static int default_max_colors;
2083 static int default_max_pairs;
2084 static int default_no_color_video;
2085 static char *default_orig_pair;
2086 static char *default_set_foreground;
2087 static char *default_set_background;
2089 /* Save or restore the default color-related capabilities of this
2090 terminal. */
2091 static void
2092 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2095 if (save)
2097 xfree (default_orig_pair);
2098 default_orig_pair = tty->TS_orig_pair ? xstrdup (tty->TS_orig_pair) : NULL;
2100 xfree (default_set_foreground);
2101 default_set_foreground = tty->TS_set_foreground ? xstrdup (tty->TS_set_foreground)
2102 : NULL;
2104 xfree (default_set_background);
2105 default_set_background = tty->TS_set_background ? xstrdup (tty->TS_set_background)
2106 : NULL;
2108 default_max_colors = tty->TN_max_colors;
2109 default_max_pairs = tty->TN_max_pairs;
2110 default_no_color_video = tty->TN_no_color_video;
2112 else
2114 tty->TS_orig_pair = default_orig_pair;
2115 tty->TS_set_foreground = default_set_foreground;
2116 tty->TS_set_background = default_set_background;
2117 tty->TN_max_colors = default_max_colors;
2118 tty->TN_max_pairs = default_max_pairs;
2119 tty->TN_no_color_video = default_no_color_video;
2123 /* Setup one of the standard tty color schemes according to MODE.
2124 MODE's value is generally the number of colors which we want to
2125 support; zero means set up for the default capabilities, the ones
2126 we saw at init_tty time; -1 means turn off color support. */
2127 static void
2128 tty_setup_colors (struct tty_display_info *tty, int mode)
2130 /* Canonicalize all negative values of MODE. */
2131 if (mode < -1)
2132 mode = -1;
2134 switch (mode)
2136 case -1: /* no colors at all */
2137 tty->TN_max_colors = 0;
2138 tty->TN_max_pairs = 0;
2139 tty->TN_no_color_video = 0;
2140 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2141 break;
2142 case 0: /* default colors, if any */
2143 default:
2144 tty_default_color_capabilities (tty, 0);
2145 break;
2146 case 8: /* 8 standard ANSI colors */
2147 tty->TS_orig_pair = "\033[0m";
2148 #ifdef TERMINFO
2149 tty->TS_set_foreground = "\033[3%p1%dm";
2150 tty->TS_set_background = "\033[4%p1%dm";
2151 #else
2152 tty->TS_set_foreground = "\033[3%dm";
2153 tty->TS_set_background = "\033[4%dm";
2154 #endif
2155 tty->TN_max_colors = 8;
2156 tty->TN_max_pairs = 64;
2157 tty->TN_no_color_video = 0;
2158 break;
2162 void
2163 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2165 Lisp_Object tem, val;
2166 Lisp_Object color_mode;
2167 int mode;
2168 Lisp_Object tty_color_mode_alist
2169 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2171 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2172 val = CONSP (tem) ? XCDR (tem) : Qnil;
2174 if (INTEGERP (val))
2175 color_mode = val;
2176 else if (SYMBOLP (tty_color_mode_alist))
2178 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2179 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2181 else
2182 color_mode = Qnil;
2184 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2186 if (mode != tty->previous_color_mode)
2188 tty->previous_color_mode = mode;
2189 tty_setup_colors (tty , mode);
2190 /* This recomputes all the faces given the new color definitions. */
2191 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2195 #endif /* !DOS_NT */
2199 /* Return the tty display object specified by TERMINAL. */
2201 static struct terminal *
2202 get_tty_terminal (Lisp_Object terminal, bool throw)
2204 struct terminal *t = get_terminal (terminal, throw);
2206 if (t && t->type != output_termcap && t->type != output_msdos_raw)
2208 if (throw)
2209 error ("Device %d is not a termcap terminal device", t->id);
2210 else
2211 return NULL;
2214 return t;
2217 /* Return an active termcap device that uses the tty device with the
2218 given name.
2220 This function ignores suspended devices.
2222 Returns NULL if the named terminal device is not opened. */
2224 struct terminal *
2225 get_named_tty (const char *name)
2227 struct terminal *t;
2229 eassert (name);
2231 for (t = terminal_list; t; t = t->next_terminal)
2233 if ((t->type == output_termcap || t->type == output_msdos_raw)
2234 && !strcmp (t->display_info.tty->name, name)
2235 && TERMINAL_ACTIVE_P (t))
2236 return t;
2239 return 0;
2243 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2244 doc: /* Return the type of the tty device that TERMINAL uses.
2245 Returns nil if TERMINAL is not on a tty device.
2247 TERMINAL can be a terminal object, a frame, or nil (meaning the
2248 selected frame's terminal). */)
2249 (Lisp_Object terminal)
2251 struct terminal *t = get_terminal (terminal, 1);
2253 if (t->type != output_termcap && t->type != output_msdos_raw)
2254 return Qnil;
2256 if (t->display_info.tty->type)
2257 return build_string (t->display_info.tty->type);
2258 else
2259 return Qnil;
2262 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2263 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2265 TERMINAL can be a terminal object, a frame, or nil (meaning the
2266 selected frame's terminal). This function always returns nil if
2267 TERMINAL is not on a tty device. */)
2268 (Lisp_Object terminal)
2270 struct terminal *t = get_terminal (terminal, 1);
2272 if ((t->type != output_termcap && t->type != output_msdos_raw)
2273 || strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2274 return Qnil;
2275 else
2276 return Qt;
2279 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2280 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2281 This is used to override the terminfo data, for certain terminals that
2282 do not really do underlining, but say that they do. This function has
2283 no effect if used on a non-tty terminal.
2285 TERMINAL can be a terminal object, a frame or nil (meaning the
2286 selected frame's terminal). This function always returns nil if
2287 TERMINAL does not refer to a text terminal. */)
2288 (Lisp_Object terminal)
2290 struct terminal *t = get_terminal (terminal, 1);
2292 if (t->type == output_termcap)
2293 t->display_info.tty->TS_enter_underline_mode = 0;
2294 return Qnil;
2297 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2298 doc: /* Return the topmost terminal frame on TERMINAL.
2299 TERMINAL can be a terminal object, a frame or nil (meaning the
2300 selected frame's terminal). This function returns nil if TERMINAL
2301 does not refer to a text terminal. Otherwise, it returns the
2302 top-most frame on the text terminal. */)
2303 (Lisp_Object terminal)
2305 struct terminal *t = get_terminal (terminal, 1);
2307 if (t->type == output_termcap)
2308 return t->display_info.tty->top_frame;
2309 return Qnil;
2314 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2315 doc: /* Suspend the terminal device TTY.
2317 The device is restored to its default state, and Emacs ceases all
2318 access to the tty device. Frames that use the device are not deleted,
2319 but input is not read from them and if they change, their display is
2320 not updated.
2322 TTY may be a terminal object, a frame, or nil for the terminal device
2323 of the currently selected frame.
2325 This function runs `suspend-tty-functions' after suspending the
2326 device. The functions are run with one arg, the id of the suspended
2327 terminal device.
2329 `suspend-tty' does nothing if it is called on a device that is already
2330 suspended.
2332 A suspended tty may be resumed by calling `resume-tty' on it. */)
2333 (Lisp_Object tty)
2335 struct terminal *t = get_tty_terminal (tty, 1);
2336 FILE *f;
2338 if (!t)
2339 error ("Unknown tty device");
2341 f = t->display_info.tty->input;
2343 if (f)
2345 /* First run `suspend-tty-functions' and then clean up the tty
2346 state because `suspend-tty-functions' might need to change
2347 the tty state. */
2348 Lisp_Object args[2];
2349 args[0] = intern ("suspend-tty-functions");
2350 XSETTERMINAL (args[1], t);
2351 Frun_hook_with_args (2, args);
2353 reset_sys_modes (t->display_info.tty);
2354 delete_keyboard_wait_descriptor (fileno (f));
2356 #ifndef MSDOS
2357 fclose (f);
2358 if (f != t->display_info.tty->output)
2359 fclose (t->display_info.tty->output);
2360 #endif
2362 t->display_info.tty->input = 0;
2363 t->display_info.tty->output = 0;
2365 if (FRAMEP (t->display_info.tty->top_frame))
2366 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2370 /* Clear display hooks to prevent further output. */
2371 clear_tty_hooks (t);
2373 return Qnil;
2376 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2377 doc: /* Resume the previously suspended terminal device TTY.
2378 The terminal is opened and reinitialized. Frames that are on the
2379 suspended terminal are revived.
2381 It is an error to resume a terminal while another terminal is active
2382 on the same device.
2384 This function runs `resume-tty-functions' after resuming the terminal.
2385 The functions are run with one arg, the id of the resumed terminal
2386 device.
2388 `resume-tty' does nothing if it is called on a device that is not
2389 suspended.
2391 TTY may be a terminal object, a frame, or nil (meaning the selected
2392 frame's terminal). */)
2393 (Lisp_Object tty)
2395 struct terminal *t = get_tty_terminal (tty, 1);
2396 int fd;
2398 if (!t)
2399 error ("Unknown tty device");
2401 if (!t->display_info.tty->input)
2403 if (get_named_tty (t->display_info.tty->name))
2404 error ("Cannot resume display while another display is active on the same device");
2406 #ifdef MSDOS
2407 t->display_info.tty->output = stdout;
2408 t->display_info.tty->input = stdin;
2409 #else /* !MSDOS */
2410 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2411 t->display_info.tty->input = t->display_info.tty->output
2412 = fd < 0 ? 0 : fdopen (fd, "w+");
2414 if (! t->display_info.tty->input)
2416 int open_errno = errno;
2417 emacs_close (fd);
2418 report_file_errno ("Cannot reopen tty device",
2419 build_string (t->display_info.tty->name),
2420 open_errno);
2423 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2424 dissociate_if_controlling_tty (fd);
2425 #endif
2427 add_keyboard_wait_descriptor (fd);
2429 if (FRAMEP (t->display_info.tty->top_frame))
2431 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2432 int width, height;
2433 int old_height = FRAME_COLS (f);
2434 int old_width = FRAME_LINES (f);
2436 /* Check if terminal/window size has changed while the frame
2437 was suspended. */
2438 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2439 if (width != old_width || height != old_height)
2440 change_frame_size (f, height, width, 0, 0, 0);
2441 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2444 set_tty_hooks (t);
2445 init_sys_modes (t->display_info.tty);
2448 /* Run `resume-tty-functions'. */
2449 Lisp_Object args[2];
2450 args[0] = intern ("resume-tty-functions");
2451 XSETTERMINAL (args[1], t);
2452 Frun_hook_with_args (2, args);
2456 set_tty_hooks (t);
2458 return Qnil;
2462 /***********************************************************************
2463 Mouse
2464 ***********************************************************************/
2466 #ifdef HAVE_GPM
2468 #ifndef HAVE_WINDOW_SYSTEM
2469 void
2470 term_mouse_moveto (int x, int y)
2472 /* TODO: how to set mouse position?
2473 const char *name;
2474 int fd;
2475 name = (const char *) ttyname (0);
2476 fd = emacs_open (name, O_WRONLY, 0);
2477 SOME_FUNCTION (x, y, fd);
2478 emacs_close (fd);
2479 last_mouse_x = x;
2480 last_mouse_y = y; */
2482 #endif /* HAVE_WINDOW_SYSTEM */
2484 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2485 void
2486 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2487 int start_hpos, int end_hpos,
2488 enum draw_glyphs_face draw)
2490 int nglyphs = end_hpos - start_hpos;
2491 struct frame *f = XFRAME (WINDOW_FRAME (w));
2492 struct tty_display_info *tty = FRAME_TTY (f);
2493 int face_id = tty->mouse_highlight.mouse_face_face_id;
2494 int save_x, save_y, pos_x, pos_y;
2496 if (end_hpos >= row->used[TEXT_AREA])
2497 nglyphs = row->used[TEXT_AREA] - start_hpos;
2499 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2500 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2502 /* Save current cursor co-ordinates. */
2503 save_y = curY (tty);
2504 save_x = curX (tty);
2505 cursor_to (f, pos_y, pos_x);
2507 if (draw == DRAW_MOUSE_FACE)
2508 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2509 nglyphs, face_id);
2510 else if (draw == DRAW_NORMAL_TEXT)
2511 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2513 cursor_to (f, save_y, save_x);
2516 static bool
2517 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2519 /* Has the mouse moved off the glyph it was on at the last sighting? */
2520 if (event->x != last_mouse_x || event->y != last_mouse_y)
2522 frame->mouse_moved = 1;
2523 note_mouse_highlight (frame, event->x, event->y);
2524 /* Remember which glyph we're now on. */
2525 last_mouse_x = event->x;
2526 last_mouse_y = event->y;
2527 return 1;
2529 return 0;
2532 /* Return the Time that corresponds to T. Wrap around on overflow. */
2533 static Time
2534 timeval_to_Time (struct timeval const *t)
2536 Time s_1000, ms;
2538 s_1000 = t->tv_sec;
2539 s_1000 *= 1000;
2540 ms = t->tv_usec / 1000;
2541 return s_1000 + ms;
2544 /* Return the current position of the mouse.
2546 Set *f to the frame the mouse is in, or zero if the mouse is in no
2547 Emacs frame. If it is set to zero, all the other arguments are
2548 garbage.
2550 Set *bar_window to Qnil, and *x and *y to the column and
2551 row of the character cell the mouse is over.
2553 Set *timeptr to the time the mouse was at the returned position.
2555 This clears mouse_moved until the next motion
2556 event arrives. */
2557 static void
2558 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2559 enum scroll_bar_part *part, Lisp_Object *x,
2560 Lisp_Object *y, Time *timeptr)
2562 struct timeval now;
2564 *fp = SELECTED_FRAME ();
2565 (*fp)->mouse_moved = 0;
2567 *bar_window = Qnil;
2568 *part = 0;
2570 XSETINT (*x, last_mouse_x);
2571 XSETINT (*y, last_mouse_y);
2572 gettimeofday(&now, 0);
2573 *timeptr = timeval_to_Time (&now);
2576 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2578 If the event is a button press, then note that we have grabbed
2579 the mouse. */
2581 static Lisp_Object
2582 term_mouse_click (struct input_event *result, Gpm_Event *event,
2583 struct frame *f)
2585 struct timeval now;
2586 int i, j;
2588 result->kind = GPM_CLICK_EVENT;
2589 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2591 if (event->buttons & j) {
2592 result->code = i; /* button number */
2593 break;
2596 gettimeofday(&now, 0);
2597 result->timestamp = timeval_to_Time (&now);
2599 if (event->type & GPM_UP)
2600 result->modifiers = up_modifier;
2601 else if (event->type & GPM_DOWN)
2602 result->modifiers = down_modifier;
2603 else
2604 result->modifiers = 0;
2606 if (event->type & GPM_SINGLE)
2607 result->modifiers |= click_modifier;
2609 if (event->type & GPM_DOUBLE)
2610 result->modifiers |= double_modifier;
2612 if (event->type & GPM_TRIPLE)
2613 result->modifiers |= triple_modifier;
2615 if (event->type & GPM_DRAG)
2616 result->modifiers |= drag_modifier;
2618 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2620 /* 1 << KG_SHIFT */
2621 if (event->modifiers & (1 << 0))
2622 result->modifiers |= shift_modifier;
2624 /* 1 << KG_CTRL */
2625 if (event->modifiers & (1 << 2))
2626 result->modifiers |= ctrl_modifier;
2628 /* 1 << KG_ALT || KG_ALTGR */
2629 if (event->modifiers & (1 << 3)
2630 || event->modifiers & (1 << 1))
2631 result->modifiers |= meta_modifier;
2634 XSETINT (result->x, event->x);
2635 XSETINT (result->y, event->y);
2636 XSETFRAME (result->frame_or_window, f);
2637 result->arg = Qnil;
2638 return Qnil;
2642 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2644 struct frame *f = XFRAME (tty->top_frame);
2645 struct input_event ie;
2646 bool do_help = 0;
2647 int count = 0;
2649 EVENT_INIT (ie);
2650 ie.kind = NO_EVENT;
2651 ie.arg = Qnil;
2653 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2654 previous_help_echo_string = help_echo_string;
2655 help_echo_string = Qnil;
2657 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2659 if (!term_mouse_movement (f, event))
2660 help_echo_string = previous_help_echo_string;
2662 /* If the contents of the global variable help_echo_string
2663 has changed, generate a HELP_EVENT. */
2664 if (!NILP (help_echo_string)
2665 || !NILP (previous_help_echo_string))
2666 do_help = 1;
2668 goto done;
2670 else {
2671 f->mouse_moved = 0;
2672 term_mouse_click (&ie, event, f);
2675 done:
2676 if (ie.kind != NO_EVENT)
2678 kbd_buffer_store_event_hold (&ie, hold_quit);
2679 count++;
2682 if (do_help
2683 && !(hold_quit && hold_quit->kind != NO_EVENT))
2685 Lisp_Object frame;
2687 if (f)
2688 XSETFRAME (frame, f);
2689 else
2690 frame = Qnil;
2692 gen_help_event (help_echo_string, frame, help_echo_window,
2693 help_echo_object, help_echo_pos);
2694 count++;
2697 return count;
2700 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2701 0, 0, 0,
2702 doc: /* Open a connection to Gpm.
2703 Gpm-mouse can only be activated for one tty at a time. */)
2704 (void)
2706 struct frame *f = SELECTED_FRAME ();
2707 struct tty_display_info *tty
2708 = ((f)->output_method == output_termcap
2709 ? (f)->terminal->display_info.tty : NULL);
2710 Gpm_Connect connection;
2712 if (!tty)
2713 error ("Gpm-mouse only works in the GNU/Linux console");
2714 if (gpm_tty == tty)
2715 return Qnil; /* Already activated, nothing to do. */
2716 if (gpm_tty)
2717 error ("Gpm-mouse can only be activated for one tty at a time");
2719 connection.eventMask = ~0;
2720 connection.defaultMask = ~GPM_HARD;
2721 connection.maxMod = ~0;
2722 connection.minMod = 0;
2723 gpm_zerobased = 1;
2725 if (Gpm_Open (&connection, 0) < 0)
2726 error ("Gpm-mouse failed to connect to the gpm daemon");
2727 else
2729 gpm_tty = tty;
2730 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2731 to generate SIGIOs. Apparently we need to call reset_sys_modes
2732 before calling init_sys_modes. */
2733 reset_sys_modes (tty);
2734 init_sys_modes (tty);
2735 add_gpm_wait_descriptor (gpm_fd);
2736 return Qnil;
2740 void
2741 close_gpm (int fd)
2743 if (fd >= 0)
2744 delete_gpm_wait_descriptor (fd);
2745 while (Gpm_Close()); /* close all the stack */
2746 gpm_tty = NULL;
2749 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2750 0, 0, 0,
2751 doc: /* Close a connection to Gpm. */)
2752 (void)
2754 struct frame *f = SELECTED_FRAME ();
2755 struct tty_display_info *tty
2756 = ((f)->output_method == output_termcap
2757 ? (f)->terminal->display_info.tty : NULL);
2759 if (!tty || gpm_tty != tty)
2760 return Qnil; /* Not activated on this terminal, nothing to do. */
2762 close_gpm (gpm_fd);
2763 return Qnil;
2765 #endif /* HAVE_GPM */
2768 /***********************************************************************
2769 Menus
2770 ***********************************************************************/
2772 #if defined (HAVE_MENUS) && !defined (MSDOS)
2774 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2776 However, unlike on MSDOS, where the menu text is drawn directly to
2777 the display video memory, on a TTY we use display_string (see
2778 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2779 the menu items directly into the frame's 'desired_matrix' glyph
2780 matrix, and then call update_frame_with_menu to deliver the results
2781 to the glass. The previous contents of the screen, in the form of
2782 the current_matrix, is stashed away, and used to restore screen
2783 contents when the menu selection changes or when the final
2784 selection is made and the menu should be popped down.
2786 The idea of this implementation was suggested by Gerd Moellmann. */
2788 #define TTYM_FAILURE -1
2789 #define TTYM_SUCCESS 1
2790 #define TTYM_NO_SELECT 2
2791 #define TTYM_IA_SELECT 3
2793 /* These hold text of the current and the previous menu help messages. */
2794 static const char *menu_help_message, *prev_menu_help_message;
2795 /* Pane number and item number of the menu item which generated the
2796 last menu help message. */
2797 static int menu_help_paneno, menu_help_itemno;
2799 static int menu_x, menu_y;
2801 static Lisp_Object Qtty_menu_navigation_map, Qtty_menu_exit;
2802 static Lisp_Object Qtty_menu_prev_item, Qtty_menu_next_item;
2803 static Lisp_Object Qtty_menu_next_menu, Qtty_menu_prev_menu;
2804 static Lisp_Object Qtty_menu_select, Qtty_menu_ignore;
2805 static Lisp_Object Qtty_menu_mouse_movement;
2807 typedef struct tty_menu_struct
2809 int count;
2810 char **text;
2811 struct tty_menu_struct **submenu;
2812 int *panenumber; /* Also used as enable. */
2813 int allocated;
2814 int panecount;
2815 int width;
2816 const char **help_text;
2817 } tty_menu;
2819 /* Create a brand new menu structure. */
2821 static tty_menu *
2822 tty_menu_create (void)
2824 tty_menu *menu;
2826 menu = (tty_menu *) xmalloc (sizeof (tty_menu));
2827 menu->allocated = menu->count = menu->panecount = menu->width = 0;
2828 return menu;
2831 /* Allocate some (more) memory for MENU ensuring that there is room for one
2832 for item. */
2834 static void
2835 tty_menu_make_room (tty_menu *menu)
2837 if (menu->allocated == 0)
2839 int count = menu->allocated = 10;
2840 menu->text = (char **) xmalloc (count * sizeof (char *));
2841 menu->submenu = (tty_menu **) xmalloc (count * sizeof (tty_menu *));
2842 menu->panenumber = (int *) xmalloc (count * sizeof (int));
2843 menu->help_text = (const char **) xmalloc (count * sizeof (char *));
2845 else if (menu->allocated == menu->count)
2847 int count = menu->allocated = menu->allocated + 10;
2848 menu->text
2849 = (char **) xrealloc (menu->text, count * sizeof (char *));
2850 menu->submenu
2851 = (tty_menu **) xrealloc (menu->submenu, count * sizeof (tty_menu *));
2852 menu->panenumber
2853 = (int *) xrealloc (menu->panenumber, count * sizeof (int));
2854 menu->help_text
2855 = (const char **) xrealloc (menu->help_text, count * sizeof (char *));
2859 /* Search the given menu structure for a given pane number. */
2861 static tty_menu *
2862 tty_menu_search_pane (tty_menu *menu, int pane)
2864 int i;
2865 tty_menu *try;
2867 for (i = 0; i < menu->count; i++)
2868 if (menu->submenu[i])
2870 if (pane == menu->panenumber[i])
2871 return menu->submenu[i];
2872 if ((try = tty_menu_search_pane (menu->submenu[i], pane)))
2873 return try;
2875 return (tty_menu *) 0;
2878 /* Determine how much screen space a given menu needs. */
2880 static void
2881 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2883 int i, h2, w2, maxsubwidth, maxheight;
2885 maxsubwidth = menu->width;
2886 maxheight = menu->count;
2887 for (i = 0; i < menu->count; i++)
2889 if (menu->submenu[i])
2891 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2892 if (w2 > maxsubwidth) maxsubwidth = w2;
2893 if (i + h2 > maxheight) maxheight = i + h2;
2896 *width = maxsubwidth;
2897 *height = maxheight;
2900 static void
2901 mouse_get_xy (int *x, int *y)
2903 struct frame *sf = SELECTED_FRAME ();
2904 Lisp_Object lmx, lmy, lisp_dummy;
2905 enum scroll_bar_part part_dummy;
2906 Time time_dummy;
2908 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2909 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2910 &lisp_dummy, &part_dummy,
2911 &lmx, &lmy,
2912 &time_dummy);
2913 if (!NILP (lmx))
2915 *x = XINT (lmx);
2916 *y = XINT (lmy);
2920 /* Display MENU at (X,Y) using FACES. */
2922 static void
2923 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2924 int mx, int my, int disp_help)
2926 int i, face, width, enabled, mousehere, row, col;
2927 struct frame *sf = SELECTED_FRAME ();
2928 struct tty_display_info *tty = FRAME_TTY (sf);
2930 menu_help_message = NULL;
2932 width = menu->width;
2933 col = cursorX (tty);
2934 row = cursorY (tty);
2935 #if 0
2936 IT_update_begin (sf); /* FIXME: do we need an update_begin_hook? */
2937 #endif
2938 for (i = 0; i < menu->count; i++)
2940 int max_width = width + 2; /* +2 for padding blanks on each side */
2942 cursor_to (sf, y + i, x);
2943 if (menu->submenu[i])
2944 max_width += 2; /* for displaying " >" after the item */
2945 enabled
2946 = (!menu->submenu[i] && menu->panenumber[i]) || (menu->submenu[i]);
2947 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2948 face = faces[enabled + mousehere * 2];
2949 /* Display the menu help string for the i-th menu item even if
2950 the menu item is currently disabled. That's what the GUI
2951 code does. */
2952 if (disp_help && enabled + mousehere * 2 >= 2)
2954 menu_help_message = menu->help_text[i];
2955 menu_help_paneno = pn - 1;
2956 menu_help_itemno = i;
2958 display_tty_menu_item (menu->text[i], max_width, face, x, y + i,
2959 menu->submenu[i] != NULL);
2961 update_frame_with_menu (sf);
2962 cursor_to (sf, row, col);
2965 /* --------------------------- X Menu emulation ---------------------- */
2967 /* Report availability of menus. */
2970 have_menus_p (void) { return 1; }
2972 /* Create a new pane and place it on the outer-most level. */
2974 static int
2975 tty_menu_add_pane (tty_menu *menu, const char *txt)
2977 int len;
2978 const char *p;
2980 tty_menu_make_room (menu);
2981 menu->submenu[menu->count] = tty_menu_create ();
2982 menu->text[menu->count] = (char *)txt;
2983 menu->panenumber[menu->count] = ++menu->panecount;
2984 menu->help_text[menu->count] = NULL;
2985 menu->count++;
2987 /* Update the menu width, if necessary. */
2988 for (len = 0, p = txt; *p; )
2990 int ch_len;
2991 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
2993 len += CHAR_WIDTH (ch);
2994 p += ch_len;
2997 if (len > menu->width)
2998 menu->width = len;
3000 return menu->panecount;
3003 /* Create a new item in a menu pane. */
3006 tty_menu_add_selection (tty_menu *menu, int pane,
3007 char *txt, int enable, char const *help_text)
3009 int len;
3010 char *p;
3012 if (pane)
3013 if (!(menu = tty_menu_search_pane (menu, pane)))
3014 return TTYM_FAILURE;
3015 tty_menu_make_room (menu);
3016 menu->submenu[menu->count] = (tty_menu *) 0;
3017 menu->text[menu->count] = txt;
3018 menu->panenumber[menu->count] = enable;
3019 menu->help_text[menu->count] = help_text;
3020 menu->count++;
3022 /* Update the menu width, if necessary. */
3023 for (len = 0, p = txt; *p; )
3025 int ch_len;
3026 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
3028 len += CHAR_WIDTH (ch);
3029 p += ch_len;
3032 if (len > menu->width)
3033 menu->width = len;
3035 return TTYM_SUCCESS;
3038 /* Decide where the menu would be placed if requested at (X,Y). */
3040 void
3041 tty_menu_locate (tty_menu *menu, int x, int y,
3042 int *ulx, int *uly, int *width, int *height)
3044 tty_menu_calc_size (menu, width, height);
3045 *ulx = x + 1;
3046 *uly = y;
3047 *width += 2;
3050 struct tty_menu_state
3052 struct glyph_matrix *screen_behind;
3053 tty_menu *menu;
3054 int pane;
3055 int x, y;
3058 /* Save away the contents of frame F's current frame matrix, and
3059 enable all its rows. Value is a glyph matrix holding the contents
3060 of F's current frame matrix with all its glyph rows enabled. */
3062 struct glyph_matrix *
3063 save_and_enable_current_matrix (struct frame *f)
3065 int i;
3066 struct glyph_matrix *saved = xzalloc (sizeof *saved);
3067 saved->nrows = f->current_matrix->nrows;
3068 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
3070 for (i = 0; i < saved->nrows; ++i)
3072 struct glyph_row *from = f->current_matrix->rows + i;
3073 struct glyph_row *to = saved->rows + i;
3074 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3076 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
3077 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3078 to->used[TEXT_AREA] = from->used[TEXT_AREA];
3079 /* Make sure every row is enabled, or else update_frame will not
3080 redraw them. (Rows that are identical to what is already on
3081 screen will not be redrawn anyway.) */
3082 to->enabled_p = 1;
3083 to->hash = from->hash;
3084 if (from->used[LEFT_MARGIN_AREA])
3086 nbytes = from->used[LEFT_MARGIN_AREA] * sizeof (struct glyph);
3087 to->glyphs[LEFT_MARGIN_AREA] = (struct glyph *) xmalloc (nbytes);
3088 memcpy (to->glyphs[LEFT_MARGIN_AREA],
3089 from->glyphs[LEFT_MARGIN_AREA], nbytes);
3090 to->used[LEFT_MARGIN_AREA] = from->used[LEFT_MARGIN_AREA];
3092 if (from->used[RIGHT_MARGIN_AREA])
3094 nbytes = from->used[RIGHT_MARGIN_AREA] * sizeof (struct glyph);
3095 to->glyphs[RIGHT_MARGIN_AREA] = (struct glyph *) xmalloc (nbytes);
3096 memcpy (to->glyphs[RIGHT_MARGIN_AREA],
3097 from->glyphs[RIGHT_MARGIN_AREA], nbytes);
3098 to->used[RIGHT_MARGIN_AREA] = from->used[RIGHT_MARGIN_AREA];
3102 return saved;
3105 /* Restore the contents of frame F's desired frame matrix from SAVED,
3106 and free memory associated with SAVED. */
3108 static void
3109 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
3111 int i;
3113 for (i = 0; i < saved->nrows; ++i)
3115 struct glyph_row *from = saved->rows + i;
3116 struct glyph_row *to = f->desired_matrix->rows + i;
3117 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3119 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
3120 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3121 to->used[TEXT_AREA] = from->used[TEXT_AREA];
3122 to->enabled_p = from->enabled_p;
3123 to->hash = from->hash;
3124 nbytes = from->used[LEFT_MARGIN_AREA] * sizeof (struct glyph);
3125 if (nbytes)
3127 eassert (to->glyphs[LEFT_MARGIN_AREA] != from->glyphs[LEFT_MARGIN_AREA]);
3128 memcpy (to->glyphs[LEFT_MARGIN_AREA],
3129 from->glyphs[LEFT_MARGIN_AREA], nbytes);
3130 to->used[LEFT_MARGIN_AREA] = from->used[LEFT_MARGIN_AREA];
3132 else
3133 to->used[LEFT_MARGIN_AREA] = 0;
3134 nbytes = from->used[RIGHT_MARGIN_AREA] * sizeof (struct glyph);
3135 if (nbytes)
3137 eassert (to->glyphs[RIGHT_MARGIN_AREA] != from->glyphs[RIGHT_MARGIN_AREA]);
3138 memcpy (to->glyphs[RIGHT_MARGIN_AREA],
3139 from->glyphs[RIGHT_MARGIN_AREA], nbytes);
3140 to->used[RIGHT_MARGIN_AREA] = from->used[RIGHT_MARGIN_AREA];
3142 else
3143 to->used[RIGHT_MARGIN_AREA] = 0;
3147 static void
3148 free_saved_screen (struct glyph_matrix *saved)
3150 int i;
3152 if (!saved)
3153 return; /* already freed */
3155 for (i = 0; i < saved->nrows; ++i)
3157 struct glyph_row *from = saved->rows + i;
3159 xfree (from->glyphs[TEXT_AREA]);
3160 if (from->used[LEFT_MARGIN_AREA])
3161 xfree (from->glyphs[LEFT_MARGIN_AREA]);
3162 if (from->used[RIGHT_MARGIN_AREA])
3163 xfree (from->glyphs[RIGHT_MARGIN_AREA]);
3166 xfree (saved->rows);
3167 xfree (saved);
3170 /* Update the display of frame F from its saved contents. */
3171 static void
3172 screen_update (struct frame *f, struct glyph_matrix *mtx)
3174 restore_desired_matrix (f, mtx);
3175 update_frame_with_menu (f);
3178 /* Read user input and return X and Y coordinates where that input
3179 puts us. We only consider mouse movement and click events and
3180 keyboard movement commands; the rest are ignored.
3182 Value is -1 if C-g was pressed, 1 if an item was selected, zero
3183 otherwise. */
3184 static int
3185 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3186 bool *first_time)
3188 if (*first_time)
3190 *first_time = false;
3191 /* FIXME: Following 2 or 3 lines are temporary! */
3192 menu_x = *x;
3193 menu_y = *y;
3194 sf->mouse_moved = 1;
3195 return 0;
3198 while (1)
3200 #if 1
3201 extern Lisp_Object read_menu_command (void);
3202 Lisp_Object cmd;
3203 int usable_input = 1;
3204 int st = 0;
3205 struct tty_display_info *tty = FRAME_TTY (sf);
3206 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3208 /* Signal the keyboard reading routines we are displaying a menu
3209 on this terminal. */
3210 tty->showing_menu = 1;
3211 /* We want mouse movements be reported by read_menu_command. */
3212 do_mouse_tracking = Qt;
3213 do {
3214 cmd = read_menu_command ();
3215 } while (NILP (cmd));
3216 tty->showing_menu = 0;
3217 do_mouse_tracking = saved_mouse_tracking;
3219 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit))
3220 return -1;
3221 if (EQ (cmd, Qtty_menu_mouse_movement))
3223 int mx, my;
3225 mouse_get_xy (&mx, &my);
3226 *x = mx;
3227 *y = my;
3229 else if (EQ (cmd, Qtty_menu_next_menu))
3230 *x += 1;
3231 else if (EQ (cmd, Qtty_menu_prev_menu))
3232 *x -= 1;
3233 else if (EQ (cmd, Qtty_menu_next_item))
3235 if (*y < max_y)
3236 *y += 1;
3238 else if (EQ (cmd, Qtty_menu_prev_item))
3240 if (*y > min_y)
3241 *y -= 1;
3243 else if (EQ (cmd, Qtty_menu_select))
3244 st = 1;
3245 else if (!EQ (cmd, Qtty_menu_ignore))
3246 usable_input = 0;
3247 if (usable_input)
3248 sf->mouse_moved = 1;
3249 #else
3250 int volatile dx = 0;
3251 int volatile dy = 0;
3252 int volatile st = 0;
3254 *x += dx;
3255 *y += dy;
3256 if (dx != 0 || dy != 0)
3257 sf->mouse_moved = 1;
3258 Sleep (300);
3259 #endif
3260 menu_x = *x;
3261 menu_y = *y;
3262 return st;
3264 return 0;
3267 /* FIXME */
3268 static bool mouse_visible;
3269 static void
3270 mouse_off (void)
3272 mouse_visible = false;
3275 static void
3276 mouse_on (void)
3278 mouse_visible = true;
3281 static bool
3282 mouse_pressed (int b, int *x, int *y)
3284 return false;
3287 static bool
3288 mouse_button_depressed (int b, int *x, int *y)
3290 return false;
3293 static bool
3294 mouse_released (int b, int *x, int *y)
3296 return true;
3299 /* Display menu, wait for user's response, and return that response. */
3301 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3302 int x0, int y0, char **txt,
3303 void (*help_callback)(char const *, int, int))
3305 struct tty_menu_state *state;
3306 int statecount, x, y, i, b, leave, result, onepane;
3307 int title_faces[4]; /* face to display the menu title */
3308 int faces[4], buffers_num_deleted = 0;
3309 struct frame *sf = SELECTED_FRAME ();
3310 struct tty_display_info *tty = FRAME_TTY (sf);
3311 bool first_time;
3312 Lisp_Object saved_echo_area_message, selectface;
3314 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3315 around the display. */
3316 if (x0 <= 0)
3317 x0 = 1;
3318 if (y0 <= 0)
3319 y0 = 1;
3321 #if 0
3322 /* We will process all the mouse events directly. */
3323 mouse_preempted++;
3324 #endif
3326 state = alloca (menu->panecount * sizeof (struct tty_menu_state));
3327 memset (state, 0, sizeof (*state));
3328 faces[0]
3329 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3330 DEFAULT_FACE_ID, 1);
3331 faces[1]
3332 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3333 DEFAULT_FACE_ID, 1);
3334 selectface = intern ("tty-menu-selected-face");
3335 faces[2] = lookup_derived_face (sf, selectface,
3336 faces[0], 1);
3337 faces[3] = lookup_derived_face (sf, selectface,
3338 faces[1], 1);
3340 /* Make sure the menu title is always displayed with
3341 `tty-menu-selected-face', no matter where the mouse pointer is. */
3342 for (i = 0; i < 4; i++)
3343 title_faces[i] = faces[3];
3345 statecount = 1;
3347 /* Don't let the title for the "Buffers" popup menu include a
3348 digit (which is ugly).
3350 This is a terrible kludge, but I think the "Buffers" case is
3351 the only one where the title includes a number, so it doesn't
3352 seem to be necessary to make this more general. */
3353 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3355 menu->text[0][7] = '\0';
3356 buffers_num_deleted = 1;
3359 #if 0
3360 /* We need to save the current echo area message, so that we could
3361 restore it below, before we exit. See the commentary below,
3362 before the call to message_with_string. */
3363 saved_echo_area_message = Fcurrent_message ();
3364 #endif
3365 /* Force update of the current frame, so that the desired and the
3366 current matrices are identical. */
3367 update_frame_with_menu (sf);
3368 state[0].menu = menu;
3369 mouse_off (); /* FIXME */
3370 state[0].screen_behind = save_and_enable_current_matrix (sf);
3372 /* Turn off the cursor. Otherwise it shows through the menu
3373 panes, which is ugly. */
3374 tty_hide_cursor (tty);
3376 /* Display the menu title. We subtract 1 from x0 and y0 because we
3377 want to interpret them as zero-based column and row coordinates,
3378 and also because we want the first item of the menu, not its
3379 title, to appear at x0,y0. */
3380 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0);
3381 if (buffers_num_deleted)
3382 menu->text[0][7] = ' ';
3383 if ((onepane = menu->count == 1 && menu->submenu[0]))
3385 menu->width = menu->submenu[0]->width;
3386 state[0].menu = menu->submenu[0];
3388 else
3390 state[0].menu = menu;
3392 state[0].x = x0 - 1;
3393 state[0].y = y0;
3394 state[0].pane = onepane;
3396 x = state[0].x;
3397 y = state[0].y;
3398 first_time = true;
3400 leave = 0;
3401 while (!leave)
3403 int mouse_button_count = 3; /* FIXME */
3404 int input_status;
3405 int min_y = state[0].y, max_y = min_y + state[0].menu->count - 1;
3407 if (!mouse_visible) mouse_on ();
3408 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3409 if (input_status)
3411 if (input_status == -1)
3413 /* Remove the last help-echo, so that it doesn't
3414 re-appear after "Quit". */
3415 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3416 result = TTYM_NO_SELECT;
3418 leave = 1;
3420 if (sf->mouse_moved && input_status != -1)
3422 sf->mouse_moved = 0;
3423 result = TTYM_IA_SELECT;
3424 for (i = 0; i < statecount; i++)
3425 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3427 int dy = y - state[i].y;
3428 if (0 <= dy && dy < state[i].menu->count)
3430 if (!state[i].menu->submenu[dy])
3432 if (state[i].menu->panenumber[dy])
3433 result = TTYM_SUCCESS;
3434 else
3435 result = TTYM_IA_SELECT;
3437 *pane = state[i].pane - 1;
3438 *selidx = dy;
3439 /* We hit some part of a menu, so drop extra menus that
3440 have been opened. That does not include an open and
3441 active submenu. */
3442 if (i != statecount - 2
3443 || state[i].menu->submenu[dy] != state[i+1].menu)
3444 while (i != statecount - 1)
3446 statecount--;
3447 mouse_off (); /* FIXME */
3448 screen_update (sf, state[statecount].screen_behind);
3449 state[statecount].screen_behind = NULL;
3451 if (i == statecount - 1 && state[i].menu->submenu[dy])
3453 tty_menu_display (state[i].menu,
3454 state[i].x,
3455 state[i].y,
3456 state[i].pane,
3457 faces, x, y, 1);
3458 state[statecount].menu = state[i].menu->submenu[dy];
3459 state[statecount].pane = state[i].menu->panenumber[dy];
3460 mouse_off (); /* FIXME */
3461 state[statecount].screen_behind
3462 = save_and_enable_current_matrix (sf);
3463 state[statecount].x
3464 = state[i].x + state[i].menu->width + 2;
3465 state[statecount].y = y;
3466 statecount++;
3470 tty_menu_display (state[statecount - 1].menu,
3471 state[statecount - 1].x,
3472 state[statecount - 1].y,
3473 state[statecount - 1].pane,
3474 faces, x, y, 1);
3477 /* Display the help-echo message for the currently-selected menu
3478 item. */
3479 if ((menu_help_message || prev_menu_help_message)
3480 && menu_help_message != prev_menu_help_message)
3482 help_callback (menu_help_message,
3483 menu_help_paneno, menu_help_itemno);
3484 tty_hide_cursor (tty);
3485 prev_menu_help_message = menu_help_message;
3487 #if 0
3488 /* We are busy-waiting for the mouse to move, so let's be nice
3489 to other Windows applications by releasing our time slice. */
3490 Sleep (20); /* FIXME */
3492 for (b = 0; b < mouse_button_count && !leave; b++)
3494 /* Only leave if user both pressed and released the mouse, and in
3495 that order. This avoids popping down the menu pane unless
3496 the user is really done with it. */
3497 if (mouse_pressed (b, &x, &y))
3499 while (mouse_button_depressed (b, &x, &y))
3500 Sleep (20); /* FIXME */
3501 leave = 1;
3503 (void) mouse_released (b, &x, &y);
3505 #endif
3508 mouse_off (); /* FIXME */
3509 sf->mouse_moved = 0;
3510 /* FIXME: Since we set the fram's garbaged flag, do we need this
3511 call to screen_update? */
3512 screen_update (sf, state[0].screen_behind);
3513 #if 0
3514 /* We have a situation here. ScreenUpdate has just restored the
3515 screen contents as it was before we started drawing this menu.
3516 That includes any echo area message that could have been
3517 displayed back then. (In reality, that echo area message will
3518 almost always be the ``keystroke echo'' that echoes the sequence
3519 of menu items chosen by the user.) However, if the menu had some
3520 help messages, then displaying those messages caused Emacs to
3521 forget about the original echo area message. So when
3522 ScreenUpdate restored it, it created a discrepancy between the
3523 actual screen contents and what Emacs internal data structures
3524 know about it.
3526 To avoid this conflict, we force Emacs to restore the original
3527 echo area message as we found it when we entered this function.
3528 The irony of this is that we then erase the restored message
3529 right away, so the only purpose of restoring it is so that
3530 erasing it works correctly... */
3531 if (! NILP (saved_echo_area_message))
3532 message_with_string ("%s", saved_echo_area_message, 0);
3533 message (0);
3534 #endif
3535 while (statecount--)
3536 free_saved_screen (state[statecount].screen_behind);
3537 tty_show_cursor (tty); /* turn cursor back on */
3539 /* Clean up any mouse events that are waiting inside Emacs event queue.
3540 These events are likely to be generated before the menu was even
3541 displayed, probably because the user pressed and released the button
3542 (which invoked the menu) too quickly. If we don't remove these events,
3543 Emacs will process them after we return and surprise the user. */
3544 discard_mouse_events ();
3545 #if 0
3546 mouse_clear_clicks ();
3547 #endif
3548 if (!kbd_buffer_events_waiting ())
3549 clear_input_pending ();
3550 #if 0
3551 /* Allow mouse events generation by dos_rawgetc. */
3552 mouse_preempted--;
3553 #endif
3554 SET_FRAME_GARBAGED (sf);
3555 return result;
3558 /* Dispose of a menu. */
3560 void
3561 tty_menu_destroy (tty_menu *menu)
3563 int i;
3564 if (menu->allocated)
3566 for (i = 0; i < menu->count; i++)
3567 if (menu->submenu[i])
3568 tty_menu_destroy (menu->submenu[i]);
3569 xfree (menu->text);
3570 xfree (menu->submenu);
3571 xfree (menu->panenumber);
3572 xfree (menu->help_text);
3574 xfree (menu);
3575 menu_help_message = prev_menu_help_message = NULL;
3578 static struct frame *tty_menu_help_frame;
3580 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3582 PANE is the pane number, and ITEM is the menu item number in
3583 the menu (currently not used).
3585 This cannot be done with generating a HELP_EVENT because
3586 XMenuActivate contains a loop that doesn't let Emacs process
3587 keyboard events.
3589 FIXME: Do we need this in TTY menus? */
3591 static void
3592 tty_menu_help_callback (char const *help_string, int pane, int item)
3594 Lisp_Object *first_item;
3595 Lisp_Object pane_name;
3596 Lisp_Object menu_object;
3598 first_item = XVECTOR (menu_items)->contents;
3599 if (EQ (first_item[0], Qt))
3600 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3601 else if (EQ (first_item[0], Qquote))
3602 /* This shouldn't happen, see xmenu_show. */
3603 pane_name = empty_unibyte_string;
3604 else
3605 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3607 /* (menu-item MENU-NAME PANE-NUMBER) */
3608 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3609 show_help_echo (help_string ? build_string (help_string) : Qnil,
3610 Qnil, menu_object, make_number (item));
3613 static void
3614 tty_pop_down_menu (Lisp_Object arg)
3616 tty_menu *menu = XSAVE_POINTER (arg, 0);
3618 block_input ();
3619 tty_menu_destroy (menu);
3620 unblock_input ();
3623 Lisp_Object
3624 tty_menu_show (struct frame *f, int x, int y, int for_click, int keymaps,
3625 Lisp_Object title, const char **error_name)
3627 tty_menu *menu;
3628 int pane, selidx, lpane, status;
3629 Lisp_Object entry, pane_prefix;
3630 char *datap;
3631 int ulx, uly, width, height;
3632 int dispwidth, dispheight;
3633 int i, j, lines, maxlines;
3634 int maxwidth;
3635 int dummy_int;
3636 unsigned int dummy_uint;
3637 ptrdiff_t specpdl_count = SPECPDL_INDEX ();
3639 if (! FRAME_TERMCAP_P (f))
3640 emacs_abort ();
3642 *error_name = 0;
3643 if (menu_items_n_panes == 0)
3644 return Qnil;
3646 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3648 *error_name = "Empty menu";
3649 return Qnil;
3652 /* Make the menu on that window. */
3653 menu = tty_menu_create ();
3654 if (menu == NULL)
3656 *error_name = "Can't create menu";
3657 return Qnil;
3660 /* Don't GC while we prepare and show the menu, because we give the
3661 menu functions pointers to the contents of strings. */
3662 inhibit_garbage_collection ();
3664 /* Adjust coordinates to be root-window-relative. */
3665 x += f->left_pos;
3666 y += f->top_pos;
3668 /* Create all the necessary panes and their items. */
3669 maxwidth = maxlines = lines = i = 0;
3670 lpane = TTYM_FAILURE;
3671 while (i < menu_items_used)
3673 if (EQ (AREF (menu_items, i), Qt))
3675 /* Create a new pane. */
3676 Lisp_Object pane_name, prefix;
3677 const char *pane_string;
3679 maxlines = max (maxlines, lines);
3680 lines = 0;
3681 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3682 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3683 pane_string = (NILP (pane_name)
3684 ? "" : SSDATA (pane_name));
3685 if (keymaps && !NILP (prefix))
3686 pane_string++;
3688 lpane = tty_menu_add_pane (menu, pane_string);
3689 if (lpane == TTYM_FAILURE)
3691 tty_menu_destroy (menu);
3692 *error_name = "Can't create pane";
3693 return Qnil;
3695 i += MENU_ITEMS_PANE_LENGTH;
3697 /* Find the width of the widest item in this pane. */
3698 j = i;
3699 while (j < menu_items_used)
3701 Lisp_Object item;
3702 item = AREF (menu_items, j);
3703 if (EQ (item, Qt))
3704 break;
3705 if (NILP (item))
3707 j++;
3708 continue;
3710 width = SBYTES (item);
3711 if (width > maxwidth)
3712 maxwidth = width;
3714 j += MENU_ITEMS_ITEM_LENGTH;
3717 /* Ignore a nil in the item list.
3718 It's meaningful only for dialog boxes. */
3719 else if (EQ (AREF (menu_items, i), Qquote))
3720 i += 1;
3721 else
3723 /* Create a new item within current pane. */
3724 Lisp_Object item_name, enable, descrip, help;
3725 char *item_data;
3726 char const *help_string;
3728 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3729 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3730 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3731 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3732 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3734 if (!NILP (descrip))
3736 /* if alloca is fast, use that to make the space,
3737 to reduce gc needs. */
3738 item_data = (char *) alloca (maxwidth + SBYTES (descrip) + 1);
3739 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3740 for (j = SCHARS (item_name); j < maxwidth; j++)
3741 item_data[j] = ' ';
3742 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3743 item_data[j + SBYTES (descrip)] = 0;
3745 else
3746 item_data = SSDATA (item_name);
3748 if (lpane == TTYM_FAILURE
3749 || (tty_menu_add_selection (menu, lpane, item_data,
3750 !NILP (enable), help_string)
3751 == TTYM_FAILURE))
3753 tty_menu_destroy (menu);
3754 *error_name = "Can't add selection to menu";
3755 return Qnil;
3757 i += MENU_ITEMS_ITEM_LENGTH;
3758 lines++;
3762 maxlines = max (maxlines, lines);
3764 /* All set and ready to fly. */
3765 dispwidth = f->text_cols;
3766 dispheight = f->text_lines;
3767 x = min (x, dispwidth);
3768 y = min (y, dispheight);
3769 x = max (x, 1);
3770 y = max (y, 1);
3771 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3772 if (ulx+width > dispwidth)
3774 x -= (ulx + width) - dispwidth;
3775 ulx = dispwidth - width;
3777 if (uly+height > dispheight)
3779 y -= (uly + height) - dispheight;
3780 uly = dispheight - height;
3783 if (FRAME_HAS_MINIBUF_P (f) && uly+height > dispheight - 2)
3785 /* Move the menu away of the echo area, to avoid overwriting the
3786 menu with help echo messages or vice versa. */
3787 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3789 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3790 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3792 else
3794 y -= 2;
3795 uly -= 2;
3799 if (ulx < 0) x -= ulx;
3800 if (uly < 0) y -= uly;
3802 #if 0
3803 /* This code doesn't make sense on a TTY, since it can easily annul
3804 the adjustments above that carefully avoid truncation of the menu
3805 items. */
3806 if (! for_click)
3808 /* If position was not given by a mouse click, adjust so upper left
3809 corner of the menu as a whole ends up at given coordinates. This
3810 is what x-popup-menu says in its documentation. */
3811 x += width/2;
3812 y += 1.5*height/(maxlines+2);
3814 #endif
3816 pane = selidx = 0;
3818 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3820 tty_menu_help_frame = f; /* FIXME: This seems unused. */
3821 specbind (Qoverriding_terminal_local_map,
3822 Fsymbol_value (Qtty_menu_navigation_map));
3823 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3824 tty_menu_help_callback);
3825 entry = pane_prefix = Qnil;
3827 switch (status)
3829 case TTYM_SUCCESS:
3830 /* Find the item number SELIDX in pane number PANE. */
3831 i = 0;
3832 while (i < menu_items_used)
3834 if (EQ (AREF (menu_items, i), Qt))
3836 if (pane == 0)
3837 pane_prefix
3838 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3839 pane--;
3840 i += MENU_ITEMS_PANE_LENGTH;
3842 else
3844 if (pane == -1)
3846 if (selidx == 0)
3848 entry
3849 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3850 if (keymaps != 0)
3852 entry = Fcons (entry, Qnil);
3853 if (!NILP (pane_prefix))
3854 entry = Fcons (pane_prefix, entry);
3856 break;
3858 selidx--;
3860 i += MENU_ITEMS_ITEM_LENGTH;
3863 break;
3865 case TTYM_FAILURE:
3866 *error_name = "Can't activate menu";
3867 case TTYM_IA_SELECT:
3868 break;
3869 case TTYM_NO_SELECT:
3870 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3871 the menu was invoked with a mouse event as POSITION). */
3872 if (! for_click)
3873 Fsignal (Qquit, Qnil);
3874 break;
3877 unbind_to (specpdl_count, Qnil);
3879 return entry;
3882 #endif /* HAVE_MENUS && !MSDOS */
3885 #ifndef MSDOS
3886 /***********************************************************************
3887 Initialization
3888 ***********************************************************************/
3890 /* Initialize the tty-dependent part of frame F. The frame must
3891 already have its device initialized. */
3893 void
3894 create_tty_output (struct frame *f)
3896 struct tty_output *t = xzalloc (sizeof *t);
3898 eassert (FRAME_TERMCAP_P (f));
3900 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3902 f->output_data.tty = t;
3905 /* Delete frame F's face cache, and its tty-dependent part. */
3907 static void
3908 tty_free_frame_resources (struct frame *f)
3910 eassert (FRAME_TERMCAP_P (f));
3912 if (FRAME_FACE_CACHE (f))
3913 free_frame_faces (f);
3915 xfree (f->output_data.tty);
3918 #else /* MSDOS */
3920 /* Delete frame F's face cache. */
3922 static void
3923 tty_free_frame_resources (struct frame *f)
3925 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3927 if (FRAME_FACE_CACHE (f))
3928 free_frame_faces (f);
3930 #endif /* MSDOS */
3932 /* Reset the hooks in TERMINAL. */
3934 static void
3935 clear_tty_hooks (struct terminal *terminal)
3937 terminal->rif = 0;
3938 terminal->cursor_to_hook = 0;
3939 terminal->raw_cursor_to_hook = 0;
3940 terminal->clear_to_end_hook = 0;
3941 terminal->clear_frame_hook = 0;
3942 terminal->clear_end_of_line_hook = 0;
3943 terminal->ins_del_lines_hook = 0;
3944 terminal->insert_glyphs_hook = 0;
3945 terminal->write_glyphs_hook = 0;
3946 terminal->delete_glyphs_hook = 0;
3947 terminal->ring_bell_hook = 0;
3948 terminal->reset_terminal_modes_hook = 0;
3949 terminal->set_terminal_modes_hook = 0;
3950 terminal->update_begin_hook = 0;
3951 terminal->update_end_hook = 0;
3952 terminal->set_terminal_window_hook = 0;
3953 terminal->mouse_position_hook = 0;
3954 terminal->frame_rehighlight_hook = 0;
3955 terminal->frame_raise_lower_hook = 0;
3956 terminal->fullscreen_hook = 0;
3957 terminal->set_vertical_scroll_bar_hook = 0;
3958 terminal->condemn_scroll_bars_hook = 0;
3959 terminal->redeem_scroll_bar_hook = 0;
3960 terminal->judge_scroll_bars_hook = 0;
3961 terminal->read_socket_hook = 0;
3962 terminal->frame_up_to_date_hook = 0;
3964 /* Leave these two set, or suspended frames are not deleted
3965 correctly. */
3966 terminal->delete_frame_hook = &tty_free_frame_resources;
3967 terminal->delete_terminal_hook = &delete_tty;
3970 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3972 static void
3973 set_tty_hooks (struct terminal *terminal)
3975 terminal->rif = 0; /* ttys don't support window-based redisplay. */
3977 terminal->cursor_to_hook = &tty_cursor_to;
3978 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3980 terminal->clear_to_end_hook = &tty_clear_to_end;
3981 terminal->clear_frame_hook = &tty_clear_frame;
3982 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3984 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3986 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3987 terminal->write_glyphs_hook = &tty_write_glyphs;
3988 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3990 terminal->ring_bell_hook = &tty_ring_bell;
3992 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3993 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3994 terminal->update_begin_hook = 0; /* Not needed. */
3995 terminal->update_end_hook = &tty_update_end;
3996 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3998 terminal->mouse_position_hook = 0; /* Not needed. */
3999 terminal->frame_rehighlight_hook = 0; /* Not needed. */
4000 terminal->frame_raise_lower_hook = 0; /* Not needed. */
4002 terminal->set_vertical_scroll_bar_hook = 0; /* Not needed. */
4003 terminal->condemn_scroll_bars_hook = 0; /* Not needed. */
4004 terminal->redeem_scroll_bar_hook = 0; /* Not needed. */
4005 terminal->judge_scroll_bars_hook = 0; /* Not needed. */
4007 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
4008 terminal->frame_up_to_date_hook = 0; /* Not needed. */
4010 terminal->delete_frame_hook = &tty_free_frame_resources;
4011 terminal->delete_terminal_hook = &delete_tty;
4014 /* If FD is the controlling terminal, drop it. */
4015 static void
4016 dissociate_if_controlling_tty (int fd)
4018 /* If tcgetpgrp succeeds, fd is the controlling terminal,
4019 so dissociate it by invoking setsid. */
4020 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
4022 #ifdef TIOCNOTTY
4023 /* setsid failed, presumably because Emacs is already a process
4024 group leader. Fall back on the obsolescent way to dissociate
4025 a controlling tty. */
4026 block_tty_out_signal ();
4027 ioctl (fd, TIOCNOTTY, 0);
4028 unblock_tty_out_signal ();
4029 #endif
4033 /* Create a termcap display on the tty device with the given name and
4034 type.
4036 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
4037 Otherwise NAME should be a path to the tty device file,
4038 e.g. "/dev/pts/7".
4040 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
4042 If MUST_SUCCEED is true, then all errors are fatal. */
4044 struct terminal *
4045 init_tty (const char *name, const char *terminal_type, bool must_succeed)
4047 char *area;
4048 char **address = &area;
4049 int status;
4050 struct tty_display_info *tty = NULL;
4051 struct terminal *terminal = NULL;
4052 bool ctty = false; /* True if asked to open controlling tty. */
4054 if (!terminal_type)
4055 maybe_fatal (must_succeed, 0,
4056 "Unknown terminal type",
4057 "Unknown terminal type");
4059 if (name == NULL)
4060 name = DEV_TTY;
4061 if (!strcmp (name, DEV_TTY))
4062 ctty = 1;
4064 /* If we already have a terminal on the given device, use that. If
4065 all such terminals are suspended, create a new one instead. */
4066 /* XXX Perhaps this should be made explicit by having init_tty
4067 always create a new terminal and separating terminal and frame
4068 creation on Lisp level. */
4069 terminal = get_named_tty (name);
4070 if (terminal)
4071 return terminal;
4073 terminal = create_terminal ();
4074 #ifdef MSDOS
4075 if (been_here > 0)
4076 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
4077 name, "");
4078 been_here = 1;
4079 tty = &the_only_display_info;
4080 #else
4081 tty = xzalloc (sizeof *tty);
4082 #endif
4083 tty->top_frame = Qnil;
4084 tty->next = tty_list;
4085 tty_list = tty;
4087 terminal->type = output_termcap;
4088 terminal->display_info.tty = tty;
4089 tty->terminal = terminal;
4091 tty->Wcm = xmalloc (sizeof *tty->Wcm);
4092 Wcm_clear (tty);
4094 encode_terminal_src_size = 0;
4095 encode_terminal_dst_size = 0;
4098 #ifndef DOS_NT
4099 set_tty_hooks (terminal);
4102 /* Open the terminal device. */
4104 /* If !ctty, don't recognize it as our controlling terminal, and
4105 don't make it the controlling tty if we don't have one now.
4107 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
4108 defined on Hurd. On other systems, we need to explicitly
4109 dissociate ourselves from the controlling tty when we want to
4110 open a frame on the same terminal. */
4111 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
4112 int fd = emacs_open (name, flags, 0);
4113 tty->input = tty->output = fd < 0 || ! isatty (fd) ? 0 : fdopen (fd, "w+");
4115 if (! tty->input)
4117 char const *diagnostic
4118 = tty->input ? "Not a tty device: %s" : "Could not open file: %s";
4119 emacs_close (fd);
4120 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
4123 tty->name = xstrdup (name);
4124 terminal->name = xstrdup (name);
4126 if (!O_IGNORE_CTTY && !ctty)
4127 dissociate_if_controlling_tty (fd);
4130 tty->type = xstrdup (terminal_type);
4132 add_keyboard_wait_descriptor (fileno (tty->input));
4134 Wcm_clear (tty);
4136 /* On some systems, tgetent tries to access the controlling
4137 terminal. */
4138 block_tty_out_signal ();
4139 status = tgetent (tty->termcap_term_buffer, terminal_type);
4140 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4141 emacs_abort ();
4142 unblock_tty_out_signal ();
4144 if (status < 0)
4146 #ifdef TERMINFO
4147 maybe_fatal (must_succeed, terminal,
4148 "Cannot open terminfo database file",
4149 "Cannot open terminfo database file");
4150 #else
4151 maybe_fatal (must_succeed, terminal,
4152 "Cannot open termcap database file",
4153 "Cannot open termcap database file");
4154 #endif
4156 if (status == 0)
4158 maybe_fatal (must_succeed, terminal,
4159 "Terminal type %s is not defined",
4160 "Terminal type %s is not defined.\n\
4161 If that is not the actual type of terminal you have,\n\
4162 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4163 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4164 #ifdef TERMINFO
4165 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4166 #else
4167 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4168 #endif
4169 terminal_type);
4172 area = tty->termcap_strings_buffer;
4173 tty->TS_ins_line = tgetstr ("al", address);
4174 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4175 tty->TS_bell = tgetstr ("bl", address);
4176 BackTab (tty) = tgetstr ("bt", address);
4177 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4178 tty->TS_clr_line = tgetstr ("ce", address);
4179 tty->TS_clr_frame = tgetstr ("cl", address);
4180 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4181 AbsPosition (tty) = tgetstr ("cm", address);
4182 CR (tty) = tgetstr ("cr", address);
4183 tty->TS_set_scroll_region = tgetstr ("cs", address);
4184 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4185 RowPosition (tty) = tgetstr ("cv", address);
4186 tty->TS_del_char = tgetstr ("dc", address);
4187 tty->TS_del_multi_chars = tgetstr ("DC", address);
4188 tty->TS_del_line = tgetstr ("dl", address);
4189 tty->TS_del_multi_lines = tgetstr ("DL", address);
4190 tty->TS_delete_mode = tgetstr ("dm", address);
4191 tty->TS_end_delete_mode = tgetstr ("ed", address);
4192 tty->TS_end_insert_mode = tgetstr ("ei", address);
4193 Home (tty) = tgetstr ("ho", address);
4194 tty->TS_ins_char = tgetstr ("ic", address);
4195 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4196 tty->TS_insert_mode = tgetstr ("im", address);
4197 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4198 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4199 tty->TS_keypad_mode = tgetstr ("ks", address);
4200 LastLine (tty) = tgetstr ("ll", address);
4201 Right (tty) = tgetstr ("nd", address);
4202 Down (tty) = tgetstr ("do", address);
4203 if (!Down (tty))
4204 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4205 if (tgetflag ("bs"))
4206 Left (tty) = "\b"; /* Can't possibly be longer! */
4207 else /* (Actually, "bs" is obsolete...) */
4208 Left (tty) = tgetstr ("le", address);
4209 if (!Left (tty))
4210 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4211 tty->TS_pad_char = tgetstr ("pc", address);
4212 tty->TS_repeat = tgetstr ("rp", address);
4213 tty->TS_end_standout_mode = tgetstr ("se", address);
4214 tty->TS_fwd_scroll = tgetstr ("sf", address);
4215 tty->TS_standout_mode = tgetstr ("so", address);
4216 tty->TS_rev_scroll = tgetstr ("sr", address);
4217 tty->Wcm->cm_tab = tgetstr ("ta", address);
4218 tty->TS_end_termcap_modes = tgetstr ("te", address);
4219 tty->TS_termcap_modes = tgetstr ("ti", address);
4220 Up (tty) = tgetstr ("up", address);
4221 tty->TS_visible_bell = tgetstr ("vb", address);
4222 tty->TS_cursor_normal = tgetstr ("ve", address);
4223 tty->TS_cursor_visible = tgetstr ("vs", address);
4224 tty->TS_cursor_invisible = tgetstr ("vi", address);
4225 tty->TS_set_window = tgetstr ("wi", address);
4227 tty->TS_enter_underline_mode = tgetstr ("us", address);
4228 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4229 tty->TS_enter_bold_mode = tgetstr ("md", address);
4230 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4231 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4232 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4233 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4234 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4235 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4237 MultiUp (tty) = tgetstr ("UP", address);
4238 MultiDown (tty) = tgetstr ("DO", address);
4239 MultiLeft (tty) = tgetstr ("LE", address);
4240 MultiRight (tty) = tgetstr ("RI", address);
4242 /* SVr4/ANSI color support. If "op" isn't available, don't support
4243 color because we can't switch back to the default foreground and
4244 background. */
4245 tty->TS_orig_pair = tgetstr ("op", address);
4246 if (tty->TS_orig_pair)
4248 tty->TS_set_foreground = tgetstr ("AF", address);
4249 tty->TS_set_background = tgetstr ("AB", address);
4250 if (!tty->TS_set_foreground)
4252 /* SVr4. */
4253 tty->TS_set_foreground = tgetstr ("Sf", address);
4254 tty->TS_set_background = tgetstr ("Sb", address);
4257 tty->TN_max_colors = tgetnum ("Co");
4258 tty->TN_max_pairs = tgetnum ("pa");
4260 tty->TN_no_color_video = tgetnum ("NC");
4261 if (tty->TN_no_color_video == -1)
4262 tty->TN_no_color_video = 0;
4265 tty_default_color_capabilities (tty, 1);
4267 MagicWrap (tty) = tgetflag ("xn");
4268 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4269 the former flag imply the latter. */
4270 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4271 terminal->memory_below_frame = tgetflag ("db");
4272 tty->TF_hazeltine = tgetflag ("hz");
4273 terminal->must_write_spaces = tgetflag ("in");
4274 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4275 tty->TF_insmode_motion = tgetflag ("mi");
4276 tty->TF_standout_motion = tgetflag ("ms");
4277 tty->TF_underscore = tgetflag ("ul");
4278 tty->TF_teleray = tgetflag ("xt");
4280 #else /* DOS_NT */
4281 #ifdef WINDOWSNT
4283 struct frame *f = XFRAME (selected_frame);
4284 int height, width;
4286 initialize_w32_display (terminal, &width, &height);
4288 FrameRows (tty) = height;
4289 FrameCols (tty) = width;
4290 tty->specified_window = height;
4292 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4293 terminal->char_ins_del_ok = 1;
4294 baud_rate = 19200;
4296 #else /* MSDOS */
4298 int height, width;
4299 if (strcmp (terminal_type, "internal") == 0)
4300 terminal->type = output_msdos_raw;
4301 initialize_msdos_display (terminal);
4303 get_tty_size (fileno (tty->input), &width, &height);
4304 FrameCols (tty) = width;
4305 FrameRows (tty) = height;
4306 terminal->char_ins_del_ok = 0;
4307 init_baud_rate (fileno (tty->input));
4309 #endif /* MSDOS */
4310 tty->output = stdout;
4311 tty->input = stdin;
4312 /* The following two are inaccessible from w32console.c. */
4313 terminal->delete_frame_hook = &tty_free_frame_resources;
4314 terminal->delete_terminal_hook = &delete_tty;
4316 tty->name = xstrdup (name);
4317 terminal->name = xstrdup (name);
4318 tty->type = xstrdup (terminal_type);
4320 add_keyboard_wait_descriptor (0);
4322 tty->delete_in_insert_mode = 1;
4324 UseTabs (tty) = 0;
4325 terminal->scroll_region_ok = 0;
4327 /* Seems to insert lines when it's not supposed to, messing up the
4328 display. In doing a trace, it didn't seem to be called much, so I
4329 don't think we're losing anything by turning it off. */
4330 terminal->line_ins_del_ok = 0;
4332 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4333 #endif /* DOS_NT */
4335 #ifdef HAVE_GPM
4336 terminal->mouse_position_hook = term_mouse_position;
4337 tty->mouse_highlight.mouse_face_window = Qnil;
4338 #endif
4340 terminal->kboard = xmalloc (sizeof *terminal->kboard);
4341 init_kboard (terminal->kboard);
4342 kset_window_system (terminal->kboard, Qnil);
4343 terminal->kboard->next_kboard = all_kboards;
4344 all_kboards = terminal->kboard;
4345 terminal->kboard->reference_count++;
4346 /* Don't let the initial kboard remain current longer than necessary.
4347 That would cause problems if a file loaded on startup tries to
4348 prompt in the mini-buffer. */
4349 if (current_kboard == initial_kboard)
4350 current_kboard = terminal->kboard;
4351 #ifndef DOS_NT
4352 term_get_fkeys (address, terminal->kboard);
4354 /* Get frame size from system, or else from termcap. */
4356 int height, width;
4357 get_tty_size (fileno (tty->input), &width, &height);
4358 FrameCols (tty) = width;
4359 FrameRows (tty) = height;
4362 if (FrameCols (tty) <= 0)
4363 FrameCols (tty) = tgetnum ("co");
4364 if (FrameRows (tty) <= 0)
4365 FrameRows (tty) = tgetnum ("li");
4367 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4368 maybe_fatal (must_succeed, terminal,
4369 "Screen size %dx%d is too small",
4370 "Screen size %dx%d is too small",
4371 FrameCols (tty), FrameRows (tty));
4373 TabWidth (tty) = tgetnum ("tw");
4375 if (!tty->TS_bell)
4376 tty->TS_bell = "\07";
4378 if (!tty->TS_fwd_scroll)
4379 tty->TS_fwd_scroll = Down (tty);
4381 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4383 if (TabWidth (tty) < 0)
4384 TabWidth (tty) = 8;
4386 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4387 and newer termcap doc does not seem to say there is a default.
4388 if (!tty->Wcm->cm_tab)
4389 tty->Wcm->cm_tab = "\t";
4392 /* We don't support standout modes that use `magic cookies', so
4393 turn off any that do. */
4394 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4396 tty->TS_standout_mode = 0;
4397 tty->TS_end_standout_mode = 0;
4399 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4401 tty->TS_enter_underline_mode = 0;
4402 tty->TS_exit_underline_mode = 0;
4405 /* If there's no standout mode, try to use underlining instead. */
4406 if (tty->TS_standout_mode == 0)
4408 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4409 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4412 /* If no `se' string, try using a `me' string instead.
4413 If that fails, we can't use standout mode at all. */
4414 if (tty->TS_end_standout_mode == 0)
4416 char *s = tgetstr ("me", address);
4417 if (s != 0)
4418 tty->TS_end_standout_mode = s;
4419 else
4420 tty->TS_standout_mode = 0;
4423 if (tty->TF_teleray)
4425 tty->Wcm->cm_tab = 0;
4426 /* We can't support standout mode, because it uses magic cookies. */
4427 tty->TS_standout_mode = 0;
4428 /* But that means we cannot rely on ^M to go to column zero! */
4429 CR (tty) = 0;
4430 /* LF can't be trusted either -- can alter hpos. */
4431 /* If move at column 0 thru a line with TS_standout_mode. */
4432 Down (tty) = 0;
4435 tty->specified_window = FrameRows (tty);
4437 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4439 maybe_fatal (must_succeed, terminal,
4440 "Terminal type \"%s\" is not powerful enough to run Emacs",
4441 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4442 It lacks the ability to position the cursor.\n\
4443 If that is not the actual type of terminal you have,\n\
4444 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4445 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4446 # ifdef TERMINFO
4447 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4448 # else /* TERMCAP */
4449 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4450 # endif /* TERMINFO */
4451 terminal_type);
4454 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4455 maybe_fatal (must_succeed, terminal,
4456 "Could not determine the frame size",
4457 "Could not determine the frame size");
4459 tty->delete_in_insert_mode
4460 = tty->TS_delete_mode && tty->TS_insert_mode
4461 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4463 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4465 terminal->scroll_region_ok
4466 = (tty->Wcm->cm_abs
4467 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4469 terminal->line_ins_del_ok
4470 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4471 && (tty->TS_del_line || tty->TS_del_multi_lines))
4472 || (terminal->scroll_region_ok
4473 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4475 terminal->char_ins_del_ok
4476 = ((tty->TS_ins_char || tty->TS_insert_mode
4477 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4478 && (tty->TS_del_char || tty->TS_del_multi_chars));
4480 terminal->fast_clear_end_of_line = tty->TS_clr_line != 0;
4482 init_baud_rate (fileno (tty->input));
4484 #endif /* not DOS_NT */
4486 /* Init system terminal modes (RAW or CBREAK, etc.). */
4487 init_sys_modes (tty);
4489 return terminal;
4493 static void
4494 vfatal (const char *str, va_list ap)
4496 fprintf (stderr, "emacs: ");
4497 vfprintf (stderr, str, ap);
4498 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4499 fprintf (stderr, "\n");
4500 fflush (stderr);
4501 exit (1);
4505 /* Auxiliary error-handling function for init_tty.
4506 Delete TERMINAL, then call error or fatal with str1 or str2,
4507 respectively, according to whether MUST_SUCCEED is true. */
4509 static void
4510 maybe_fatal (bool must_succeed, struct terminal *terminal,
4511 const char *str1, const char *str2, ...)
4513 va_list ap;
4514 va_start (ap, str2);
4515 if (terminal)
4516 delete_tty (terminal);
4518 if (must_succeed)
4519 vfatal (str2, ap);
4520 else
4521 verror (str1, ap);
4524 void
4525 fatal (const char *str, ...)
4527 va_list ap;
4528 va_start (ap, str);
4529 vfatal (str, ap);
4534 /* Delete the given tty terminal, closing all frames on it. */
4536 static void
4537 delete_tty (struct terminal *terminal)
4539 struct tty_display_info *tty;
4541 /* Protect against recursive calls. delete_frame in
4542 delete_terminal calls us back when it deletes our last frame. */
4543 if (!terminal->name)
4544 return;
4546 eassert (terminal->type == output_termcap);
4548 tty = terminal->display_info.tty;
4550 if (tty == tty_list)
4551 tty_list = tty->next;
4552 else
4554 struct tty_display_info *p;
4555 for (p = tty_list; p && p->next != tty; p = p->next)
4558 if (! p)
4559 /* This should not happen. */
4560 emacs_abort ();
4562 p->next = tty->next;
4563 tty->next = 0;
4566 /* reset_sys_modes needs a valid device, so this call needs to be
4567 before delete_terminal. */
4568 reset_sys_modes (tty);
4570 delete_terminal (terminal);
4572 xfree (tty->name);
4573 xfree (tty->type);
4575 if (tty->input)
4577 delete_keyboard_wait_descriptor (fileno (tty->input));
4578 if (tty->input != stdin)
4579 fclose (tty->input);
4581 if (tty->output && tty->output != stdout && tty->output != tty->input)
4582 fclose (tty->output);
4583 if (tty->termscript)
4584 fclose (tty->termscript);
4586 xfree (tty->old_tty);
4587 xfree (tty->Wcm);
4588 xfree (tty);
4591 void
4592 syms_of_term (void)
4594 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4595 doc: /* Non-nil means the system uses terminfo rather than termcap.
4596 This variable can be used by terminal emulator packages. */);
4597 #ifdef TERMINFO
4598 system_uses_terminfo = 1;
4599 #else
4600 system_uses_terminfo = 0;
4601 #endif
4603 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4604 doc: /* Functions run after suspending a tty.
4605 The functions are run with one argument, the terminal object to be suspended.
4606 See `suspend-tty'. */);
4607 Vsuspend_tty_functions = Qnil;
4610 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4611 doc: /* Functions run after resuming a tty.
4612 The functions are run with one argument, the terminal object that was revived.
4613 See `resume-tty'. */);
4614 Vresume_tty_functions = Qnil;
4616 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4617 doc: /* Non-nil means to make the cursor very visible.
4618 This only has an effect when running in a text terminal.
4619 What means \"very visible\" is up to your terminal. It may make the cursor
4620 bigger, or it may make it blink, or it may do nothing at all. */);
4621 visible_cursor = 1;
4623 defsubr (&Stty_display_color_p);
4624 defsubr (&Stty_display_color_cells);
4625 defsubr (&Stty_no_underline);
4626 defsubr (&Stty_type);
4627 defsubr (&Scontrolling_tty_p);
4628 defsubr (&Stty_top_frame);
4629 defsubr (&Ssuspend_tty);
4630 defsubr (&Sresume_tty);
4631 #ifdef HAVE_GPM
4632 defsubr (&Sgpm_mouse_start);
4633 defsubr (&Sgpm_mouse_stop);
4634 #endif /* HAVE_GPM */
4636 #ifndef DOS_NT
4637 default_orig_pair = NULL;
4638 default_set_foreground = NULL;
4639 default_set_background = NULL;
4640 #endif /* !DOS_NT */
4642 encode_terminal_src = NULL;
4643 encode_terminal_dst = NULL;
4645 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4646 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4647 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4648 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4649 DEFSYM (Qtty_menu_select, "tty-menu-select");
4650 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4651 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4652 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4653 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");