NEWS: Document `comment-line'.
[emacs.git] / src / term.c
blob15d33b4e3ee48986c664902ba06f35102024af0c
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2015 Free Software
3 Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <sys/file.h>
27 #include <sys/time.h>
28 #include <unistd.h>
30 #include "lisp.h"
31 #include "termchar.h"
32 #include "tparam.h"
33 #include "character.h"
34 #include "buffer.h"
35 #include "charset.h"
36 #include "coding.h"
37 #include "composite.h"
38 #include "keyboard.h"
39 #include "frame.h"
40 #include "disptab.h"
41 #include "termhooks.h"
42 #include "dispextern.h"
43 #include "window.h"
44 #include "keymap.h"
45 #include "blockinput.h"
46 #include "syssignal.h"
47 #include "systty.h"
48 #include "intervals.h"
49 #ifdef MSDOS
50 #include "msdos.h"
51 static int been_here = -1;
52 #endif
54 #ifdef USE_X_TOOLKIT
55 #include "../lwlib/lwlib.h"
56 #endif
58 #include "cm.h"
59 #ifdef HAVE_X_WINDOWS
60 #include "xterm.h"
61 #endif
63 #include "menu.h"
65 /* The name of the default console device. */
66 #ifdef WINDOWSNT
67 #define DEV_TTY "CONOUT$"
68 #include "w32term.h"
69 #else
70 #define DEV_TTY "/dev/tty"
71 #endif
73 static void tty_set_scroll_region (struct frame *f, int start, int stop);
74 static void turn_on_face (struct frame *, int face_id);
75 static void turn_off_face (struct frame *, int face_id);
76 static void tty_turn_off_highlight (struct tty_display_info *);
77 static void tty_show_cursor (struct tty_display_info *);
78 static void tty_hide_cursor (struct tty_display_info *);
79 static void tty_background_highlight (struct tty_display_info *tty);
80 static void clear_tty_hooks (struct terminal *terminal);
81 static void set_tty_hooks (struct terminal *terminal);
82 static void dissociate_if_controlling_tty (int fd);
83 static void delete_tty (struct terminal *);
84 static _Noreturn void maybe_fatal (bool, struct terminal *,
85 const char *, const char *, ...)
86 ATTRIBUTE_FORMAT_PRINTF (3, 5) ATTRIBUTE_FORMAT_PRINTF (4, 5);
87 static _Noreturn void vfatal (const char *str, va_list ap)
88 ATTRIBUTE_FORMAT_PRINTF (1, 0);
91 #define OUTPUT(tty, a) \
92 emacs_tputs ((tty), a, \
93 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
94 cmputc)
96 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
97 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
99 #define OUTPUT_IF(tty, a) \
100 do { \
101 if (a) \
102 OUTPUT (tty, a); \
103 } while (0)
105 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
107 /* Display space properties. */
109 /* Chain of all tty device parameters. */
110 struct tty_display_info *tty_list;
112 /* Meaning of bits in no_color_video. Each bit set means that the
113 corresponding attribute cannot be combined with colors. */
115 enum no_color_bit
117 NC_STANDOUT = 1 << 0,
118 NC_UNDERLINE = 1 << 1,
119 NC_REVERSE = 1 << 2,
120 NC_ITALIC = 1 << 3,
121 NC_DIM = 1 << 4,
122 NC_BOLD = 1 << 5,
123 NC_INVIS = 1 << 6,
124 NC_PROTECT = 1 << 7
127 /* internal state */
129 /* The largest frame width in any call to calculate_costs. */
131 static int max_frame_cols;
135 #ifdef HAVE_GPM
136 #include <sys/fcntl.h>
138 /* The device for which we have enabled gpm support (or NULL). */
139 struct tty_display_info *gpm_tty = NULL;
141 /* Last recorded mouse coordinates. */
142 static int last_mouse_x, last_mouse_y;
143 #endif /* HAVE_GPM */
145 /* Ring the bell on a tty. */
147 static void
148 tty_ring_bell (struct frame *f)
150 struct tty_display_info *tty = FRAME_TTY (f);
152 if (tty->output)
154 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
155 ? tty->TS_visible_bell
156 : tty->TS_bell));
157 fflush (tty->output);
161 /* Set up termcap modes for Emacs. */
163 static void
164 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
166 Lisp_Object lisp_terminal;
167 Lisp_Object extra_codes;
168 struct tty_display_info *tty = terminal->display_info.tty;
170 XSETTERMINAL (lisp_terminal, terminal);
171 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
172 CONSP (extra_codes);
173 extra_codes = XCDR (extra_codes))
175 Lisp_Object string = XCAR (extra_codes);
176 if (STRINGP (string))
178 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
179 if (tty->termscript)
180 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
185 static void
186 tty_set_terminal_modes (struct terminal *terminal)
188 struct tty_display_info *tty = terminal->display_info.tty;
190 if (tty->output)
192 if (tty->TS_termcap_modes)
193 OUTPUT (tty, tty->TS_termcap_modes);
194 else
196 /* Output enough newlines to scroll all the old screen contents
197 off the screen, so it won't be overwritten and lost. */
198 int i;
199 current_tty = tty;
200 for (i = 0; i < FRAME_TOTAL_LINES (XFRAME (selected_frame)); i++)
201 cmputc ('\n');
204 OUTPUT_IF (tty, visible_cursor ? tty->TS_cursor_visible : tty->TS_cursor_normal);
205 OUTPUT_IF (tty, tty->TS_keypad_mode);
206 losecursor (tty);
207 tty_send_additional_strings (terminal, Qtty_mode_set_strings);
208 fflush (tty->output);
212 /* Reset termcap modes before exiting Emacs. */
214 static void
215 tty_reset_terminal_modes (struct terminal *terminal)
217 struct tty_display_info *tty = terminal->display_info.tty;
219 if (tty->output)
221 tty_send_additional_strings (terminal, Qtty_mode_reset_strings);
222 tty_turn_off_highlight (tty);
223 tty_turn_off_insert (tty);
224 OUTPUT_IF (tty, tty->TS_end_keypad_mode);
225 OUTPUT_IF (tty, tty->TS_cursor_normal);
226 OUTPUT_IF (tty, tty->TS_end_termcap_modes);
227 OUTPUT_IF (tty, tty->TS_orig_pair);
228 /* Output raw CR so kernel can track the cursor hpos. */
229 current_tty = tty;
230 cmputc ('\r');
231 fflush (tty->output);
235 /* Flag the end of a display update on a termcap terminal. */
237 static void
238 tty_update_end (struct frame *f)
240 struct tty_display_info *tty = FRAME_TTY (f);
242 if (!XWINDOW (selected_window)->cursor_off_p)
243 tty_show_cursor (tty);
244 tty_turn_off_insert (tty);
245 tty_background_highlight (tty);
246 fflush (tty->output);
249 /* The implementation of set_terminal_window for termcap frames. */
251 static void
252 tty_set_terminal_window (struct frame *f, int size)
254 struct tty_display_info *tty = FRAME_TTY (f);
256 tty->specified_window = size ? size : FRAME_TOTAL_LINES (f);
257 if (FRAME_SCROLL_REGION_OK (f))
258 tty_set_scroll_region (f, 0, tty->specified_window);
261 static void
262 tty_set_scroll_region (struct frame *f, int start, int stop)
264 char *buf;
265 struct tty_display_info *tty = FRAME_TTY (f);
267 if (tty->TS_set_scroll_region)
268 buf = tparam (tty->TS_set_scroll_region, 0, 0, start, stop - 1, 0, 0);
269 else if (tty->TS_set_scroll_region_1)
270 buf = tparam (tty->TS_set_scroll_region_1, 0, 0,
271 FRAME_TOTAL_LINES (f), start,
272 FRAME_TOTAL_LINES (f) - stop,
273 FRAME_TOTAL_LINES (f));
274 else
275 buf = tparam (tty->TS_set_window, 0, 0, start, 0, stop, FRAME_COLS (f));
277 OUTPUT (tty, buf);
278 xfree (buf);
279 losecursor (tty);
283 static void
284 tty_turn_on_insert (struct tty_display_info *tty)
286 if (!tty->insert_mode)
287 OUTPUT (tty, tty->TS_insert_mode);
288 tty->insert_mode = 1;
291 void
292 tty_turn_off_insert (struct tty_display_info *tty)
294 if (tty->insert_mode)
295 OUTPUT (tty, tty->TS_end_insert_mode);
296 tty->insert_mode = 0;
299 /* Handle highlighting. */
301 static void
302 tty_turn_off_highlight (struct tty_display_info *tty)
304 if (tty->standout_mode)
305 OUTPUT_IF (tty, tty->TS_end_standout_mode);
306 tty->standout_mode = 0;
309 static void
310 tty_turn_on_highlight (struct tty_display_info *tty)
312 if (!tty->standout_mode)
313 OUTPUT_IF (tty, tty->TS_standout_mode);
314 tty->standout_mode = 1;
317 static void
318 tty_toggle_highlight (struct tty_display_info *tty)
320 if (tty->standout_mode)
321 tty_turn_off_highlight (tty);
322 else
323 tty_turn_on_highlight (tty);
327 /* Make cursor invisible. */
329 static void
330 tty_hide_cursor (struct tty_display_info *tty)
332 if (tty->cursor_hidden == 0)
334 tty->cursor_hidden = 1;
335 #ifdef WINDOWSNT
336 w32con_hide_cursor ();
337 #else
338 OUTPUT_IF (tty, tty->TS_cursor_invisible);
339 #endif
344 /* Ensure that cursor is visible. */
346 static void
347 tty_show_cursor (struct tty_display_info *tty)
349 if (tty->cursor_hidden)
351 tty->cursor_hidden = 0;
352 #ifdef WINDOWSNT
353 w32con_show_cursor ();
354 #else
355 OUTPUT_IF (tty, tty->TS_cursor_normal);
356 if (visible_cursor)
357 OUTPUT_IF (tty, tty->TS_cursor_visible);
358 #endif
363 /* Set standout mode to the state it should be in for
364 empty space inside windows. What this is,
365 depends on the user option inverse-video. */
367 static void
368 tty_background_highlight (struct tty_display_info *tty)
370 if (inverse_video)
371 tty_turn_on_highlight (tty);
372 else
373 tty_turn_off_highlight (tty);
376 /* Set standout mode to the mode specified for the text to be output. */
378 static void
379 tty_highlight_if_desired (struct tty_display_info *tty)
381 if (inverse_video)
382 tty_turn_on_highlight (tty);
383 else
384 tty_turn_off_highlight (tty);
388 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
389 frame-relative coordinates. */
391 static void
392 tty_cursor_to (struct frame *f, int vpos, int hpos)
394 struct tty_display_info *tty = FRAME_TTY (f);
396 /* Detect the case where we are called from reset_sys_modes
397 and the costs have never been calculated. Do nothing. */
398 if (! tty->costs_set)
399 return;
401 if (curY (tty) == vpos
402 && curX (tty) == hpos)
403 return;
404 if (!tty->TF_standout_motion)
405 tty_background_highlight (tty);
406 if (!tty->TF_insmode_motion)
407 tty_turn_off_insert (tty);
408 cmgoto (tty, vpos, hpos);
411 /* Similar but don't take any account of the wasted characters. */
413 static void
414 tty_raw_cursor_to (struct frame *f, int row, int col)
416 struct tty_display_info *tty = FRAME_TTY (f);
418 if (curY (tty) == row
419 && curX (tty) == col)
420 return;
421 if (!tty->TF_standout_motion)
422 tty_background_highlight (tty);
423 if (!tty->TF_insmode_motion)
424 tty_turn_off_insert (tty);
425 cmgoto (tty, row, col);
428 /* Erase operations */
430 /* Clear from cursor to end of frame on a termcap device. */
432 static void
433 tty_clear_to_end (struct frame *f)
435 register int i;
436 struct tty_display_info *tty = FRAME_TTY (f);
438 if (tty->TS_clr_to_bottom)
440 tty_background_highlight (tty);
441 OUTPUT (tty, tty->TS_clr_to_bottom);
443 else
445 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
447 cursor_to (f, i, 0);
448 clear_end_of_line (f, FRAME_COLS (f));
453 /* Clear an entire termcap frame. */
455 static void
456 tty_clear_frame (struct frame *f)
458 struct tty_display_info *tty = FRAME_TTY (f);
460 if (tty->TS_clr_frame)
462 tty_background_highlight (tty);
463 OUTPUT (tty, tty->TS_clr_frame);
464 cmat (tty, 0, 0);
466 else
468 cursor_to (f, 0, 0);
469 clear_to_end (f);
473 /* An implementation of clear_end_of_line for termcap frames.
475 Note that the cursor may be moved, on terminals lacking a `ce' string. */
477 static void
478 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
480 register int i;
481 struct tty_display_info *tty = FRAME_TTY (f);
483 /* Detect the case where we are called from reset_sys_modes
484 and the costs have never been calculated. Do nothing. */
485 if (! tty->costs_set)
486 return;
488 if (curX (tty) >= first_unused_hpos)
489 return;
490 tty_background_highlight (tty);
491 if (tty->TS_clr_line)
493 OUTPUT1 (tty, tty->TS_clr_line);
495 else
496 { /* have to do it the hard way */
497 tty_turn_off_insert (tty);
499 /* Do not write in last row last col with Auto-wrap on. */
500 if (AutoWrap (tty)
501 && curY (tty) == FrameRows (tty) - 1
502 && first_unused_hpos == FrameCols (tty))
503 first_unused_hpos--;
505 for (i = curX (tty); i < first_unused_hpos; i++)
507 if (tty->termscript)
508 fputc (' ', tty->termscript);
509 fputc (' ', tty->output);
511 cmplus (tty, first_unused_hpos - curX (tty));
515 /* Buffers to store the source and result of code conversion for terminal. */
516 static unsigned char *encode_terminal_src;
517 static unsigned char *encode_terminal_dst;
518 /* Allocated sizes of the above buffers. */
519 static ptrdiff_t encode_terminal_src_size;
520 static ptrdiff_t encode_terminal_dst_size;
522 /* Encode SRC_LEN glyphs starting at SRC to terminal output codes.
523 Set CODING->produced to the byte-length of the resulting byte
524 sequence, and return a pointer to that byte sequence. */
526 unsigned char *
527 encode_terminal_code (struct glyph *src, int src_len,
528 struct coding_system *coding)
530 struct glyph *src_end = src + src_len;
531 unsigned char *buf;
532 ptrdiff_t nchars, nbytes, required;
533 ptrdiff_t tlen = GLYPH_TABLE_LENGTH;
534 register Lisp_Object *tbase = GLYPH_TABLE_BASE;
535 Lisp_Object charset_list;
537 /* Allocate sufficient size of buffer to store all characters in
538 multibyte-form. But, it may be enlarged on demand if
539 Vglyph_table contains a string or a composite glyph is
540 encountered. */
541 if (min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH < src_len)
542 memory_full (SIZE_MAX);
543 required = src_len;
544 required *= MAX_MULTIBYTE_LENGTH;
545 if (encode_terminal_src_size < required)
547 encode_terminal_src = xrealloc (encode_terminal_src, required);
548 encode_terminal_src_size = required;
551 charset_list = coding_charset_list (coding);
553 buf = encode_terminal_src;
554 nchars = 0;
555 while (src < src_end)
557 if (src->type == COMPOSITE_GLYPH)
559 struct composition *cmp IF_LINT (= NULL);
560 Lisp_Object gstring IF_LINT (= Qnil);
561 int i;
563 nbytes = buf - encode_terminal_src;
564 if (src->u.cmp.automatic)
566 gstring = composition_gstring_from_id (src->u.cmp.id);
567 required = src->slice.cmp.to - src->slice.cmp.from + 1;
569 else
571 cmp = composition_table[src->u.cmp.id];
572 required = cmp->glyph_len;
573 required *= MAX_MULTIBYTE_LENGTH;
576 if (encode_terminal_src_size - nbytes < required)
578 encode_terminal_src =
579 xpalloc (encode_terminal_src, &encode_terminal_src_size,
580 required - (encode_terminal_src_size - nbytes),
581 -1, 1);
582 buf = encode_terminal_src + nbytes;
585 if (src->u.cmp.automatic)
586 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
588 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
589 int c = LGLYPH_CHAR (g);
591 if (! char_charset (c, charset_list, NULL))
592 c = '?';
593 buf += CHAR_STRING (c, buf);
594 nchars++;
596 else
597 for (i = 0; i < cmp->glyph_len; i++)
599 int c = COMPOSITION_GLYPH (cmp, i);
601 /* TAB in a composition means display glyphs with
602 padding space on the left or right. */
603 if (c == '\t')
604 continue;
605 if (char_charset (c, charset_list, NULL))
607 if (CHAR_WIDTH (c) == 0
608 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
609 /* Should be left-padded */
611 buf += CHAR_STRING (' ', buf);
612 nchars++;
615 else
616 c = '?';
617 buf += CHAR_STRING (c, buf);
618 nchars++;
621 /* We must skip glyphs to be padded for a wide character. */
622 else if (! CHAR_GLYPH_PADDING_P (*src))
624 GLYPH g;
625 int c IF_LINT (= 0);
626 Lisp_Object string;
628 string = Qnil;
629 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
631 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
633 /* This glyph doesn't have an entry in Vglyph_table. */
634 c = src->u.ch;
636 else
638 /* This glyph has an entry in Vglyph_table,
639 so process any alias before testing for simpleness. */
640 GLYPH_FOLLOW_ALIASES (tbase, tlen, g);
642 if (GLYPH_SIMPLE_P (tbase, tlen, g))
643 /* We set the multi-byte form of a character in G
644 (that should be an ASCII character) at WORKBUF. */
645 c = GLYPH_CHAR (g);
646 else
647 /* We have a string in Vglyph_table. */
648 string = tbase[GLYPH_CHAR (g)];
651 if (NILP (string))
653 nbytes = buf - encode_terminal_src;
654 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
656 encode_terminal_src =
657 xpalloc (encode_terminal_src, &encode_terminal_src_size,
658 MAX_MULTIBYTE_LENGTH, -1, 1);
659 buf = encode_terminal_src + nbytes;
661 if (CHAR_BYTE8_P (c)
662 || char_charset (c, charset_list, NULL))
664 /* Store the multibyte form of C at BUF. */
665 buf += CHAR_STRING (c, buf);
666 nchars++;
668 else
670 /* C is not encodable. */
671 *buf++ = '?';
672 nchars++;
673 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
675 *buf++ = '?';
676 nchars++;
677 src++;
681 else
683 if (! STRING_MULTIBYTE (string))
684 string = string_to_multibyte (string);
685 nbytes = buf - encode_terminal_src;
686 if (encode_terminal_src_size - nbytes < SBYTES (string))
688 encode_terminal_src =
689 xpalloc (encode_terminal_src, &encode_terminal_src_size,
690 (SBYTES (string)
691 - (encode_terminal_src_size - nbytes)),
692 -1, 1);
693 buf = encode_terminal_src + nbytes;
695 memcpy (buf, SDATA (string), SBYTES (string));
696 buf += SBYTES (string);
697 nchars += SCHARS (string);
700 src++;
703 if (nchars == 0)
705 coding->produced = 0;
706 return NULL;
709 nbytes = buf - encode_terminal_src;
710 coding->source = encode_terminal_src;
711 if (encode_terminal_dst_size == 0)
713 encode_terminal_dst = xrealloc (encode_terminal_dst,
714 encode_terminal_src_size);
715 encode_terminal_dst_size = encode_terminal_src_size;
717 coding->destination = encode_terminal_dst;
718 coding->dst_bytes = encode_terminal_dst_size;
719 encode_coding_object (coding, Qnil, 0, 0, nchars, nbytes, Qnil);
720 /* coding->destination may have been reallocated. */
721 encode_terminal_dst = coding->destination;
722 encode_terminal_dst_size = coding->dst_bytes;
724 return (encode_terminal_dst);
729 /* An implementation of write_glyphs for termcap frames. */
731 static void
732 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
734 unsigned char *conversion_buffer;
735 struct coding_system *coding;
736 int n, stringlen;
738 struct tty_display_info *tty = FRAME_TTY (f);
740 tty_turn_off_insert (tty);
741 tty_hide_cursor (tty);
743 /* Don't dare write in last column of bottom line, if Auto-Wrap,
744 since that would scroll the whole frame on some terminals. */
746 if (AutoWrap (tty)
747 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
748 && (curX (tty) + len) == FRAME_COLS (f))
749 len --;
750 if (len <= 0)
751 return;
753 cmplus (tty, len);
755 /* If terminal_coding does any conversion, use it, otherwise use
756 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
757 because it always return 1 if the member src_multibyte is 1. */
758 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
759 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
760 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
761 the tail. */
762 coding->mode &= ~CODING_MODE_LAST_BLOCK;
764 for (stringlen = len; stringlen != 0; stringlen -= n)
766 /* Identify a run of glyphs with the same face. */
767 int face_id = string->face_id;
769 for (n = 1; n < stringlen; ++n)
770 if (string[n].face_id != face_id)
771 break;
773 /* Turn appearance modes of the face of the run on. */
774 tty_highlight_if_desired (tty);
775 turn_on_face (f, face_id);
777 if (n == stringlen)
778 /* This is the last run. */
779 coding->mode |= CODING_MODE_LAST_BLOCK;
780 conversion_buffer = encode_terminal_code (string, n, coding);
781 if (coding->produced > 0)
783 block_input ();
784 fwrite (conversion_buffer, 1, coding->produced, tty->output);
785 if (ferror (tty->output))
786 clearerr (tty->output);
787 if (tty->termscript)
788 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
789 unblock_input ();
791 string += n;
793 /* Turn appearance modes off. */
794 turn_off_face (f, face_id);
795 tty_turn_off_highlight (tty);
798 cmcheckmagic (tty);
801 #ifdef HAVE_GPM /* Only used by GPM code. */
803 static void
804 tty_write_glyphs_with_face (register struct frame *f, register struct glyph *string,
805 register int len, register int face_id)
807 unsigned char *conversion_buffer;
808 struct coding_system *coding;
810 struct tty_display_info *tty = FRAME_TTY (f);
812 tty_turn_off_insert (tty);
813 tty_hide_cursor (tty);
815 /* Don't dare write in last column of bottom line, if Auto-Wrap,
816 since that would scroll the whole frame on some terminals. */
818 if (AutoWrap (tty)
819 && curY (tty) + 1 == FRAME_TOTAL_LINES (f)
820 && (curX (tty) + len) == FRAME_COLS (f))
821 len --;
822 if (len <= 0)
823 return;
825 cmplus (tty, len);
827 /* If terminal_coding does any conversion, use it, otherwise use
828 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
829 because it always return 1 if the member src_multibyte is 1. */
830 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
831 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
832 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
833 the tail. */
834 coding->mode &= ~CODING_MODE_LAST_BLOCK;
836 /* Turn appearance modes of the face. */
837 tty_highlight_if_desired (tty);
838 turn_on_face (f, face_id);
840 coding->mode |= CODING_MODE_LAST_BLOCK;
841 conversion_buffer = encode_terminal_code (string, len, coding);
842 if (coding->produced > 0)
844 block_input ();
845 fwrite (conversion_buffer, 1, coding->produced, tty->output);
846 if (ferror (tty->output))
847 clearerr (tty->output);
848 if (tty->termscript)
849 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
850 unblock_input ();
853 /* Turn appearance modes off. */
854 turn_off_face (f, face_id);
855 tty_turn_off_highlight (tty);
857 cmcheckmagic (tty);
859 #endif
861 /* An implementation of insert_glyphs for termcap frames. */
863 static void
864 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
866 char *buf;
867 struct glyph *glyph = NULL;
868 unsigned char *conversion_buffer;
869 unsigned char space[1];
870 struct coding_system *coding;
872 struct tty_display_info *tty = FRAME_TTY (f);
874 if (tty->TS_ins_multi_chars)
876 buf = tparam (tty->TS_ins_multi_chars, 0, 0, len, 0, 0, 0);
877 OUTPUT1 (tty, buf);
878 xfree (buf);
879 if (start)
880 write_glyphs (f, start, len);
881 return;
884 tty_turn_on_insert (tty);
885 cmplus (tty, len);
887 if (! start)
888 space[0] = SPACEGLYPH;
890 /* If terminal_coding does any conversion, use it, otherwise use
891 safe_terminal_coding. We can't use CODING_REQUIRE_ENCODING here
892 because it always return 1 if the member src_multibyte is 1. */
893 coding = (FRAME_TERMINAL_CODING (f)->common_flags & CODING_REQUIRE_ENCODING_MASK
894 ? FRAME_TERMINAL_CODING (f) : &safe_terminal_coding);
895 /* The mode bit CODING_MODE_LAST_BLOCK should be set to 1 only at
896 the tail. */
897 coding->mode &= ~CODING_MODE_LAST_BLOCK;
899 while (len-- > 0)
901 OUTPUT1_IF (tty, tty->TS_ins_char);
902 if (!start)
904 conversion_buffer = space;
905 coding->produced = 1;
907 else
909 tty_highlight_if_desired (tty);
910 turn_on_face (f, start->face_id);
911 glyph = start;
912 ++start;
913 /* We must open sufficient space for a character which
914 occupies more than one column. */
915 while (len && CHAR_GLYPH_PADDING_P (*start))
917 OUTPUT1_IF (tty, tty->TS_ins_char);
918 start++, len--;
921 if (len <= 0)
922 /* This is the last glyph. */
923 coding->mode |= CODING_MODE_LAST_BLOCK;
925 conversion_buffer = encode_terminal_code (glyph, 1, coding);
928 if (coding->produced > 0)
930 block_input ();
931 fwrite (conversion_buffer, 1, coding->produced, tty->output);
932 if (ferror (tty->output))
933 clearerr (tty->output);
934 if (tty->termscript)
935 fwrite (conversion_buffer, 1, coding->produced, tty->termscript);
936 unblock_input ();
939 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
940 if (start)
942 turn_off_face (f, glyph->face_id);
943 tty_turn_off_highlight (tty);
947 cmcheckmagic (tty);
950 /* An implementation of delete_glyphs for termcap frames. */
952 static void
953 tty_delete_glyphs (struct frame *f, int n)
955 char *buf;
956 register int i;
958 struct tty_display_info *tty = FRAME_TTY (f);
960 if (tty->delete_in_insert_mode)
962 tty_turn_on_insert (tty);
964 else
966 tty_turn_off_insert (tty);
967 OUTPUT_IF (tty, tty->TS_delete_mode);
970 if (tty->TS_del_multi_chars)
972 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
973 OUTPUT1 (tty, buf);
974 xfree (buf);
976 else
977 for (i = 0; i < n; i++)
978 OUTPUT1 (tty, tty->TS_del_char);
979 if (!tty->delete_in_insert_mode)
980 OUTPUT_IF (tty, tty->TS_end_delete_mode);
983 /* An implementation of ins_del_lines for termcap frames. */
985 static void
986 tty_ins_del_lines (struct frame *f, int vpos, int n)
988 struct tty_display_info *tty = FRAME_TTY (f);
989 const char *multi =
990 n > 0 ? tty->TS_ins_multi_lines : tty->TS_del_multi_lines;
991 const char *single = n > 0 ? tty->TS_ins_line : tty->TS_del_line;
992 const char *scroll = n > 0 ? tty->TS_rev_scroll : tty->TS_fwd_scroll;
994 int i = eabs (n);
995 char *buf;
997 /* If the lines below the insertion are being pushed
998 into the end of the window, this is the same as clearing;
999 and we know the lines are already clear, since the matching
1000 deletion has already been done. So can ignore this. */
1001 /* If the lines below the deletion are blank lines coming
1002 out of the end of the window, don't bother,
1003 as there will be a matching inslines later that will flush them. */
1004 if (FRAME_SCROLL_REGION_OK (f)
1005 && vpos + i >= tty->specified_window)
1006 return;
1007 if (!FRAME_MEMORY_BELOW_FRAME (f)
1008 && vpos + i >= FRAME_TOTAL_LINES (f))
1009 return;
1011 if (multi)
1013 raw_cursor_to (f, vpos, 0);
1014 tty_background_highlight (tty);
1015 buf = tparam (multi, 0, 0, i, 0, 0, 0);
1016 OUTPUT (tty, buf);
1017 xfree (buf);
1019 else if (single)
1021 raw_cursor_to (f, vpos, 0);
1022 tty_background_highlight (tty);
1023 while (--i >= 0)
1024 OUTPUT (tty, single);
1025 if (tty->TF_teleray)
1026 curX (tty) = 0;
1028 else
1030 tty_set_scroll_region (f, vpos, tty->specified_window);
1031 if (n < 0)
1032 raw_cursor_to (f, tty->specified_window - 1, 0);
1033 else
1034 raw_cursor_to (f, vpos, 0);
1035 tty_background_highlight (tty);
1036 while (--i >= 0)
1037 OUTPUTL (tty, scroll, tty->specified_window - vpos);
1038 tty_set_scroll_region (f, 0, tty->specified_window);
1041 if (!FRAME_SCROLL_REGION_OK (f)
1042 && FRAME_MEMORY_BELOW_FRAME (f)
1043 && n < 0)
1045 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1046 clear_to_end (f);
1050 /* Compute cost of sending "str", in characters,
1051 not counting any line-dependent padding. */
1054 string_cost (const char *str)
1056 cost = 0;
1057 if (str)
1058 tputs (str, 0, evalcost);
1059 return cost;
1062 /* Compute cost of sending "str", in characters,
1063 counting any line-dependent padding at one line. */
1065 static int
1066 string_cost_one_line (const char *str)
1068 cost = 0;
1069 if (str)
1070 tputs (str, 1, evalcost);
1071 return cost;
1074 /* Compute per line amount of line-dependent padding,
1075 in tenths of characters. */
1078 per_line_cost (const char *str)
1080 cost = 0;
1081 if (str)
1082 tputs (str, 0, evalcost);
1083 cost = - cost;
1084 if (str)
1085 tputs (str, 10, evalcost);
1086 return cost;
1089 /* char_ins_del_cost[n] is cost of inserting N characters.
1090 char_ins_del_cost[-n] is cost of deleting N characters.
1091 The length of this vector is based on max_frame_cols. */
1093 int *char_ins_del_vector;
1095 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1097 /* ARGSUSED */
1098 static void
1099 calculate_ins_del_char_costs (struct frame *f)
1101 struct tty_display_info *tty = FRAME_TTY (f);
1102 int ins_startup_cost, del_startup_cost;
1103 int ins_cost_per_char, del_cost_per_char;
1104 register int i;
1105 register int *p;
1107 if (tty->TS_ins_multi_chars)
1109 ins_cost_per_char = 0;
1110 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1112 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1113 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1115 ins_startup_cost = (30 * (string_cost (tty->TS_insert_mode)
1116 + string_cost (tty->TS_end_insert_mode))) / 100;
1117 ins_cost_per_char = (string_cost_one_line (tty->TS_ins_char)
1118 + string_cost_one_line (tty->TS_pad_inserted_char));
1120 else
1122 ins_startup_cost = 9999;
1123 ins_cost_per_char = 0;
1126 if (tty->TS_del_multi_chars)
1128 del_cost_per_char = 0;
1129 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1131 else if (tty->TS_del_char)
1133 del_startup_cost = (string_cost (tty->TS_delete_mode)
1134 + string_cost (tty->TS_end_delete_mode));
1135 if (tty->delete_in_insert_mode)
1136 del_startup_cost /= 2;
1137 del_cost_per_char = string_cost_one_line (tty->TS_del_char);
1139 else
1141 del_startup_cost = 9999;
1142 del_cost_per_char = 0;
1145 /* Delete costs are at negative offsets */
1146 p = &char_ins_del_cost (f)[0];
1147 for (i = FRAME_COLS (f); --i >= 0;)
1148 *--p = (del_startup_cost += del_cost_per_char);
1150 /* Doing nothing is free */
1151 p = &char_ins_del_cost (f)[0];
1152 *p++ = 0;
1154 /* Insert costs are at positive offsets */
1155 for (i = FRAME_COLS (f); --i >= 0;)
1156 *p++ = (ins_startup_cost += ins_cost_per_char);
1159 void
1160 calculate_costs (struct frame *frame)
1162 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1164 if (FRAME_TERMCAP_P (frame))
1166 struct tty_display_info *tty = FRAME_TTY (frame);
1167 register const char *f = (tty->TS_set_scroll_region
1168 ? tty->TS_set_scroll_region
1169 : tty->TS_set_scroll_region_1);
1171 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1173 tty->costs_set = 1;
1175 /* These variables are only used for terminal stuff. They are
1176 allocated once for the terminal frame of X-windows emacs, but not
1177 used afterwards.
1179 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1180 X turns off char_ins_del_ok. */
1182 max_frame_cols = max (max_frame_cols, FRAME_COLS (frame));
1183 if ((min (PTRDIFF_MAX, SIZE_MAX) / sizeof (int) - 1) / 2
1184 < max_frame_cols)
1185 memory_full (SIZE_MAX);
1187 char_ins_del_vector =
1188 xrealloc (char_ins_del_vector,
1189 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1191 memset (char_ins_del_vector, 0,
1192 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1195 if (f && (!tty->TS_ins_line && !tty->TS_del_line))
1196 do_line_insertion_deletion_costs (frame,
1197 tty->TS_rev_scroll, tty->TS_ins_multi_lines,
1198 tty->TS_fwd_scroll, tty->TS_del_multi_lines,
1199 f, f, 1);
1200 else
1201 do_line_insertion_deletion_costs (frame,
1202 tty->TS_ins_line, tty->TS_ins_multi_lines,
1203 tty->TS_del_line, tty->TS_del_multi_lines,
1204 0, 0, 1);
1206 calculate_ins_del_char_costs (frame);
1208 /* Don't use TS_repeat if its padding is worse than sending the chars */
1209 if (tty->TS_repeat && per_line_cost (tty->TS_repeat) * baud_rate < 9000)
1210 tty->RPov = string_cost (tty->TS_repeat);
1211 else
1212 tty->RPov = FRAME_COLS (frame) * 2;
1214 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1218 struct fkey_table {
1219 const char *cap, *name;
1222 /* Termcap capability names that correspond directly to X keysyms.
1223 Some of these (marked "terminfo") aren't supplied by old-style
1224 (Berkeley) termcap entries. They're listed in X keysym order;
1225 except we put the keypad keys first, so that if they clash with
1226 other keys (as on the IBM PC keyboard) they get overridden.
1229 static const struct fkey_table keys[] =
1231 {"kh", "home"}, /* termcap */
1232 {"kl", "left"}, /* termcap */
1233 {"ku", "up"}, /* termcap */
1234 {"kr", "right"}, /* termcap */
1235 {"kd", "down"}, /* termcap */
1236 {"%8", "prior"}, /* terminfo */
1237 {"%5", "next"}, /* terminfo */
1238 {"@7", "end"}, /* terminfo */
1239 {"@1", "begin"}, /* terminfo */
1240 {"*6", "select"}, /* terminfo */
1241 {"%9", "print"}, /* terminfo */
1242 {"@4", "execute"}, /* terminfo --- actually the `command' key */
1244 * "insert" --- see below
1246 {"&8", "undo"}, /* terminfo */
1247 {"%0", "redo"}, /* terminfo */
1248 {"%7", "menu"}, /* terminfo --- actually the `options' key */
1249 {"@0", "find"}, /* terminfo */
1250 {"@2", "cancel"}, /* terminfo */
1251 {"%1", "help"}, /* terminfo */
1253 * "break" goes here, but can't be reliably intercepted with termcap
1255 {"&4", "reset"}, /* terminfo --- actually `restart' */
1257 * "system" and "user" --- no termcaps
1259 {"kE", "clearline"}, /* terminfo */
1260 {"kA", "insertline"}, /* terminfo */
1261 {"kL", "deleteline"}, /* terminfo */
1262 {"kI", "insertchar"}, /* terminfo */
1263 {"kD", "deletechar"}, /* terminfo */
1264 {"kB", "backtab"}, /* terminfo */
1266 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1268 {"@8", "kp-enter"}, /* terminfo */
1270 * "kp-f1", "kp-f2", "kp-f3" "kp-f4",
1271 * "kp-multiply", "kp-add", "kp-separator",
1272 * "kp-subtract", "kp-decimal", "kp-divide", "kp-0";
1273 * --- no termcaps for any of these.
1275 {"K4", "kp-1"}, /* terminfo */
1277 * "kp-2" --- no termcap
1279 {"K5", "kp-3"}, /* terminfo */
1281 * "kp-4" --- no termcap
1283 {"K2", "kp-5"}, /* terminfo */
1285 * "kp-6" --- no termcap
1287 {"K1", "kp-7"}, /* terminfo */
1289 * "kp-8" --- no termcap
1291 {"K3", "kp-9"}, /* terminfo */
1293 * "kp-equal" --- no termcap
1295 {"k1", "f1"},
1296 {"k2", "f2"},
1297 {"k3", "f3"},
1298 {"k4", "f4"},
1299 {"k5", "f5"},
1300 {"k6", "f6"},
1301 {"k7", "f7"},
1302 {"k8", "f8"},
1303 {"k9", "f9"},
1305 {"&0", "S-cancel"}, /*shifted cancel key*/
1306 {"&9", "S-begin"}, /*shifted begin key*/
1307 {"*0", "S-find"}, /*shifted find key*/
1308 {"*1", "S-execute"}, /*shifted execute? actually shifted command key*/
1309 {"*4", "S-delete"}, /*shifted delete-character key*/
1310 {"*7", "S-end"}, /*shifted end key*/
1311 {"*8", "S-clearline"}, /*shifted clear-to end-of-line key*/
1312 {"#1", "S-help"}, /*shifted help key*/
1313 {"#2", "S-home"}, /*shifted home key*/
1314 {"#3", "S-insert"}, /*shifted insert-character key*/
1315 {"#4", "S-left"}, /*shifted left-arrow key*/
1316 {"%d", "S-menu"}, /*shifted menu? actually shifted options key*/
1317 {"%c", "S-next"}, /*shifted next key*/
1318 {"%e", "S-prior"}, /*shifted previous key*/
1319 {"%f", "S-print"}, /*shifted print key*/
1320 {"%g", "S-redo"}, /*shifted redo key*/
1321 {"%i", "S-right"}, /*shifted right-arrow key*/
1322 {"!3", "S-undo"} /*shifted undo key*/
1325 #ifndef DOS_NT
1326 static char **term_get_fkeys_address;
1327 static KBOARD *term_get_fkeys_kboard;
1328 static Lisp_Object term_get_fkeys_1 (void);
1330 /* Find the escape codes sent by the function keys for Vinput_decode_map.
1331 This function scans the termcap function key sequence entries, and
1332 adds entries to Vinput_decode_map for each function key it finds. */
1334 static void
1335 term_get_fkeys (char **address, KBOARD *kboard)
1337 /* We run the body of the function (term_get_fkeys_1) and ignore all Lisp
1338 errors during the call. The only errors should be from Fdefine_key
1339 when given a key sequence containing an invalid prefix key. If the
1340 termcap defines function keys which use a prefix that is already bound
1341 to a command by the default bindings, we should silently ignore that
1342 function key specification, rather than giving the user an error and
1343 refusing to run at all on such a terminal. */
1345 term_get_fkeys_address = address;
1346 term_get_fkeys_kboard = kboard;
1347 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1350 static Lisp_Object
1351 term_get_fkeys_1 (void)
1353 int i;
1355 char **address = term_get_fkeys_address;
1356 KBOARD *kboard = term_get_fkeys_kboard;
1358 /* This can happen if CANNOT_DUMP or with strange options. */
1359 if (!KEYMAPP (KVAR (kboard, Vinput_decode_map)))
1360 kset_input_decode_map (kboard, Fmake_sparse_keymap (Qnil));
1362 for (i = 0; i < ARRAYELTS (keys); i++)
1364 char *sequence = tgetstr (keys[i].cap, address);
1365 if (sequence)
1366 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1367 Fmake_vector (make_number (1),
1368 intern (keys[i].name)));
1371 /* The uses of the "k0" capability are inconsistent; sometimes it
1372 describes F10, whereas othertimes it describes F0 and "k;" describes F10.
1373 We will attempt to politely accommodate both systems by testing for
1374 "k;", and if it is present, assuming that "k0" denotes F0, otherwise F10.
1377 const char *k_semi = tgetstr ("k;", address);
1378 const char *k0 = tgetstr ("k0", address);
1379 const char *k0_name = "f10";
1381 if (k_semi)
1383 if (k0)
1384 /* Define f0 first, so that f10 takes precedence in case the
1385 key sequences happens to be the same. */
1386 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1387 Fmake_vector (make_number (1), intern ("f0")));
1388 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k_semi),
1389 Fmake_vector (make_number (1), intern ("f10")));
1391 else if (k0)
1392 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1393 Fmake_vector (make_number (1), intern (k0_name)));
1396 /* Set up cookies for numbered function keys above f10. */
1398 char fcap[3], fkey[4];
1400 fcap[0] = 'F'; fcap[2] = '\0';
1401 for (i = 11; i < 64; i++)
1403 if (i <= 19)
1404 fcap[1] = '1' + i - 11;
1405 else if (i <= 45)
1406 fcap[1] = 'A' + i - 20;
1407 else
1408 fcap[1] = 'a' + i - 46;
1411 char *sequence = tgetstr (fcap, address);
1412 if (sequence)
1414 sprintf (fkey, "f%d", i);
1415 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence),
1416 Fmake_vector (make_number (1),
1417 intern (fkey)));
1424 * Various mappings to try and get a better fit.
1427 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1428 if (!tgetstr (cap1, address)) \
1430 char *sequence = tgetstr (cap2, address); \
1431 if (sequence) \
1432 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (sequence), \
1433 Fmake_vector (make_number (1), \
1434 intern (sym))); \
1437 /* if there's no key_next keycap, map key_npage to `next' keysym */
1438 CONDITIONAL_REASSIGN ("%5", "kN", "next");
1439 /* if there's no key_prev keycap, map key_ppage to `previous' keysym */
1440 CONDITIONAL_REASSIGN ("%8", "kP", "prior");
1441 /* if there's no key_dc keycap, map key_ic to `insert' keysym */
1442 CONDITIONAL_REASSIGN ("kD", "kI", "insert");
1443 /* if there's no key_end keycap, map key_ll to 'end' keysym */
1444 CONDITIONAL_REASSIGN ("@7", "kH", "end");
1445 #undef CONDITIONAL_REASSIGN
1448 return Qnil;
1450 #endif /* not DOS_NT */
1453 /***********************************************************************
1454 Character Display Information
1455 ***********************************************************************/
1456 static void append_glyph (struct it *);
1457 static void append_composite_glyph (struct it *);
1458 static void produce_composite_glyph (struct it *);
1459 static void append_glyphless_glyph (struct it *, int, const char *);
1460 static void produce_glyphless_glyph (struct it *, Lisp_Object);
1462 /* Append glyphs to IT's glyph_row. Called from produce_glyphs for
1463 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1464 the character for which to produce glyphs; IT->face_id contains the
1465 character's face. Padding glyphs are appended if IT->c has a
1466 IT->pixel_width > 1. */
1468 static void
1469 append_glyph (struct it *it)
1471 struct glyph *glyph, *end;
1472 int i;
1474 eassert (it->glyph_row);
1475 glyph = (it->glyph_row->glyphs[it->area]
1476 + it->glyph_row->used[it->area]);
1477 end = it->glyph_row->glyphs[1 + it->area];
1479 /* If the glyph row is reversed, we need to prepend the glyph rather
1480 than append it. */
1481 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1483 struct glyph *g;
1484 int move_by = it->pixel_width;
1486 /* Make room for the new glyphs. */
1487 if (move_by > end - glyph) /* don't overstep end of this area */
1488 move_by = end - glyph;
1489 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1490 g[move_by] = *g;
1491 glyph = it->glyph_row->glyphs[it->area];
1492 end = glyph + move_by;
1495 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1496 right, even in the REVERSED_P case, since (a) all of its u.ch are
1497 identical, and (b) the PADDING_P flag needs to be set for the
1498 leftmost one, because we write to the terminal left-to-right. */
1499 for (i = 0;
1500 i < it->pixel_width && glyph < end;
1501 ++i)
1503 glyph->type = CHAR_GLYPH;
1504 glyph->pixel_width = 1;
1505 glyph->u.ch = it->char_to_display;
1506 glyph->face_id = it->face_id;
1507 glyph->padding_p = i > 0;
1508 glyph->charpos = CHARPOS (it->position);
1509 glyph->object = it->object;
1510 if (it->bidi_p)
1512 glyph->resolved_level = it->bidi_it.resolved_level;
1513 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1514 glyph->bidi_type = it->bidi_it.type;
1516 else
1518 glyph->resolved_level = 0;
1519 glyph->bidi_type = UNKNOWN_BT;
1522 ++it->glyph_row->used[it->area];
1523 ++glyph;
1527 /* For external use. */
1528 void
1529 tty_append_glyph (struct it *it)
1531 append_glyph (it);
1535 /* Produce glyphs for the display element described by IT. *IT
1536 specifies what we want to produce a glyph for (character, image, ...),
1537 and where in the glyph matrix we currently are (glyph row and hpos).
1538 produce_glyphs fills in output fields of *IT with information such as the
1539 pixel width and height of a character, and maybe output actual glyphs at
1540 the same time if IT->glyph_row is non-null. For an overview, see
1541 the explanation in dispextern.h, before the definition of the
1542 display_element_type enumeration.
1544 produce_glyphs also stores the result of glyph width, ascent
1545 etc. computations in *IT.
1547 IT->glyph_row may be null, in which case produce_glyphs does not
1548 actually fill in the glyphs. This is used in the move_* functions
1549 in xdisp.c for text width and height computations.
1551 Callers usually don't call produce_glyphs directly;
1552 instead they use the macro PRODUCE_GLYPHS. */
1554 void
1555 produce_glyphs (struct it *it)
1557 /* If a hook is installed, let it do the work. */
1559 /* Nothing but characters are supported on terminal frames. */
1560 eassert (it->what == IT_CHARACTER
1561 || it->what == IT_COMPOSITION
1562 || it->what == IT_STRETCH
1563 || it->what == IT_GLYPHLESS);
1565 if (it->what == IT_STRETCH)
1567 produce_stretch_glyph (it);
1568 goto done;
1571 if (it->what == IT_COMPOSITION)
1573 produce_composite_glyph (it);
1574 goto done;
1577 if (it->what == IT_GLYPHLESS)
1579 produce_glyphless_glyph (it, Qnil);
1580 goto done;
1583 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1585 it->pixel_width = it->nglyphs = 1;
1586 if (it->glyph_row)
1587 append_glyph (it);
1589 else if (it->char_to_display == '\n')
1590 it->pixel_width = it->nglyphs = 0;
1591 else if (it->char_to_display == '\t')
1593 int absolute_x = (it->current_x
1594 + it->continuation_lines_width);
1595 int next_tab_x
1596 = (((1 + absolute_x + it->tab_width - 1)
1597 / it->tab_width)
1598 * it->tab_width);
1599 int nspaces;
1601 /* If part of the TAB has been displayed on the previous line
1602 which is continued now, continuation_lines_width will have
1603 been incremented already by the part that fitted on the
1604 continued line. So, we will get the right number of spaces
1605 here. */
1606 nspaces = next_tab_x - absolute_x;
1608 if (it->glyph_row)
1610 int n = nspaces;
1612 it->char_to_display = ' ';
1613 it->pixel_width = it->len = 1;
1615 while (n--)
1616 append_glyph (it);
1619 it->pixel_width = nspaces;
1620 it->nglyphs = nspaces;
1622 else if (CHAR_BYTE8_P (it->char_to_display))
1624 /* Coming here means that we must send the raw 8-bit byte as is
1625 to the terminal. Although there's no way to know how many
1626 columns it occupies on a screen, it is a good assumption that
1627 a single byte code has 1-column width. */
1628 it->pixel_width = it->nglyphs = 1;
1629 if (it->glyph_row)
1630 append_glyph (it);
1632 else
1634 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1636 if (char_charset (it->char_to_display, charset_list, NULL))
1638 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1639 it->nglyphs = it->pixel_width;
1640 if (it->glyph_row)
1641 append_glyph (it);
1643 else
1645 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1647 eassert (it->what == IT_GLYPHLESS);
1648 produce_glyphless_glyph (it, acronym);
1652 done:
1653 /* Advance current_x by the pixel width as a convenience for
1654 the caller. */
1655 if (it->area == TEXT_AREA)
1656 it->current_x += it->pixel_width;
1657 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1658 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
1661 /* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1662 Called from produce_composite_glyph for terminal frames if
1663 IT->glyph_row != NULL. IT->face_id contains the character's
1664 face. */
1666 static void
1667 append_composite_glyph (struct it *it)
1669 struct glyph *glyph;
1671 eassert (it->glyph_row);
1672 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1673 if (glyph < it->glyph_row->glyphs[1 + it->area])
1675 /* If the glyph row is reversed, we need to prepend the glyph
1676 rather than append it. */
1677 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1679 struct glyph *g;
1681 /* Make room for the new glyph. */
1682 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1683 g[1] = *g;
1684 glyph = it->glyph_row->glyphs[it->area];
1686 glyph->type = COMPOSITE_GLYPH;
1687 glyph->pixel_width = it->pixel_width;
1688 glyph->u.cmp.id = it->cmp_it.id;
1689 if (it->cmp_it.ch < 0)
1691 glyph->u.cmp.automatic = 0;
1692 glyph->u.cmp.id = it->cmp_it.id;
1694 else
1696 glyph->u.cmp.automatic = 1;
1697 glyph->u.cmp.id = it->cmp_it.id;
1698 glyph->slice.cmp.from = it->cmp_it.from;
1699 glyph->slice.cmp.to = it->cmp_it.to - 1;
1702 glyph->face_id = it->face_id;
1703 glyph->padding_p = 0;
1704 glyph->charpos = CHARPOS (it->position);
1705 glyph->object = it->object;
1706 if (it->bidi_p)
1708 glyph->resolved_level = it->bidi_it.resolved_level;
1709 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1710 glyph->bidi_type = it->bidi_it.type;
1712 else
1714 glyph->resolved_level = 0;
1715 glyph->bidi_type = UNKNOWN_BT;
1718 ++it->glyph_row->used[it->area];
1719 ++glyph;
1724 /* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1725 the composition. We simply produces components of the composition
1726 assuming that the terminal has a capability to layout/render it
1727 correctly. */
1729 static void
1730 produce_composite_glyph (struct it *it)
1732 if (it->cmp_it.ch < 0)
1734 struct composition *cmp = composition_table[it->cmp_it.id];
1736 it->pixel_width = cmp->width;
1738 else
1740 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1742 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1743 it->cmp_it.to, NULL);
1745 it->nglyphs = 1;
1746 if (it->glyph_row)
1747 append_composite_glyph (it);
1751 /* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
1752 is a face ID to be used for the glyph. What is actually appended
1753 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1754 comes from it->nglyphs bytes). */
1756 static void
1757 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1759 struct glyph *glyph, *end;
1760 int i;
1762 eassert (it->glyph_row);
1763 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1764 end = it->glyph_row->glyphs[1 + it->area];
1766 /* If the glyph row is reversed, we need to prepend the glyph rather
1767 than append it. */
1768 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1770 struct glyph *g;
1771 int move_by = it->pixel_width;
1773 /* Make room for the new glyphs. */
1774 if (move_by > end - glyph) /* don't overstep end of this area */
1775 move_by = end - glyph;
1776 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1777 g[move_by] = *g;
1778 glyph = it->glyph_row->glyphs[it->area];
1779 end = glyph + move_by;
1782 if (glyph >= end)
1783 return;
1784 glyph->type = CHAR_GLYPH;
1785 glyph->pixel_width = 1;
1786 glyph->face_id = face_id;
1787 glyph->padding_p = 0;
1788 glyph->charpos = CHARPOS (it->position);
1789 glyph->object = it->object;
1790 if (it->bidi_p)
1792 glyph->resolved_level = it->bidi_it.resolved_level;
1793 eassert ((it->bidi_it.type & 7) == it->bidi_it.type);
1794 glyph->bidi_type = it->bidi_it.type;
1796 else
1798 glyph->resolved_level = 0;
1799 glyph->bidi_type = UNKNOWN_BT;
1802 /* BIDI Note: we put the glyphs of characters left to right, even in
1803 the REVERSED_P case because we write to the terminal
1804 left-to-right. */
1805 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1807 if (i > 0)
1808 glyph[0] = glyph[-1];
1809 glyph->u.ch = str[i];
1810 ++it->glyph_row->used[it->area];
1811 ++glyph;
1815 /* Produce glyphs for a glyphless character for iterator IT.
1816 IT->glyphless_method specifies which method to use for displaying
1817 the character. See the description of enum
1818 glyphless_display_method in dispextern.h for the details.
1820 ACRONYM, if non-nil, is an acronym string for the character.
1822 The glyphs actually produced are of type CHAR_GLYPH. */
1824 static void
1825 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1827 int len, face_id = merge_glyphless_glyph_face (it);
1828 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
1829 char const *str = " ";
1831 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1833 /* As there's no way to produce a thin space, we produce a space
1834 of canonical width. */
1835 len = 1;
1837 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1839 len = CHAR_WIDTH (it->c);
1840 if (len == 0)
1841 len = 1;
1842 else if (len > 4)
1843 len = 4;
1844 len = sprintf (buf, "[%.*s]", len, str);
1845 str = buf;
1847 else
1849 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1851 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1852 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
1853 if (CONSP (acronym))
1854 acronym = XCDR (acronym);
1855 buf[0] = '[';
1856 str = STRINGP (acronym) ? SSDATA (acronym) : "";
1857 for (len = 0; len < 6 && str[len] && ASCII_CHAR_P (str[len]); len++)
1858 buf[1 + len] = str[len];
1859 buf[1 + len] = ']';
1860 len += 2;
1862 else
1864 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1865 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1866 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1867 : sprintf (buf, "\\x%06X", it->c));
1869 str = buf;
1872 it->pixel_width = len;
1873 it->nglyphs = len;
1874 if (it->glyph_row)
1875 append_glyphless_glyph (it, face_id, str);
1879 /***********************************************************************
1880 Faces
1881 ***********************************************************************/
1883 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1884 one of the enumerators from enum no_color_bit, or a bit set built
1885 from them. Some display attributes may not be used together with
1886 color; the termcap capability `NC' specifies which ones. */
1888 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1889 (tty->TN_max_colors > 0 \
1890 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1891 : 1)
1893 /* Turn appearances of face FACE_ID on tty frame F on.
1894 FACE_ID is a realized face ID number, in the face cache. */
1896 static void
1897 turn_on_face (struct frame *f, int face_id)
1899 struct face *face = FACE_FROM_ID (f, face_id);
1900 unsigned long fg = face->foreground;
1901 unsigned long bg = face->background;
1902 struct tty_display_info *tty = FRAME_TTY (f);
1904 /* Use reverse video if the face specifies that.
1905 Do this first because TS_end_standout_mode may be the same
1906 as TS_exit_attribute_mode, which turns all appearances off. */
1907 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1908 && (inverse_video
1909 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1910 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1911 tty_toggle_highlight (tty);
1913 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1914 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1916 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1918 if (tty->TS_enter_italic_mode)
1919 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1920 else
1921 /* Italics mode is unavailable on many terminals. In that
1922 case, map slant to dimmed text; we want italic text to
1923 appear different and dimming is not otherwise used. */
1924 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1927 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1928 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1930 if (tty->TN_max_colors > 0)
1932 const char *ts;
1933 char *p;
1935 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1936 if (face_tty_specified_color (fg) && ts)
1938 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1939 OUTPUT (tty, p);
1940 xfree (p);
1943 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1944 if (face_tty_specified_color (bg) && ts)
1946 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1947 OUTPUT (tty, p);
1948 xfree (p);
1954 /* Turn off appearances of face FACE_ID on tty frame F. */
1956 static void
1957 turn_off_face (struct frame *f, int face_id)
1959 struct face *face = FACE_FROM_ID (f, face_id);
1960 struct tty_display_info *tty = FRAME_TTY (f);
1962 eassert (face != NULL);
1964 if (tty->TS_exit_attribute_mode)
1966 /* Capability "me" will turn off appearance modes double-bright,
1967 half-bright, reverse-video, standout, underline. It may or
1968 may not turn off alt-char-mode. */
1969 if (face->tty_bold_p
1970 || face->tty_italic_p
1971 || face->tty_reverse_p
1972 || face->tty_underline_p)
1974 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1975 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1976 tty->standout_mode = 0;
1979 else
1981 /* If we don't have "me" we can only have those appearances
1982 that have exit sequences defined. */
1983 if (face->tty_underline_p)
1984 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1987 /* Switch back to default colors. */
1988 if (tty->TN_max_colors > 0
1989 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1990 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1991 || (face->background != FACE_TTY_DEFAULT_COLOR
1992 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1993 OUTPUT1_IF (tty, tty->TS_orig_pair);
1997 /* Return true if the terminal on frame F supports all of the
1998 capabilities in CAPS simultaneously. */
2000 bool
2001 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2003 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2004 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2005 return 0;
2007 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2008 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2009 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2010 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2011 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2013 /* We can do it! */
2014 return 1;
2017 /* Return non-zero if the terminal is capable to display colors. */
2019 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2020 0, 1, 0,
2021 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2023 TERMINAL can be a terminal object, a frame, or nil (meaning the
2024 selected frame's terminal). This function always returns nil if
2025 TERMINAL does not refer to a text terminal. */)
2026 (Lisp_Object terminal)
2028 struct terminal *t = decode_tty_terminal (terminal);
2030 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2033 /* Return the number of supported colors. */
2034 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2035 Stty_display_color_cells, 0, 1, 0,
2036 doc: /* Return the number of colors supported by the tty device TERMINAL.
2038 TERMINAL can be a terminal object, a frame, or nil (meaning the
2039 selected frame's terminal). This function always returns 0 if
2040 TERMINAL does not refer to a text terminal. */)
2041 (Lisp_Object terminal)
2043 struct terminal *t = decode_tty_terminal (terminal);
2045 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2048 #ifndef DOS_NT
2050 /* Declare here rather than in the function, as in the rest of Emacs,
2051 to work around an HPUX compiler bug (?). See
2052 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2053 static int default_max_colors;
2054 static int default_max_pairs;
2055 static int default_no_color_video;
2056 static char *default_orig_pair;
2057 static char *default_set_foreground;
2058 static char *default_set_background;
2060 /* Save or restore the default color-related capabilities of this
2061 terminal. */
2062 static void
2063 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2066 if (save)
2068 dupstring (&default_orig_pair, tty->TS_orig_pair);
2069 dupstring (&default_set_foreground, tty->TS_set_foreground);
2070 dupstring (&default_set_background, tty->TS_set_background);
2071 default_max_colors = tty->TN_max_colors;
2072 default_max_pairs = tty->TN_max_pairs;
2073 default_no_color_video = tty->TN_no_color_video;
2075 else
2077 tty->TS_orig_pair = default_orig_pair;
2078 tty->TS_set_foreground = default_set_foreground;
2079 tty->TS_set_background = default_set_background;
2080 tty->TN_max_colors = default_max_colors;
2081 tty->TN_max_pairs = default_max_pairs;
2082 tty->TN_no_color_video = default_no_color_video;
2086 /* Setup one of the standard tty color schemes according to MODE.
2087 MODE's value is generally the number of colors which we want to
2088 support; zero means set up for the default capabilities, the ones
2089 we saw at init_tty time; -1 means turn off color support. */
2090 static void
2091 tty_setup_colors (struct tty_display_info *tty, int mode)
2093 /* Canonicalize all negative values of MODE. */
2094 if (mode < -1)
2095 mode = -1;
2097 switch (mode)
2099 case -1: /* no colors at all */
2100 tty->TN_max_colors = 0;
2101 tty->TN_max_pairs = 0;
2102 tty->TN_no_color_video = 0;
2103 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2104 break;
2105 case 0: /* default colors, if any */
2106 default:
2107 tty_default_color_capabilities (tty, 0);
2108 break;
2109 case 8: /* 8 standard ANSI colors */
2110 tty->TS_orig_pair = "\033[0m";
2111 #ifdef TERMINFO
2112 tty->TS_set_foreground = "\033[3%p1%dm";
2113 tty->TS_set_background = "\033[4%p1%dm";
2114 #else
2115 tty->TS_set_foreground = "\033[3%dm";
2116 tty->TS_set_background = "\033[4%dm";
2117 #endif
2118 tty->TN_max_colors = 8;
2119 tty->TN_max_pairs = 64;
2120 tty->TN_no_color_video = 0;
2121 break;
2125 void
2126 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2128 Lisp_Object tem, val;
2129 Lisp_Object color_mode;
2130 int mode;
2131 Lisp_Object tty_color_mode_alist
2132 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2134 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2135 val = CONSP (tem) ? XCDR (tem) : Qnil;
2137 if (INTEGERP (val))
2138 color_mode = val;
2139 else if (SYMBOLP (tty_color_mode_alist))
2141 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2142 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2144 else
2145 color_mode = Qnil;
2147 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2149 if (mode != tty->previous_color_mode)
2151 tty->previous_color_mode = mode;
2152 tty_setup_colors (tty , mode);
2153 /* This recomputes all the faces given the new color definitions. */
2154 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2158 #endif /* !DOS_NT */
2160 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2161 doc: /* Return the type of the tty device that TERMINAL uses.
2162 Returns nil if TERMINAL is not on a tty device.
2164 TERMINAL can be a terminal object, a frame, or nil (meaning the
2165 selected frame's terminal). */)
2166 (Lisp_Object terminal)
2168 struct terminal *t = decode_tty_terminal (terminal);
2170 return (t && t->display_info.tty->type
2171 ? build_string (t->display_info.tty->type) : Qnil);
2174 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2175 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2177 TERMINAL can be a terminal object, a frame, or nil (meaning the
2178 selected frame's terminal). This function always returns nil if
2179 TERMINAL is not on a tty device. */)
2180 (Lisp_Object terminal)
2182 struct terminal *t = decode_tty_terminal (terminal);
2184 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2187 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2188 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2189 This is used to override the terminfo data, for certain terminals that
2190 do not really do underlining, but say that they do. This function has
2191 no effect if used on a non-tty terminal.
2193 TERMINAL can be a terminal object, a frame or nil (meaning the
2194 selected frame's terminal). This function always returns nil if
2195 TERMINAL does not refer to a text terminal. */)
2196 (Lisp_Object terminal)
2198 struct terminal *t = decode_live_terminal (terminal);
2200 if (t->type == output_termcap)
2201 t->display_info.tty->TS_enter_underline_mode = 0;
2202 return Qnil;
2205 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2206 doc: /* Return the topmost terminal frame on TERMINAL.
2207 TERMINAL can be a terminal object, a frame or nil (meaning the
2208 selected frame's terminal). This function returns nil if TERMINAL
2209 does not refer to a text terminal. Otherwise, it returns the
2210 top-most frame on the text terminal. */)
2211 (Lisp_Object terminal)
2213 struct terminal *t = decode_live_terminal (terminal);
2215 if (t->type == output_termcap)
2216 return t->display_info.tty->top_frame;
2217 return Qnil;
2222 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2223 doc: /* Suspend the terminal device TTY.
2225 The device is restored to its default state, and Emacs ceases all
2226 access to the tty device. Frames that use the device are not deleted,
2227 but input is not read from them and if they change, their display is
2228 not updated.
2230 TTY may be a terminal object, a frame, or nil for the terminal device
2231 of the currently selected frame.
2233 This function runs `suspend-tty-functions' after suspending the
2234 device. The functions are run with one arg, the id of the suspended
2235 terminal device.
2237 `suspend-tty' does nothing if it is called on a device that is already
2238 suspended.
2240 A suspended tty may be resumed by calling `resume-tty' on it. */)
2241 (Lisp_Object tty)
2243 struct terminal *t = decode_tty_terminal (tty);
2244 FILE *f;
2246 if (!t)
2247 error ("Attempt to suspend a non-text terminal device");
2249 f = t->display_info.tty->input;
2251 if (f)
2253 /* First run `suspend-tty-functions' and then clean up the tty
2254 state because `suspend-tty-functions' might need to change
2255 the tty state. */
2256 Lisp_Object term;
2257 XSETTERMINAL (term, t);
2258 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2260 reset_sys_modes (t->display_info.tty);
2261 delete_keyboard_wait_descriptor (fileno (f));
2263 #ifndef MSDOS
2264 fclose (f);
2265 if (f != t->display_info.tty->output)
2266 fclose (t->display_info.tty->output);
2267 #endif
2269 t->display_info.tty->input = 0;
2270 t->display_info.tty->output = 0;
2272 if (FRAMEP (t->display_info.tty->top_frame))
2273 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2277 /* Clear display hooks to prevent further output. */
2278 clear_tty_hooks (t);
2280 return Qnil;
2283 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2284 doc: /* Resume the previously suspended terminal device TTY.
2285 The terminal is opened and reinitialized. Frames that are on the
2286 suspended terminal are revived.
2288 It is an error to resume a terminal while another terminal is active
2289 on the same device.
2291 This function runs `resume-tty-functions' after resuming the terminal.
2292 The functions are run with one arg, the id of the resumed terminal
2293 device.
2295 `resume-tty' does nothing if it is called on a device that is not
2296 suspended.
2298 TTY may be a terminal object, a frame, or nil (meaning the selected
2299 frame's terminal). */)
2300 (Lisp_Object tty)
2302 struct terminal *t = decode_tty_terminal (tty);
2303 int fd;
2305 if (!t)
2306 error ("Attempt to resume a non-text terminal device");
2308 if (!t->display_info.tty->input)
2310 if (get_named_terminal (t->display_info.tty->name))
2311 error ("Cannot resume display while another display is active on the same device");
2313 #ifdef MSDOS
2314 t->display_info.tty->output = stdout;
2315 t->display_info.tty->input = stdin;
2316 #else /* !MSDOS */
2317 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2318 t->display_info.tty->input = t->display_info.tty->output
2319 = fd < 0 ? 0 : fdopen (fd, "w+");
2321 if (! t->display_info.tty->input)
2323 int open_errno = errno;
2324 emacs_close (fd);
2325 report_file_errno ("Cannot reopen tty device",
2326 build_string (t->display_info.tty->name),
2327 open_errno);
2330 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2331 dissociate_if_controlling_tty (fd);
2332 #endif
2334 add_keyboard_wait_descriptor (fd);
2336 if (FRAMEP (t->display_info.tty->top_frame))
2338 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2339 int width, height;
2340 int old_height = FRAME_COLS (f);
2341 int old_width = FRAME_TOTAL_LINES (f);
2343 /* Check if terminal/window size has changed while the frame
2344 was suspended. */
2345 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2346 if (width != old_width || height != old_height)
2347 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2348 0, 0, 0, 0);
2349 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2352 set_tty_hooks (t);
2353 init_sys_modes (t->display_info.tty);
2355 /* Run `resume-tty-functions'. */
2356 Lisp_Object term;
2357 XSETTERMINAL (term, t);
2358 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2361 set_tty_hooks (t);
2363 return Qnil;
2367 /***********************************************************************
2368 Mouse
2369 ***********************************************************************/
2371 #ifdef HAVE_GPM
2373 #ifndef HAVE_WINDOW_SYSTEM
2374 void
2375 term_mouse_moveto (int x, int y)
2377 /* TODO: how to set mouse position?
2378 const char *name;
2379 int fd;
2380 name = (const char *) ttyname (0);
2381 fd = emacs_open (name, O_WRONLY, 0);
2382 SOME_FUNCTION (x, y, fd);
2383 emacs_close (fd);
2384 last_mouse_x = x;
2385 last_mouse_y = y; */
2387 #endif /* HAVE_WINDOW_SYSTEM */
2389 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2390 void
2391 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2392 int start_hpos, int end_hpos,
2393 enum draw_glyphs_face draw)
2395 int nglyphs = end_hpos - start_hpos;
2396 struct frame *f = XFRAME (WINDOW_FRAME (w));
2397 struct tty_display_info *tty = FRAME_TTY (f);
2398 int face_id = tty->mouse_highlight.mouse_face_face_id;
2399 int save_x, save_y, pos_x, pos_y;
2401 if (end_hpos >= row->used[TEXT_AREA])
2402 nglyphs = row->used[TEXT_AREA] - start_hpos;
2404 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2405 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2407 /* Save current cursor co-ordinates. */
2408 save_y = curY (tty);
2409 save_x = curX (tty);
2410 cursor_to (f, pos_y, pos_x);
2412 if (draw == DRAW_MOUSE_FACE)
2413 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2414 nglyphs, face_id);
2415 else if (draw == DRAW_NORMAL_TEXT)
2416 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2418 cursor_to (f, save_y, save_x);
2421 static bool
2422 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2424 /* Has the mouse moved off the glyph it was on at the last sighting? */
2425 if (event->x != last_mouse_x || event->y != last_mouse_y)
2427 frame->mouse_moved = 1;
2428 note_mouse_highlight (frame, event->x, event->y);
2429 /* Remember which glyph we're now on. */
2430 last_mouse_x = event->x;
2431 last_mouse_y = event->y;
2432 return 1;
2434 return 0;
2437 /* Return the Time that corresponds to T. Wrap around on overflow. */
2438 static Time
2439 timeval_to_Time (struct timeval const *t)
2441 Time s_1000, ms;
2443 s_1000 = t->tv_sec;
2444 s_1000 *= 1000;
2445 ms = t->tv_usec / 1000;
2446 return s_1000 + ms;
2449 /* Return the current position of the mouse.
2451 Set *f to the frame the mouse is in, or zero if the mouse is in no
2452 Emacs frame. If it is set to zero, all the other arguments are
2453 garbage.
2455 Set *bar_window to Qnil, and *x and *y to the column and
2456 row of the character cell the mouse is over.
2458 Set *timeptr to the time the mouse was at the returned position.
2460 This clears mouse_moved until the next motion
2461 event arrives. */
2462 static void
2463 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2464 enum scroll_bar_part *part, Lisp_Object *x,
2465 Lisp_Object *y, Time *timeptr)
2467 struct timeval now;
2469 *fp = SELECTED_FRAME ();
2470 (*fp)->mouse_moved = 0;
2472 *bar_window = Qnil;
2473 *part = scroll_bar_above_handle;
2475 XSETINT (*x, last_mouse_x);
2476 XSETINT (*y, last_mouse_y);
2477 gettimeofday(&now, 0);
2478 *timeptr = timeval_to_Time (&now);
2481 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2483 If the event is a button press, then note that we have grabbed
2484 the mouse. */
2486 static Lisp_Object
2487 term_mouse_click (struct input_event *result, Gpm_Event *event,
2488 struct frame *f)
2490 struct timeval now;
2491 int i, j;
2493 result->kind = GPM_CLICK_EVENT;
2494 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2496 if (event->buttons & j) {
2497 result->code = i; /* button number */
2498 break;
2501 gettimeofday(&now, 0);
2502 result->timestamp = timeval_to_Time (&now);
2504 if (event->type & GPM_UP)
2505 result->modifiers = up_modifier;
2506 else if (event->type & GPM_DOWN)
2507 result->modifiers = down_modifier;
2508 else
2509 result->modifiers = 0;
2511 if (event->type & GPM_SINGLE)
2512 result->modifiers |= click_modifier;
2514 if (event->type & GPM_DOUBLE)
2515 result->modifiers |= double_modifier;
2517 if (event->type & GPM_TRIPLE)
2518 result->modifiers |= triple_modifier;
2520 if (event->type & GPM_DRAG)
2521 result->modifiers |= drag_modifier;
2523 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2525 /* 1 << KG_SHIFT */
2526 if (event->modifiers & (1 << 0))
2527 result->modifiers |= shift_modifier;
2529 /* 1 << KG_CTRL */
2530 if (event->modifiers & (1 << 2))
2531 result->modifiers |= ctrl_modifier;
2533 /* 1 << KG_ALT || KG_ALTGR */
2534 if (event->modifiers & (1 << 3)
2535 || event->modifiers & (1 << 1))
2536 result->modifiers |= meta_modifier;
2539 XSETINT (result->x, event->x);
2540 XSETINT (result->y, event->y);
2541 XSETFRAME (result->frame_or_window, f);
2542 result->arg = Qnil;
2543 return Qnil;
2547 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2549 struct frame *f = XFRAME (tty->top_frame);
2550 struct input_event ie;
2551 bool do_help = 0;
2552 int count = 0;
2554 EVENT_INIT (ie);
2555 ie.kind = NO_EVENT;
2556 ie.arg = Qnil;
2558 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2559 previous_help_echo_string = help_echo_string;
2560 help_echo_string = Qnil;
2562 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2564 if (!term_mouse_movement (f, event))
2565 help_echo_string = previous_help_echo_string;
2567 /* If the contents of the global variable help_echo_string
2568 has changed, generate a HELP_EVENT. */
2569 if (!NILP (help_echo_string)
2570 || !NILP (previous_help_echo_string))
2571 do_help = 1;
2573 goto done;
2575 else {
2576 f->mouse_moved = 0;
2577 term_mouse_click (&ie, event, f);
2580 done:
2581 if (ie.kind != NO_EVENT)
2583 kbd_buffer_store_event_hold (&ie, hold_quit);
2584 count++;
2587 if (do_help
2588 && !(hold_quit && hold_quit->kind != NO_EVENT))
2590 Lisp_Object frame;
2592 if (f)
2593 XSETFRAME (frame, f);
2594 else
2595 frame = Qnil;
2597 gen_help_event (help_echo_string, frame, help_echo_window,
2598 help_echo_object, help_echo_pos);
2599 count++;
2602 return count;
2605 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2606 0, 0, 0,
2607 doc: /* Open a connection to Gpm.
2608 Gpm-mouse can only be activated for one tty at a time. */)
2609 (void)
2611 struct frame *f = SELECTED_FRAME ();
2612 struct tty_display_info *tty
2613 = ((f)->output_method == output_termcap
2614 ? (f)->terminal->display_info.tty : NULL);
2615 Gpm_Connect connection;
2617 if (!tty)
2618 error ("Gpm-mouse only works in the GNU/Linux console");
2619 if (gpm_tty == tty)
2620 return Qnil; /* Already activated, nothing to do. */
2621 if (gpm_tty)
2622 error ("Gpm-mouse can only be activated for one tty at a time");
2624 connection.eventMask = ~0;
2625 connection.defaultMask = ~GPM_HARD;
2626 connection.maxMod = ~0;
2627 connection.minMod = 0;
2628 gpm_zerobased = 1;
2630 if (Gpm_Open (&connection, 0) < 0)
2631 error ("Gpm-mouse failed to connect to the gpm daemon");
2632 else
2634 gpm_tty = tty;
2635 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2636 to generate SIGIOs. Apparently we need to call reset_sys_modes
2637 before calling init_sys_modes. */
2638 reset_sys_modes (tty);
2639 init_sys_modes (tty);
2640 add_gpm_wait_descriptor (gpm_fd);
2641 return Qnil;
2645 void
2646 close_gpm (int fd)
2648 if (fd >= 0)
2649 delete_gpm_wait_descriptor (fd);
2650 while (Gpm_Close()); /* close all the stack */
2651 gpm_tty = NULL;
2654 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2655 0, 0, 0,
2656 doc: /* Close a connection to Gpm. */)
2657 (void)
2659 struct frame *f = SELECTED_FRAME ();
2660 struct tty_display_info *tty
2661 = ((f)->output_method == output_termcap
2662 ? (f)->terminal->display_info.tty : NULL);
2664 if (!tty || gpm_tty != tty)
2665 return Qnil; /* Not activated on this terminal, nothing to do. */
2667 close_gpm (gpm_fd);
2668 return Qnil;
2670 #endif /* HAVE_GPM */
2673 /***********************************************************************
2674 Menus
2675 ***********************************************************************/
2677 #if !defined (MSDOS)
2679 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2681 However, unlike on MSDOS, where the menu text is drawn directly to
2682 the display video memory, on a TTY we use display_string (see
2683 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2684 the menu items into the frame's 'desired_matrix' glyph matrix, and
2685 then call update_frame_with_menu to deliver the results to the
2686 glass. The previous contents of the screen, in the form of the
2687 current_matrix, is stashed away, and used to restore screen
2688 contents when the menu selection changes or when the final
2689 selection is made and the menu should be popped down.
2691 The idea of this implementation was suggested by Gerd Moellmann. */
2693 #define TTYM_FAILURE -1
2694 #define TTYM_SUCCESS 1
2695 #define TTYM_NO_SELECT 2
2696 #define TTYM_IA_SELECT 3
2697 #define TTYM_NEXT 4
2698 #define TTYM_PREV 5
2700 /* These hold text of the current and the previous menu help messages. */
2701 static const char *menu_help_message, *prev_menu_help_message;
2702 /* Pane number and item number of the menu item which generated the
2703 last menu help message. */
2704 static int menu_help_paneno, menu_help_itemno;
2706 typedef struct tty_menu_struct
2708 int count;
2709 char **text;
2710 struct tty_menu_struct **submenu;
2711 int *panenumber; /* Also used as enabled flag. */
2712 ptrdiff_t allocated;
2713 int panecount;
2714 int width;
2715 const char **help_text;
2716 } tty_menu;
2718 /* Create a brand new menu structure. */
2720 static tty_menu *
2721 tty_menu_create (void)
2723 return xzalloc (sizeof *tty_menu_create ());
2726 /* Allocate some (more) memory for MENU ensuring that there is room for one
2727 more item. */
2729 static void
2730 tty_menu_make_room (tty_menu *menu)
2732 if (menu->allocated == menu->count)
2734 ptrdiff_t allocated = menu->allocated;
2735 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2736 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2737 menu->submenu = xrealloc (menu->submenu,
2738 allocated * sizeof *menu->submenu);
2739 menu->panenumber = xrealloc (menu->panenumber,
2740 allocated * sizeof *menu->panenumber);
2741 menu->help_text = xrealloc (menu->help_text,
2742 allocated * sizeof *menu->help_text);
2743 menu->allocated = allocated;
2747 /* Search the given menu structure for a given pane number. */
2749 static tty_menu *
2750 tty_menu_search_pane (tty_menu *menu, int pane)
2752 int i;
2753 tty_menu *try;
2755 for (i = 0; i < menu->count; i++)
2756 if (menu->submenu[i])
2758 if (pane == menu->panenumber[i])
2759 return menu->submenu[i];
2760 try = tty_menu_search_pane (menu->submenu[i], pane);
2761 if (try)
2762 return try;
2764 return (tty_menu *) 0;
2767 /* Determine how much screen space a given menu needs. */
2769 static void
2770 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2772 int i, h2, w2, maxsubwidth, maxheight;
2774 maxsubwidth = menu->width;
2775 maxheight = menu->count;
2776 for (i = 0; i < menu->count; i++)
2778 if (menu->submenu[i])
2780 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2781 if (w2 > maxsubwidth) maxsubwidth = w2;
2782 if (i + h2 > maxheight) maxheight = i + h2;
2785 *width = maxsubwidth;
2786 *height = maxheight;
2789 static void
2790 mouse_get_xy (int *x, int *y)
2792 struct frame *sf = SELECTED_FRAME ();
2793 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2794 enum scroll_bar_part part_dummy;
2795 Time time_dummy;
2797 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2798 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2799 &lisp_dummy, &part_dummy,
2800 &lmx, &lmy,
2801 &time_dummy);
2802 if (!NILP (lmx))
2804 *x = XINT (lmx);
2805 *y = XINT (lmy);
2809 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2810 (zero-based). */
2812 static void
2813 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2814 int mx, int my, int first_item, bool disp_help)
2816 int i, face, width, enabled, mousehere, row, col;
2817 struct frame *sf = SELECTED_FRAME ();
2818 struct tty_display_info *tty = FRAME_TTY (sf);
2819 /* Don't try to display more menu items than the console can display
2820 using the available screen lines. Exclude the echo area line, as
2821 it will be overwritten by the help-echo anyway. */
2822 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2824 menu_help_message = NULL;
2826 width = menu->width;
2827 col = cursorX (tty);
2828 row = cursorY (tty);
2829 for (i = 0; i < max_items; i++)
2831 int max_width = width + 2; /* +2 for padding blanks on each side */
2832 int j = i + first_item;
2834 if (menu->submenu[j])
2835 max_width += 2; /* for displaying " >" after the item */
2836 enabled
2837 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2838 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2839 face = faces[enabled + mousehere * 2];
2840 /* Display the menu help string for the i-th menu item even if
2841 the menu item is currently disabled. That's what the GUI
2842 code does. */
2843 if (disp_help && enabled + mousehere * 2 >= 2)
2845 menu_help_message = menu->help_text[j];
2846 menu_help_paneno = pn - 1;
2847 menu_help_itemno = j;
2849 /* Take note of the coordinates of the active menu item, to
2850 display the cursor there. */
2851 if (mousehere)
2853 row = y + i;
2854 col = x;
2856 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2857 menu->submenu[j] != NULL);
2859 update_frame_with_menu (sf, row, col);
2862 /* --------------------------- X Menu emulation ---------------------- */
2864 /* Create a new pane and place it on the outer-most level. */
2866 static int
2867 tty_menu_add_pane (tty_menu *menu, const char *txt)
2869 int len;
2871 tty_menu_make_room (menu);
2872 menu->submenu[menu->count] = tty_menu_create ();
2873 menu->text[menu->count] = (char *)txt;
2874 menu->panenumber[menu->count] = ++menu->panecount;
2875 menu->help_text[menu->count] = NULL;
2876 menu->count++;
2878 /* Update the menu width, if necessary. */
2879 len = menu_item_width ((const unsigned char *) txt);
2880 if (len > menu->width)
2881 menu->width = len;
2883 return menu->panecount;
2886 /* Create a new item in a menu pane. */
2888 static bool
2889 tty_menu_add_selection (tty_menu *menu, int pane,
2890 char *txt, bool enable, char const *help_text)
2892 int len;
2894 if (pane)
2896 menu = tty_menu_search_pane (menu, pane);
2897 if (! menu)
2898 return 0;
2900 tty_menu_make_room (menu);
2901 menu->submenu[menu->count] = (tty_menu *) 0;
2902 menu->text[menu->count] = txt;
2903 menu->panenumber[menu->count] = enable;
2904 menu->help_text[menu->count] = help_text;
2905 menu->count++;
2907 /* Update the menu width, if necessary. */
2908 len = menu_item_width ((const unsigned char *) txt);
2909 if (len > menu->width)
2910 menu->width = len;
2912 return 1;
2915 /* Decide where the menu would be placed if requested at (X,Y). */
2917 static void
2918 tty_menu_locate (tty_menu *menu, int x, int y,
2919 int *ulx, int *uly, int *width, int *height)
2921 tty_menu_calc_size (menu, width, height);
2922 *ulx = x + 1;
2923 *uly = y;
2924 *width += 2;
2927 struct tty_menu_state
2929 struct glyph_matrix *screen_behind;
2930 tty_menu *menu;
2931 int pane;
2932 int x, y;
2935 /* Save away the contents of frame F's current frame matrix, and
2936 enable all its rows. Value is a glyph matrix holding the contents
2937 of F's current frame matrix with all its glyph rows enabled. */
2939 static struct glyph_matrix *
2940 save_and_enable_current_matrix (struct frame *f)
2942 int i;
2943 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2944 saved->nrows = f->current_matrix->nrows;
2945 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2947 for (i = 0; i < saved->nrows; ++i)
2949 struct glyph_row *from = f->current_matrix->rows + i;
2950 struct glyph_row *to = saved->rows + i;
2951 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2953 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2954 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2955 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2956 /* Make sure every row is enabled, or else update_frame will not
2957 redraw them. (Rows that are identical to what is already on
2958 screen will not be redrawn anyway.) */
2959 to->enabled_p = true;
2960 to->hash = from->hash;
2963 return saved;
2966 /* Restore the contents of frame F's desired frame matrix from SAVED,
2967 and free memory associated with SAVED. */
2969 static void
2970 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2972 int i;
2974 for (i = 0; i < saved->nrows; ++i)
2976 struct glyph_row *from = saved->rows + i;
2977 struct glyph_row *to = f->desired_matrix->rows + i;
2978 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2980 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2981 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2982 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2983 to->enabled_p = from->enabled_p;
2984 to->hash = from->hash;
2988 static void
2989 free_saved_screen (struct glyph_matrix *saved)
2991 int i;
2993 if (!saved)
2994 return; /* Already freed! */
2996 for (i = 0; i < saved->nrows; ++i)
2998 struct glyph_row *from = saved->rows + i;
3000 xfree (from->glyphs[TEXT_AREA]);
3003 xfree (saved->rows);
3004 xfree (saved);
3007 /* Update the display of frame F from its saved contents. */
3008 static void
3009 screen_update (struct frame *f, struct glyph_matrix *mtx)
3011 restore_desired_matrix (f, mtx);
3012 update_frame_with_menu (f, -1, -1);
3015 typedef enum {
3016 MI_QUIT_MENU = -1,
3017 MI_CONTINUE = 0,
3018 MI_ITEM_SELECTED = 1,
3019 MI_NEXT_ITEM = 2,
3020 MI_PREV_ITEM = 3,
3021 MI_SCROLL_FORWARD = 4,
3022 MI_SCROLL_BACK = 5
3023 } mi_result;
3025 /* Read user input and return X and Y coordinates where that input
3026 puts us. We only consider mouse movement and click events, and
3027 keyboard movement commands; the rest are ignored. */
3028 static mi_result
3029 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3030 bool *first_time)
3032 if (*first_time)
3034 *first_time = false;
3035 sf->mouse_moved = 1;
3037 else
3039 Lisp_Object cmd;
3040 bool usable_input = 1;
3041 mi_result st = MI_CONTINUE;
3042 struct tty_display_info *tty = FRAME_TTY (sf);
3043 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3045 /* Signal the keyboard reading routines we are displaying a menu
3046 on this terminal. */
3047 tty->showing_menu = 1;
3048 /* We want mouse movements be reported by read_menu_command. */
3049 do_mouse_tracking = Qt;
3050 do {
3051 cmd = read_menu_command ();
3052 } while (NILP (cmd));
3053 tty->showing_menu = 0;
3054 do_mouse_tracking = saved_mouse_tracking;
3056 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3057 /* If some input switched frames under our feet, exit the
3058 menu, since the menu faces are no longer valid, and the
3059 menu is no longer relevant anyway. */
3060 || sf != SELECTED_FRAME ())
3061 return MI_QUIT_MENU;
3062 if (EQ (cmd, Qtty_menu_mouse_movement))
3063 mouse_get_xy (x, y);
3064 else if (EQ (cmd, Qtty_menu_next_menu))
3066 usable_input = 0;
3067 st = MI_NEXT_ITEM;
3069 else if (EQ (cmd, Qtty_menu_prev_menu))
3071 usable_input = 0;
3072 st = MI_PREV_ITEM;
3074 else if (EQ (cmd, Qtty_menu_next_item))
3076 if (*y < max_y)
3077 *y += 1;
3078 else
3079 st = MI_SCROLL_FORWARD;
3081 else if (EQ (cmd, Qtty_menu_prev_item))
3083 if (*y > min_y)
3084 *y -= 1;
3085 else
3086 st = MI_SCROLL_BACK;
3088 else if (EQ (cmd, Qtty_menu_select))
3089 st = MI_ITEM_SELECTED;
3090 else if (!EQ (cmd, Qtty_menu_ignore))
3091 usable_input = 0;
3092 if (usable_input)
3093 sf->mouse_moved = 1;
3094 return st;
3096 return MI_CONTINUE;
3099 /* Display menu, wait for user's response, and return that response. */
3100 static int
3101 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3102 int x0, int y0, char **txt,
3103 void (*help_callback)(char const *, int, int),
3104 bool kbd_navigation)
3106 struct tty_menu_state *state;
3107 int statecount, x, y, i;
3108 bool leave, onepane;
3109 int result IF_LINT (= 0);
3110 int title_faces[4]; /* Face to display the menu title. */
3111 int faces[4], buffers_num_deleted = 0;
3112 struct frame *sf = SELECTED_FRAME ();
3113 struct tty_display_info *tty = FRAME_TTY (sf);
3114 bool first_time;
3115 Lisp_Object selectface;
3116 int first_item = 0;
3117 int col, row;
3118 USE_SAFE_ALLOCA;
3120 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3121 around the display. */
3122 if (x0 <= 0)
3123 x0 = 1;
3124 if (y0 <= 0)
3125 y0 = 1;
3127 SAFE_NALLOCA (state, 1, menu->panecount);
3128 memset (state, 0, sizeof (*state));
3129 faces[0]
3130 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3131 DEFAULT_FACE_ID, 1);
3132 faces[1]
3133 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3134 DEFAULT_FACE_ID, 1);
3135 selectface = intern ("tty-menu-selected-face");
3136 faces[2] = lookup_derived_face (sf, selectface,
3137 faces[0], 1);
3138 faces[3] = lookup_derived_face (sf, selectface,
3139 faces[1], 1);
3141 /* Make sure the menu title is always displayed with
3142 `tty-menu-selected-face', no matter where the mouse pointer is. */
3143 for (i = 0; i < 4; i++)
3144 title_faces[i] = faces[3];
3146 statecount = 1;
3148 /* Don't let the title for the "Buffers" popup menu include a
3149 digit (which is ugly).
3151 This is a terrible kludge, but I think the "Buffers" case is
3152 the only one where the title includes a number, so it doesn't
3153 seem to be necessary to make this more general. */
3154 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3156 menu->text[0][7] = '\0';
3157 buffers_num_deleted = 1;
3160 /* Force update of the current frame, so that the desired and the
3161 current matrices are identical. */
3162 update_frame_with_menu (sf, -1, -1);
3163 state[0].menu = menu;
3164 state[0].screen_behind = save_and_enable_current_matrix (sf);
3166 /* Display the menu title. We subtract 1 from x0 and y0 because we
3167 want to interpret them as zero-based column and row coordinates,
3168 and also because we want the first item of the menu, not its
3169 title, to appear at x0,y0. */
3170 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3172 /* Turn off the cursor. Otherwise it shows through the menu
3173 panes, which is ugly. */
3174 col = cursorX (tty);
3175 row = cursorY (tty);
3176 tty_hide_cursor (tty);
3178 if (buffers_num_deleted)
3179 menu->text[0][7] = ' ';
3180 onepane = menu->count == 1 && menu->submenu[0];
3181 if (onepane)
3183 menu->width = menu->submenu[0]->width;
3184 state[0].menu = menu->submenu[0];
3186 else
3188 state[0].menu = menu;
3190 state[0].x = x0 - 1;
3191 state[0].y = y0;
3192 state[0].pane = onepane;
3194 x = state[0].x;
3195 y = state[0].y;
3196 first_time = true;
3198 leave = 0;
3199 while (!leave)
3201 mi_result input_status;
3202 int min_y = state[0].y;
3203 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3205 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3206 if (input_status)
3208 leave = 1;
3209 switch (input_status)
3211 case MI_QUIT_MENU:
3212 /* Remove the last help-echo, so that it doesn't
3213 re-appear after "Quit". */
3214 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3215 result = TTYM_NO_SELECT;
3216 break;
3217 case MI_NEXT_ITEM:
3218 if (kbd_navigation)
3219 result = TTYM_NEXT;
3220 else
3221 leave = 0;
3222 break;
3223 case MI_PREV_ITEM:
3224 if (kbd_navigation)
3225 result = TTYM_PREV;
3226 else
3227 leave = 0;
3228 break;
3229 case MI_SCROLL_FORWARD:
3230 if (y - min_y == state[0].menu->count - 1 - first_item)
3232 y = min_y;
3233 first_item = 0;
3235 else
3236 first_item++;
3237 leave = 0;
3238 break;
3239 case MI_SCROLL_BACK:
3240 if (first_item == 0)
3242 y = max_y;
3243 first_item = state[0].menu->count - 1 - (y - min_y);
3245 else
3246 first_item--;
3247 leave = 0;
3248 break;
3249 default:
3250 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3251 break;
3254 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3256 sf->mouse_moved = 0;
3257 result = TTYM_IA_SELECT;
3258 for (i = 0; i < statecount; i++)
3259 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3261 int dy = y - state[i].y + first_item;
3262 if (0 <= dy && dy < state[i].menu->count)
3264 if (!state[i].menu->submenu[dy])
3266 if (state[i].menu->panenumber[dy])
3267 result = TTYM_SUCCESS;
3268 else
3269 result = TTYM_IA_SELECT;
3271 *pane = state[i].pane - 1;
3272 *selidx = dy;
3273 /* We hit some part of a menu, so drop extra menus that
3274 have been opened. That does not include an open and
3275 active submenu. */
3276 if (i != statecount - 2
3277 || state[i].menu->submenu[dy] != state[i + 1].menu)
3278 while (i != statecount - 1)
3280 statecount--;
3281 screen_update (sf, state[statecount].screen_behind);
3282 state[statecount].screen_behind = NULL;
3284 if (i == statecount - 1 && state[i].menu->submenu[dy])
3286 tty_menu_display (state[i].menu,
3287 state[i].x,
3288 state[i].y,
3289 state[i].pane,
3290 faces, x, y, first_item, 1);
3291 state[statecount].menu = state[i].menu->submenu[dy];
3292 state[statecount].pane = state[i].menu->panenumber[dy];
3293 state[statecount].screen_behind
3294 = save_and_enable_current_matrix (sf);
3295 state[statecount].x
3296 = state[i].x + state[i].menu->width + 2;
3297 state[statecount].y = y;
3298 statecount++;
3302 tty_menu_display (state[statecount - 1].menu,
3303 state[statecount - 1].x,
3304 state[statecount - 1].y,
3305 state[statecount - 1].pane,
3306 faces, x, y, first_item, 1);
3307 /* The call to display help-echo below will move the cursor,
3308 so remember its current position as computed by
3309 tty_menu_display. */
3310 col = cursorX (tty);
3311 row = cursorY (tty);
3314 /* Display the help-echo message for the currently-selected menu
3315 item. */
3316 if ((menu_help_message || prev_menu_help_message)
3317 && menu_help_message != prev_menu_help_message)
3319 help_callback (menu_help_message,
3320 menu_help_paneno, menu_help_itemno);
3321 /* Move the cursor to the beginning of the current menu
3322 item, so that screen readers and other accessibility aids
3323 know where the active region is. */
3324 cursor_to (sf, row, col);
3325 prev_menu_help_message = menu_help_message;
3327 /* Both tty_menu_display and help_callback invoke update_end,
3328 which calls tty_show_cursor. Re-hide it, so it doesn't show
3329 through the menus. */
3330 tty_hide_cursor (tty);
3331 fflush (tty->output);
3334 sf->mouse_moved = 0;
3335 screen_update (sf, state[0].screen_behind);
3336 while (statecount--)
3337 free_saved_screen (state[statecount].screen_behind);
3338 tty_show_cursor (tty); /* Turn cursor back on. */
3339 fflush (tty->output);
3341 /* Clean up any mouse events that are waiting inside Emacs event queue.
3342 These events are likely to be generated before the menu was even
3343 displayed, probably because the user pressed and released the button
3344 (which invoked the menu) too quickly. If we don't remove these events,
3345 Emacs will process them after we return and surprise the user. */
3346 discard_mouse_events ();
3347 if (!kbd_buffer_events_waiting ())
3348 clear_input_pending ();
3349 SAFE_FREE ();
3350 return result;
3353 /* Dispose of a menu. */
3355 static void
3356 tty_menu_destroy (tty_menu *menu)
3358 int i;
3359 if (menu->allocated)
3361 for (i = 0; i < menu->count; i++)
3362 if (menu->submenu[i])
3363 tty_menu_destroy (menu->submenu[i]);
3364 xfree (menu->text);
3365 xfree (menu->submenu);
3366 xfree (menu->panenumber);
3367 xfree (menu->help_text);
3369 xfree (menu);
3370 menu_help_message = prev_menu_help_message = NULL;
3373 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3375 PANE is the pane number, and ITEM is the menu item number in
3376 the menu (currently not used). */
3378 static void
3379 tty_menu_help_callback (char const *help_string, int pane, int item)
3381 Lisp_Object *first_item;
3382 Lisp_Object pane_name;
3383 Lisp_Object menu_object;
3385 first_item = XVECTOR (menu_items)->contents;
3386 if (EQ (first_item[0], Qt))
3387 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3388 else if (EQ (first_item[0], Qquote))
3389 /* This shouldn't happen, see xmenu_show. */
3390 pane_name = empty_unibyte_string;
3391 else
3392 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3394 /* (menu-item MENU-NAME PANE-NUMBER) */
3395 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3396 show_help_echo (help_string ? build_string (help_string) : Qnil,
3397 Qnil, menu_object, make_number (item));
3400 static void
3401 tty_pop_down_menu (Lisp_Object arg)
3403 tty_menu *menu = XSAVE_POINTER (arg, 0);
3405 block_input ();
3406 tty_menu_destroy (menu);
3407 unblock_input ();
3410 /* Return the zero-based index of the last menu-bar item on frame F. */
3411 static int
3412 tty_menu_last_menubar_item (struct frame *f)
3414 int i = 0;
3416 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3417 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3419 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3421 while (i < ASIZE (items))
3423 Lisp_Object str;
3425 str = AREF (items, i + 1);
3426 if (NILP (str))
3427 break;
3428 i += 4;
3430 i -= 4; /* Went one too far! */
3432 return i;
3435 /* Find in frame F's menu bar the menu item that is next or previous
3436 to the item at X/Y, and return that item's position in X/Y. WHICH
3437 says which one--next or previous--item to look for. X and Y are
3438 measured in character cells. This should only be called on TTY
3439 frames. */
3440 static void
3441 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3443 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3444 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3446 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3447 int last_i = tty_menu_last_menubar_item (f);
3448 int i, prev_x;
3450 /* This loop assumes a single menu-bar line, and will fail to
3451 find an item if it is not in the first line. Note that
3452 make_lispy_event in keyboard.c makes the same assumption. */
3453 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3455 Lisp_Object pos, str;
3456 int ix;
3458 str = AREF (items, i + 1);
3459 pos = AREF (items, i + 3);
3460 if (NILP (str))
3461 return;
3462 ix = XINT (pos);
3463 if (ix <= *x
3464 /* We use <= so the blank between 2 items on a TTY is
3465 considered part of the previous item. */
3466 && *x <= ix + menu_item_width (SDATA (str)))
3468 /* Found current item. Now compute the X coordinate of
3469 the previous or next item. */
3470 if (which == TTYM_NEXT)
3472 if (i < last_i)
3473 *x = XINT (AREF (items, i + 4 + 3));
3474 else
3475 *x = 0; /* Wrap around to the first item. */
3477 else if (prev_x < 0)
3479 /* Wrap around to the last item. */
3480 *x = XINT (AREF (items, last_i + 3));
3482 else
3483 *x = prev_x;
3484 return;
3486 prev_x = ix;
3491 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3492 Lisp_Object
3493 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3494 Lisp_Object title, const char **error_name)
3496 tty_menu *menu;
3497 int pane, selidx, lpane, status;
3498 Lisp_Object entry, pane_prefix;
3499 char *datap;
3500 int ulx, uly, width, height;
3501 int item_x, item_y;
3502 int dispwidth, dispheight;
3503 int i, j, lines, maxlines;
3504 int maxwidth;
3505 ptrdiff_t specpdl_count;
3507 eassert (FRAME_TERMCAP_P (f));
3509 *error_name = 0;
3510 if (menu_items_n_panes == 0)
3511 return Qnil;
3513 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3515 *error_name = "Empty menu";
3516 return Qnil;
3519 /* Make the menu on that window. */
3520 menu = tty_menu_create ();
3522 /* Don't GC while we prepare and show the menu, because we give the
3523 menu functions pointers to the contents of strings. */
3524 specpdl_count = inhibit_garbage_collection ();
3526 /* Avoid crashes if, e.g., another client will connect while we
3527 are in a menu. */
3528 temporarily_switch_to_single_kboard (f);
3530 /* Adjust coordinates to be root-window-relative. */
3531 item_x = x += f->left_pos;
3532 item_y = y += f->top_pos;
3534 /* Create all the necessary panes and their items. */
3535 USE_SAFE_ALLOCA;
3536 maxwidth = maxlines = lines = i = 0;
3537 lpane = TTYM_FAILURE;
3538 while (i < menu_items_used)
3540 if (EQ (AREF (menu_items, i), Qt))
3542 /* Create a new pane. */
3543 Lisp_Object pane_name, prefix;
3544 const char *pane_string;
3546 maxlines = max (maxlines, lines);
3547 lines = 0;
3548 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3549 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3550 pane_string = (NILP (pane_name)
3551 ? "" : SSDATA (pane_name));
3552 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3553 pane_string++;
3555 lpane = tty_menu_add_pane (menu, pane_string);
3556 if (lpane == TTYM_FAILURE)
3558 tty_menu_destroy (menu);
3559 *error_name = "Can't create pane";
3560 entry = Qnil;
3561 goto tty_menu_end;
3563 i += MENU_ITEMS_PANE_LENGTH;
3565 /* Find the width of the widest item in this pane. */
3566 j = i;
3567 while (j < menu_items_used)
3569 Lisp_Object item;
3570 item = AREF (menu_items, j);
3571 if (EQ (item, Qt))
3572 break;
3573 if (NILP (item))
3575 j++;
3576 continue;
3578 width = SBYTES (item);
3579 if (width > maxwidth)
3580 maxwidth = width;
3582 j += MENU_ITEMS_ITEM_LENGTH;
3585 /* Ignore a nil in the item list.
3586 It's meaningful only for dialog boxes. */
3587 else if (EQ (AREF (menu_items, i), Qquote))
3588 i += 1;
3589 else
3591 /* Create a new item within current pane. */
3592 Lisp_Object item_name, enable, descrip, help;
3593 char *item_data;
3594 char const *help_string;
3596 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3597 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3598 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3599 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3600 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3602 if (!NILP (descrip))
3604 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3605 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3606 for (j = SCHARS (item_name); j < maxwidth; j++)
3607 item_data[j] = ' ';
3608 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3609 item_data[j + SBYTES (descrip)] = 0;
3611 else
3612 item_data = SSDATA (item_name);
3614 if (lpane == TTYM_FAILURE
3615 || (! tty_menu_add_selection (menu, lpane, item_data,
3616 !NILP (enable), help_string)))
3618 tty_menu_destroy (menu);
3619 *error_name = "Can't add selection to menu";
3620 entry = Qnil;
3621 goto tty_menu_end;
3623 i += MENU_ITEMS_ITEM_LENGTH;
3624 lines++;
3628 maxlines = max (maxlines, lines);
3630 /* All set and ready to fly. */
3631 dispwidth = f->text_cols;
3632 dispheight = f->text_lines;
3633 x = min (x, dispwidth);
3634 y = min (y, dispheight);
3635 x = max (x, 1);
3636 y = max (y, 1);
3637 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3638 if (ulx + width > dispwidth)
3640 x -= (ulx + width) - dispwidth;
3641 ulx = dispwidth - width;
3643 if (uly + height > dispheight)
3645 y -= (uly + height) - dispheight;
3646 uly = dispheight - height;
3649 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3651 /* Move the menu away of the echo area, to avoid overwriting the
3652 menu with help echo messages or vice versa. */
3653 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3655 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3656 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3658 else
3660 y -= 2;
3661 uly -= 2;
3665 if (ulx < 0) x -= ulx;
3666 if (uly < 0) y -= uly;
3668 #if 0
3669 /* This code doesn't make sense on a TTY, since it can easily annul
3670 the adjustments above that carefully avoid truncation of the menu
3671 items. I think it was written to fix some problem that only
3672 happens on X11. */
3673 if (! for_click)
3675 /* If position was not given by a mouse click, adjust so upper left
3676 corner of the menu as a whole ends up at given coordinates. This
3677 is what x-popup-menu says in its documentation. */
3678 x += width / 2;
3679 y += 1.5 * height / (maxlines + 2);
3681 #endif
3683 pane = selidx = 0;
3685 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3687 specbind (Qoverriding_terminal_local_map,
3688 Fsymbol_value (Qtty_menu_navigation_map));
3689 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3690 tty_menu_help_callback,
3691 menuflags & MENU_KBD_NAVIGATION);
3692 entry = pane_prefix = Qnil;
3694 switch (status)
3696 case TTYM_SUCCESS:
3697 /* Find the item number SELIDX in pane number PANE. */
3698 i = 0;
3699 while (i < menu_items_used)
3701 if (EQ (AREF (menu_items, i), Qt))
3703 if (pane == 0)
3704 pane_prefix
3705 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3706 pane--;
3707 i += MENU_ITEMS_PANE_LENGTH;
3709 else
3711 if (pane == -1)
3713 if (selidx == 0)
3715 entry
3716 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3717 if (menuflags & MENU_KEYMAPS)
3719 entry = Fcons (entry, Qnil);
3720 if (!NILP (pane_prefix))
3721 entry = Fcons (pane_prefix, entry);
3723 break;
3725 selidx--;
3727 i += MENU_ITEMS_ITEM_LENGTH;
3730 break;
3732 case TTYM_NEXT:
3733 case TTYM_PREV:
3734 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3735 entry = Fcons (make_number (item_x), make_number (item_y));
3736 break;
3738 case TTYM_FAILURE:
3739 *error_name = "Can't activate menu";
3740 case TTYM_IA_SELECT:
3741 break;
3742 case TTYM_NO_SELECT:
3743 /* If the selected frame was changed while we displayed a menu,
3744 throw to top level in order to undo any temporary settings
3745 made by TTY menu code. */
3746 if (f != SELECTED_FRAME ())
3747 Ftop_level ();
3748 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3749 the menu was invoked with a mouse event as POSITION). */
3750 if (!(menuflags & MENU_FOR_CLICK))
3751 Fsignal (Qquit, Qnil);
3752 break;
3755 tty_menu_end:
3757 SAFE_FREE ();
3758 unbind_to (specpdl_count, Qnil);
3759 return entry;
3762 #endif /* !MSDOS */
3765 #ifndef MSDOS
3766 /***********************************************************************
3767 Initialization
3768 ***********************************************************************/
3770 /* Initialize the tty-dependent part of frame F. The frame must
3771 already have its device initialized. */
3773 void
3774 create_tty_output (struct frame *f)
3776 struct tty_output *t = xzalloc (sizeof *t);
3778 eassert (FRAME_TERMCAP_P (f));
3780 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3782 f->output_data.tty = t;
3785 /* Delete frame F's face cache, and its tty-dependent part. */
3787 static void
3788 tty_free_frame_resources (struct frame *f)
3790 eassert (FRAME_TERMCAP_P (f));
3791 free_frame_faces (f);
3792 xfree (f->output_data.tty);
3795 #else /* MSDOS */
3797 /* Delete frame F's face cache. */
3799 static void
3800 tty_free_frame_resources (struct frame *f)
3802 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3803 free_frame_faces (f);
3805 #endif /* MSDOS */
3807 /* Reset the hooks in TERMINAL. */
3809 static void
3810 clear_tty_hooks (struct terminal *terminal)
3812 terminal->rif = 0;
3813 terminal->cursor_to_hook = 0;
3814 terminal->raw_cursor_to_hook = 0;
3815 terminal->clear_to_end_hook = 0;
3816 terminal->clear_frame_hook = 0;
3817 terminal->clear_end_of_line_hook = 0;
3818 terminal->ins_del_lines_hook = 0;
3819 terminal->insert_glyphs_hook = 0;
3820 terminal->write_glyphs_hook = 0;
3821 terminal->delete_glyphs_hook = 0;
3822 terminal->ring_bell_hook = 0;
3823 terminal->reset_terminal_modes_hook = 0;
3824 terminal->set_terminal_modes_hook = 0;
3825 terminal->update_begin_hook = 0;
3826 terminal->update_end_hook = 0;
3827 terminal->set_terminal_window_hook = 0;
3828 terminal->mouse_position_hook = 0;
3829 terminal->frame_rehighlight_hook = 0;
3830 terminal->frame_raise_lower_hook = 0;
3831 terminal->fullscreen_hook = 0;
3832 terminal->menu_show_hook = 0;
3833 terminal->set_vertical_scroll_bar_hook = 0;
3834 terminal->set_horizontal_scroll_bar_hook = 0;
3835 terminal->condemn_scroll_bars_hook = 0;
3836 terminal->redeem_scroll_bar_hook = 0;
3837 terminal->judge_scroll_bars_hook = 0;
3838 terminal->read_socket_hook = 0;
3839 terminal->frame_up_to_date_hook = 0;
3841 /* Leave these two set, or suspended frames are not deleted
3842 correctly. */
3843 terminal->delete_frame_hook = &tty_free_frame_resources;
3844 terminal->delete_terminal_hook = &delete_tty;
3847 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3849 static void
3850 set_tty_hooks (struct terminal *terminal)
3852 terminal->cursor_to_hook = &tty_cursor_to;
3853 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3854 terminal->clear_to_end_hook = &tty_clear_to_end;
3855 terminal->clear_frame_hook = &tty_clear_frame;
3856 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3857 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3858 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3859 terminal->write_glyphs_hook = &tty_write_glyphs;
3860 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3861 terminal->ring_bell_hook = &tty_ring_bell;
3862 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3863 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3864 terminal->update_end_hook = &tty_update_end;
3865 #ifdef MSDOS
3866 terminal->menu_show_hook = &x_menu_show;
3867 #else
3868 terminal->menu_show_hook = &tty_menu_show;
3869 #endif
3870 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3871 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3872 terminal->delete_frame_hook = &tty_free_frame_resources;
3873 terminal->delete_terminal_hook = &delete_tty;
3874 /* Other hooks are NULL by default. */
3877 /* If FD is the controlling terminal, drop it. */
3878 static void
3879 dissociate_if_controlling_tty (int fd)
3881 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3882 so dissociate it by invoking setsid. */
3883 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3885 #ifdef TIOCNOTTY
3886 /* setsid failed, presumably because Emacs is already a process
3887 group leader. Fall back on the obsolescent way to dissociate
3888 a controlling tty. */
3889 sigset_t oldset;
3890 block_tty_out_signal (&oldset);
3891 ioctl (fd, TIOCNOTTY, 0);
3892 unblock_tty_out_signal (&oldset);
3893 #endif
3897 /* Create a termcap display on the tty device with the given name and
3898 type.
3900 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3901 Otherwise NAME should be a path to the tty device file,
3902 e.g. "/dev/pts/7".
3904 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3906 If MUST_SUCCEED is true, then all errors are fatal. */
3908 struct terminal *
3909 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3911 char *area;
3912 char **address = &area;
3913 int status;
3914 struct tty_display_info *tty = NULL;
3915 struct terminal *terminal = NULL;
3916 sigset_t oldset;
3917 bool ctty = false; /* True if asked to open controlling tty. */
3919 if (!terminal_type)
3920 maybe_fatal (must_succeed, 0,
3921 "Unknown terminal type",
3922 "Unknown terminal type");
3924 if (name == NULL)
3925 name = DEV_TTY;
3926 if (!strcmp (name, DEV_TTY))
3927 ctty = 1;
3929 /* If we already have a terminal on the given device, use that. If
3930 all such terminals are suspended, create a new one instead. */
3931 /* XXX Perhaps this should be made explicit by having init_tty
3932 always create a new terminal and separating terminal and frame
3933 creation on Lisp level. */
3934 terminal = get_named_terminal (name);
3935 if (terminal)
3936 return terminal;
3938 terminal = create_terminal (output_termcap, NULL);
3939 #ifdef MSDOS
3940 if (been_here > 0)
3941 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3942 name, "");
3943 been_here = 1;
3944 tty = &the_only_display_info;
3945 #else
3946 tty = xzalloc (sizeof *tty);
3947 #endif
3948 tty->top_frame = Qnil;
3949 tty->next = tty_list;
3950 tty_list = tty;
3952 terminal->display_info.tty = tty;
3953 tty->terminal = terminal;
3955 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3956 Wcm_clear (tty);
3958 encode_terminal_src_size = 0;
3959 encode_terminal_dst_size = 0;
3962 #ifndef DOS_NT
3963 set_tty_hooks (terminal);
3966 /* Open the terminal device. */
3968 /* If !ctty, don't recognize it as our controlling terminal, and
3969 don't make it the controlling tty if we don't have one now.
3971 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3972 defined on Hurd. On other systems, we need to explicitly
3973 dissociate ourselves from the controlling tty when we want to
3974 open a frame on the same terminal. */
3975 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3976 int fd = emacs_open (name, flags, 0);
3977 tty->input = tty->output
3978 = ((fd < 0 || ! isatty (fd))
3979 ? NULL
3980 : fdopen (fd, "w+"));
3982 if (! tty->input)
3984 char const *diagnostic
3985 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3986 emacs_close (fd);
3987 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
3990 tty->name = xstrdup (name);
3991 terminal->name = xstrdup (name);
3993 if (!O_IGNORE_CTTY && !ctty)
3994 dissociate_if_controlling_tty (fd);
3997 tty->type = xstrdup (terminal_type);
3999 add_keyboard_wait_descriptor (fileno (tty->input));
4001 Wcm_clear (tty);
4003 /* On some systems, tgetent tries to access the controlling
4004 terminal. */
4005 block_tty_out_signal (&oldset);
4006 status = tgetent (tty->termcap_term_buffer, terminal_type);
4007 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4008 emacs_abort ();
4009 unblock_tty_out_signal (&oldset);
4011 if (status < 0)
4013 #ifdef TERMINFO
4014 maybe_fatal (must_succeed, terminal,
4015 "Cannot open terminfo database file",
4016 "Cannot open terminfo database file");
4017 #else
4018 maybe_fatal (must_succeed, terminal,
4019 "Cannot open termcap database file",
4020 "Cannot open termcap database file");
4021 #endif
4023 if (status == 0)
4025 maybe_fatal (must_succeed, terminal,
4026 "Terminal type %s is not defined",
4027 "Terminal type %s is not defined.\n\
4028 If that is not the actual type of terminal you have,\n\
4029 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4030 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4031 #ifdef TERMINFO
4032 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4033 #else
4034 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4035 #endif
4036 terminal_type);
4039 area = tty->termcap_strings_buffer;
4040 tty->TS_ins_line = tgetstr ("al", address);
4041 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4042 tty->TS_bell = tgetstr ("bl", address);
4043 BackTab (tty) = tgetstr ("bt", address);
4044 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4045 tty->TS_clr_line = tgetstr ("ce", address);
4046 tty->TS_clr_frame = tgetstr ("cl", address);
4047 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4048 AbsPosition (tty) = tgetstr ("cm", address);
4049 CR (tty) = tgetstr ("cr", address);
4050 tty->TS_set_scroll_region = tgetstr ("cs", address);
4051 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4052 RowPosition (tty) = tgetstr ("cv", address);
4053 tty->TS_del_char = tgetstr ("dc", address);
4054 tty->TS_del_multi_chars = tgetstr ("DC", address);
4055 tty->TS_del_line = tgetstr ("dl", address);
4056 tty->TS_del_multi_lines = tgetstr ("DL", address);
4057 tty->TS_delete_mode = tgetstr ("dm", address);
4058 tty->TS_end_delete_mode = tgetstr ("ed", address);
4059 tty->TS_end_insert_mode = tgetstr ("ei", address);
4060 Home (tty) = tgetstr ("ho", address);
4061 tty->TS_ins_char = tgetstr ("ic", address);
4062 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4063 tty->TS_insert_mode = tgetstr ("im", address);
4064 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4065 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4066 tty->TS_keypad_mode = tgetstr ("ks", address);
4067 LastLine (tty) = tgetstr ("ll", address);
4068 Right (tty) = tgetstr ("nd", address);
4069 Down (tty) = tgetstr ("do", address);
4070 if (!Down (tty))
4071 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4072 if (tgetflag ("bs"))
4073 Left (tty) = "\b"; /* Can't possibly be longer! */
4074 else /* (Actually, "bs" is obsolete...) */
4075 Left (tty) = tgetstr ("le", address);
4076 if (!Left (tty))
4077 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4078 tty->TS_pad_char = tgetstr ("pc", address);
4079 tty->TS_repeat = tgetstr ("rp", address);
4080 tty->TS_end_standout_mode = tgetstr ("se", address);
4081 tty->TS_fwd_scroll = tgetstr ("sf", address);
4082 tty->TS_standout_mode = tgetstr ("so", address);
4083 tty->TS_rev_scroll = tgetstr ("sr", address);
4084 tty->Wcm->cm_tab = tgetstr ("ta", address);
4085 tty->TS_end_termcap_modes = tgetstr ("te", address);
4086 tty->TS_termcap_modes = tgetstr ("ti", address);
4087 Up (tty) = tgetstr ("up", address);
4088 tty->TS_visible_bell = tgetstr ("vb", address);
4089 tty->TS_cursor_normal = tgetstr ("ve", address);
4090 tty->TS_cursor_visible = tgetstr ("vs", address);
4091 tty->TS_cursor_invisible = tgetstr ("vi", address);
4092 tty->TS_set_window = tgetstr ("wi", address);
4094 tty->TS_enter_underline_mode = tgetstr ("us", address);
4095 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4096 tty->TS_enter_bold_mode = tgetstr ("md", address);
4097 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4098 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4099 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4100 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4101 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4102 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4104 MultiUp (tty) = tgetstr ("UP", address);
4105 MultiDown (tty) = tgetstr ("DO", address);
4106 MultiLeft (tty) = tgetstr ("LE", address);
4107 MultiRight (tty) = tgetstr ("RI", address);
4109 /* SVr4/ANSI color support. If "op" isn't available, don't support
4110 color because we can't switch back to the default foreground and
4111 background. */
4112 tty->TS_orig_pair = tgetstr ("op", address);
4113 if (tty->TS_orig_pair)
4115 tty->TS_set_foreground = tgetstr ("AF", address);
4116 tty->TS_set_background = tgetstr ("AB", address);
4117 if (!tty->TS_set_foreground)
4119 /* SVr4. */
4120 tty->TS_set_foreground = tgetstr ("Sf", address);
4121 tty->TS_set_background = tgetstr ("Sb", address);
4124 tty->TN_max_colors = tgetnum ("Co");
4125 tty->TN_max_pairs = tgetnum ("pa");
4127 tty->TN_no_color_video = tgetnum ("NC");
4128 if (tty->TN_no_color_video == -1)
4129 tty->TN_no_color_video = 0;
4132 tty_default_color_capabilities (tty, 1);
4134 MagicWrap (tty) = tgetflag ("xn");
4135 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4136 the former flag imply the latter. */
4137 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4138 tty->memory_below_frame = tgetflag ("db");
4139 tty->TF_hazeltine = tgetflag ("hz");
4140 tty->must_write_spaces = tgetflag ("in");
4141 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4142 tty->TF_insmode_motion = tgetflag ("mi");
4143 tty->TF_standout_motion = tgetflag ("ms");
4144 tty->TF_underscore = tgetflag ("ul");
4145 tty->TF_teleray = tgetflag ("xt");
4147 #else /* DOS_NT */
4148 #ifdef WINDOWSNT
4150 struct frame *f = XFRAME (selected_frame);
4151 int height, width;
4153 initialize_w32_display (terminal, &width, &height);
4155 FrameRows (tty) = height;
4156 FrameCols (tty) = width;
4157 tty->specified_window = height;
4159 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4160 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4161 tty->char_ins_del_ok = 1;
4162 baud_rate = 19200;
4164 #else /* MSDOS */
4166 int height, width;
4167 if (strcmp (terminal_type, "internal") == 0)
4168 terminal->type = output_msdos_raw;
4169 initialize_msdos_display (terminal);
4171 get_tty_size (fileno (tty->input), &width, &height);
4172 FrameCols (tty) = width;
4173 FrameRows (tty) = height;
4174 tty->char_ins_del_ok = 0;
4175 init_baud_rate (fileno (tty->input));
4177 #endif /* MSDOS */
4178 tty->output = stdout;
4179 tty->input = stdin;
4180 /* The following two are inaccessible from w32console.c. */
4181 terminal->delete_frame_hook = &tty_free_frame_resources;
4182 terminal->delete_terminal_hook = &delete_tty;
4184 tty->name = xstrdup (name);
4185 terminal->name = xstrdup (name);
4186 tty->type = xstrdup (terminal_type);
4188 add_keyboard_wait_descriptor (0);
4190 tty->delete_in_insert_mode = 1;
4192 UseTabs (tty) = 0;
4193 tty->scroll_region_ok = 0;
4195 /* Seems to insert lines when it's not supposed to, messing up the
4196 display. In doing a trace, it didn't seem to be called much, so I
4197 don't think we're losing anything by turning it off. */
4198 tty->line_ins_del_ok = 0;
4200 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4201 #endif /* DOS_NT */
4203 #ifdef HAVE_GPM
4204 terminal->mouse_position_hook = term_mouse_position;
4205 tty->mouse_highlight.mouse_face_window = Qnil;
4206 #endif
4208 terminal->kboard = allocate_kboard (Qnil);
4209 terminal->kboard->reference_count++;
4210 /* Don't let the initial kboard remain current longer than necessary.
4211 That would cause problems if a file loaded on startup tries to
4212 prompt in the mini-buffer. */
4213 if (current_kboard == initial_kboard)
4214 current_kboard = terminal->kboard;
4215 #ifndef DOS_NT
4216 term_get_fkeys (address, terminal->kboard);
4218 /* Get frame size from system, or else from termcap. */
4220 int height, width;
4221 get_tty_size (fileno (tty->input), &width, &height);
4222 FrameCols (tty) = width;
4223 FrameRows (tty) = height;
4226 if (FrameCols (tty) <= 0)
4227 FrameCols (tty) = tgetnum ("co");
4228 if (FrameRows (tty) <= 0)
4229 FrameRows (tty) = tgetnum ("li");
4231 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4232 maybe_fatal (must_succeed, terminal,
4233 "Screen size %dx%d is too small",
4234 "Screen size %dx%d is too small",
4235 FrameCols (tty), FrameRows (tty));
4237 TabWidth (tty) = tgetnum ("tw");
4239 if (!tty->TS_bell)
4240 tty->TS_bell = "\07";
4242 if (!tty->TS_fwd_scroll)
4243 tty->TS_fwd_scroll = Down (tty);
4245 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4247 if (TabWidth (tty) < 0)
4248 TabWidth (tty) = 8;
4250 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4251 and newer termcap doc does not seem to say there is a default.
4252 if (!tty->Wcm->cm_tab)
4253 tty->Wcm->cm_tab = "\t";
4256 /* We don't support standout modes that use `magic cookies', so
4257 turn off any that do. */
4258 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4260 tty->TS_standout_mode = 0;
4261 tty->TS_end_standout_mode = 0;
4263 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4265 tty->TS_enter_underline_mode = 0;
4266 tty->TS_exit_underline_mode = 0;
4269 /* If there's no standout mode, try to use underlining instead. */
4270 if (tty->TS_standout_mode == 0)
4272 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4273 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4276 /* If no `se' string, try using a `me' string instead.
4277 If that fails, we can't use standout mode at all. */
4278 if (tty->TS_end_standout_mode == 0)
4280 char *s = tgetstr ("me", address);
4281 if (s != 0)
4282 tty->TS_end_standout_mode = s;
4283 else
4284 tty->TS_standout_mode = 0;
4287 if (tty->TF_teleray)
4289 tty->Wcm->cm_tab = 0;
4290 /* We can't support standout mode, because it uses magic cookies. */
4291 tty->TS_standout_mode = 0;
4292 /* But that means we cannot rely on ^M to go to column zero! */
4293 CR (tty) = 0;
4294 /* LF can't be trusted either -- can alter hpos. */
4295 /* If move at column 0 thru a line with TS_standout_mode. */
4296 Down (tty) = 0;
4299 tty->specified_window = FrameRows (tty);
4301 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4303 maybe_fatal (must_succeed, terminal,
4304 "Terminal type \"%s\" is not powerful enough to run Emacs",
4305 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4306 It lacks the ability to position the cursor.\n\
4307 If that is not the actual type of terminal you have,\n\
4308 use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
4309 `setenv TERM ...') to specify the correct type. It may be necessary\n"
4310 # ifdef TERMINFO
4311 "to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
4312 # else /* TERMCAP */
4313 "to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
4314 # endif /* TERMINFO */
4315 terminal_type);
4318 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4319 maybe_fatal (must_succeed, terminal,
4320 "Could not determine the frame size",
4321 "Could not determine the frame size");
4323 tty->delete_in_insert_mode
4324 = tty->TS_delete_mode && tty->TS_insert_mode
4325 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4327 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4329 tty->scroll_region_ok
4330 = (tty->Wcm->cm_abs
4331 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4333 tty->line_ins_del_ok
4334 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4335 && (tty->TS_del_line || tty->TS_del_multi_lines))
4336 || (tty->scroll_region_ok
4337 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4339 tty->char_ins_del_ok
4340 = ((tty->TS_ins_char || tty->TS_insert_mode
4341 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4342 && (tty->TS_del_char || tty->TS_del_multi_chars));
4344 init_baud_rate (fileno (tty->input));
4346 #endif /* not DOS_NT */
4348 /* Init system terminal modes (RAW or CBREAK, etc.). */
4349 init_sys_modes (tty);
4351 return terminal;
4355 static void
4356 vfatal (const char *str, va_list ap)
4358 fprintf (stderr, "emacs: ");
4359 vfprintf (stderr, str, ap);
4360 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4361 fprintf (stderr, "\n");
4362 fflush (stderr);
4363 exit (1);
4367 /* Auxiliary error-handling function for init_tty.
4368 Delete TERMINAL, then call error or fatal with str1 or str2,
4369 respectively, according to whether MUST_SUCCEED is true. */
4371 static void
4372 maybe_fatal (bool must_succeed, struct terminal *terminal,
4373 const char *str1, const char *str2, ...)
4375 va_list ap;
4376 va_start (ap, str2);
4377 if (terminal)
4378 delete_tty (terminal);
4380 if (must_succeed)
4381 vfatal (str2, ap);
4382 else
4383 verror (str1, ap);
4386 void
4387 fatal (const char *str, ...)
4389 va_list ap;
4390 va_start (ap, str);
4391 vfatal (str, ap);
4396 /* Delete the given tty terminal, closing all frames on it. */
4398 static void
4399 delete_tty (struct terminal *terminal)
4401 struct tty_display_info *tty;
4403 /* Protect against recursive calls. delete_frame in
4404 delete_terminal calls us back when it deletes our last frame. */
4405 if (!terminal->name)
4406 return;
4408 eassert (terminal->type == output_termcap);
4410 tty = terminal->display_info.tty;
4412 if (tty == tty_list)
4413 tty_list = tty->next;
4414 else
4416 struct tty_display_info *p;
4417 for (p = tty_list; p && p->next != tty; p = p->next)
4420 if (! p)
4421 /* This should not happen. */
4422 emacs_abort ();
4424 p->next = tty->next;
4425 tty->next = 0;
4428 /* reset_sys_modes needs a valid device, so this call needs to be
4429 before delete_terminal. */
4430 reset_sys_modes (tty);
4432 delete_terminal (terminal);
4434 xfree (tty->name);
4435 xfree (tty->type);
4437 if (tty->input)
4439 delete_keyboard_wait_descriptor (fileno (tty->input));
4440 if (tty->input != stdin)
4441 fclose (tty->input);
4443 if (tty->output && tty->output != stdout && tty->output != tty->input)
4444 fclose (tty->output);
4445 if (tty->termscript)
4446 fclose (tty->termscript);
4448 xfree (tty->old_tty);
4449 xfree (tty->Wcm);
4450 xfree (tty);
4453 void
4454 syms_of_term (void)
4456 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4457 doc: /* Non-nil means the system uses terminfo rather than termcap.
4458 This variable can be used by terminal emulator packages. */);
4459 #ifdef TERMINFO
4460 system_uses_terminfo = 1;
4461 #else
4462 system_uses_terminfo = 0;
4463 #endif
4465 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4466 doc: /* Functions run after suspending a tty.
4467 The functions are run with one argument, the terminal object to be suspended.
4468 See `suspend-tty'. */);
4469 Vsuspend_tty_functions = Qnil;
4472 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4473 doc: /* Functions run after resuming a tty.
4474 The functions are run with one argument, the terminal object that was revived.
4475 See `resume-tty'. */);
4476 Vresume_tty_functions = Qnil;
4478 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4479 doc: /* Non-nil means to make the cursor very visible.
4480 This only has an effect when running in a text terminal.
4481 What means \"very visible\" is up to your terminal. It may make the cursor
4482 bigger, or it may make it blink, or it may do nothing at all. */);
4483 visible_cursor = 1;
4485 defsubr (&Stty_display_color_p);
4486 defsubr (&Stty_display_color_cells);
4487 defsubr (&Stty_no_underline);
4488 defsubr (&Stty_type);
4489 defsubr (&Scontrolling_tty_p);
4490 defsubr (&Stty_top_frame);
4491 defsubr (&Ssuspend_tty);
4492 defsubr (&Sresume_tty);
4493 #ifdef HAVE_GPM
4494 defsubr (&Sgpm_mouse_start);
4495 defsubr (&Sgpm_mouse_stop);
4496 #endif /* HAVE_GPM */
4498 #ifndef DOS_NT
4499 default_orig_pair = NULL;
4500 default_set_foreground = NULL;
4501 default_set_background = NULL;
4502 #endif /* !DOS_NT */
4504 encode_terminal_src = NULL;
4505 encode_terminal_dst = NULL;
4507 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4508 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4510 #ifndef MSDOS
4511 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4512 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4513 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4514 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4515 DEFSYM (Qtty_menu_select, "tty-menu-select");
4516 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4517 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4518 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4519 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4520 #endif