]> code.delx.au - gnu-emacs/blob - src/term.c
; Merge from origin/emacs-24
[gnu-emacs] / src / term.c
1 /* Terminal control module for terminals described by TERMCAP
2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2015 Free Software
3 Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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/>. */
19
20 /* New redisplay, TTY faces by Gerd Moellmann <gerd@gnu.org>. */
21
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>
29
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
53
54 #ifdef USE_X_TOOLKIT
55 #include "../lwlib/lwlib.h"
56 #endif
57
58 #include "cm.h"
59 #ifdef HAVE_X_WINDOWS
60 #include "xterm.h"
61 #endif
62
63 #include "menu.h"
64
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
72
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);
89
90
91 #define OUTPUT(tty, a) \
92 emacs_tputs ((tty), a, \
93 FRAME_TOTAL_LINES (XFRAME (selected_frame)) - curY (tty), \
94 cmputc)
95
96 #define OUTPUT1(tty, a) emacs_tputs ((tty), a, 1, cmputc)
97 #define OUTPUTL(tty, a, lines) emacs_tputs ((tty), a, lines, cmputc)
98
99 #define OUTPUT_IF(tty, a) \
100 do { \
101 if (a) \
102 OUTPUT (tty, a); \
103 } while (0)
104
105 #define OUTPUT1_IF(tty, a) do { if (a) emacs_tputs ((tty), a, 1, cmputc); } while (0)
106
107 /* Display space properties. */
108
109 /* Chain of all tty device parameters. */
110 struct tty_display_info *tty_list;
111
112 /* Meaning of bits in no_color_video. Each bit set means that the
113 corresponding attribute cannot be combined with colors. */
114
115 enum no_color_bit
116 {
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
125 };
126
127 /* internal state */
128
129 /* The largest frame width in any call to calculate_costs. */
130
131 static int max_frame_cols;
132
133 \f
134
135 #ifdef HAVE_GPM
136 #include <sys/fcntl.h>
137
138 /* The device for which we have enabled gpm support (or NULL). */
139 struct tty_display_info *gpm_tty = NULL;
140
141 /* Last recorded mouse coordinates. */
142 static int last_mouse_x, last_mouse_y;
143 #endif /* HAVE_GPM */
144
145 /* Ring the bell on a tty. */
146
147 static void
148 tty_ring_bell (struct frame *f)
149 {
150 struct tty_display_info *tty = FRAME_TTY (f);
151
152 if (tty->output)
153 {
154 OUTPUT (tty, (tty->TS_visible_bell && visible_bell
155 ? tty->TS_visible_bell
156 : tty->TS_bell));
157 fflush (tty->output);
158 }
159 }
160
161 /* Set up termcap modes for Emacs. */
162
163 static void
164 tty_send_additional_strings (struct terminal *terminal, Lisp_Object sym)
165 {
166 Lisp_Object lisp_terminal;
167 Lisp_Object extra_codes;
168 struct tty_display_info *tty = terminal->display_info.tty;
169
170 XSETTERMINAL (lisp_terminal, terminal);
171 for (extra_codes = Fterminal_parameter (lisp_terminal, sym);
172 CONSP (extra_codes);
173 extra_codes = XCDR (extra_codes))
174 {
175 Lisp_Object string = XCAR (extra_codes);
176 if (STRINGP (string))
177 {
178 fwrite (SDATA (string), 1, SBYTES (string), tty->output);
179 if (tty->termscript)
180 fwrite (SDATA (string), 1, SBYTES (string), tty->termscript);
181 }
182 }
183 }
184
185 static void
186 tty_set_terminal_modes (struct terminal *terminal)
187 {
188 struct tty_display_info *tty = terminal->display_info.tty;
189
190 if (tty->output)
191 {
192 if (tty->TS_termcap_modes)
193 OUTPUT (tty, tty->TS_termcap_modes);
194 else
195 {
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');
202 }
203
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);
209 }
210 }
211
212 /* Reset termcap modes before exiting Emacs. */
213
214 static void
215 tty_reset_terminal_modes (struct terminal *terminal)
216 {
217 struct tty_display_info *tty = terminal->display_info.tty;
218
219 if (tty->output)
220 {
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);
232 }
233 }
234
235 /* Flag the end of a display update on a termcap terminal. */
236
237 static void
238 tty_update_end (struct frame *f)
239 {
240 struct tty_display_info *tty = FRAME_TTY (f);
241
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);
247 }
248
249 /* The implementation of set_terminal_window for termcap frames. */
250
251 static void
252 tty_set_terminal_window (struct frame *f, int size)
253 {
254 struct tty_display_info *tty = FRAME_TTY (f);
255
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);
259 }
260
261 static void
262 tty_set_scroll_region (struct frame *f, int start, int stop)
263 {
264 char *buf;
265 struct tty_display_info *tty = FRAME_TTY (f);
266
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));
276
277 OUTPUT (tty, buf);
278 xfree (buf);
279 losecursor (tty);
280 }
281
282 \f
283 static void
284 tty_turn_on_insert (struct tty_display_info *tty)
285 {
286 if (!tty->insert_mode)
287 OUTPUT (tty, tty->TS_insert_mode);
288 tty->insert_mode = 1;
289 }
290
291 void
292 tty_turn_off_insert (struct tty_display_info *tty)
293 {
294 if (tty->insert_mode)
295 OUTPUT (tty, tty->TS_end_insert_mode);
296 tty->insert_mode = 0;
297 }
298 \f
299 /* Handle highlighting. */
300
301 static void
302 tty_turn_off_highlight (struct tty_display_info *tty)
303 {
304 if (tty->standout_mode)
305 OUTPUT_IF (tty, tty->TS_end_standout_mode);
306 tty->standout_mode = 0;
307 }
308
309 static void
310 tty_turn_on_highlight (struct tty_display_info *tty)
311 {
312 if (!tty->standout_mode)
313 OUTPUT_IF (tty, tty->TS_standout_mode);
314 tty->standout_mode = 1;
315 }
316
317 static void
318 tty_toggle_highlight (struct tty_display_info *tty)
319 {
320 if (tty->standout_mode)
321 tty_turn_off_highlight (tty);
322 else
323 tty_turn_on_highlight (tty);
324 }
325
326
327 /* Make cursor invisible. */
328
329 static void
330 tty_hide_cursor (struct tty_display_info *tty)
331 {
332 if (tty->cursor_hidden == 0)
333 {
334 tty->cursor_hidden = 1;
335 #ifdef WINDOWSNT
336 w32con_hide_cursor ();
337 #else
338 OUTPUT_IF (tty, tty->TS_cursor_invisible);
339 #endif
340 }
341 }
342
343
344 /* Ensure that cursor is visible. */
345
346 static void
347 tty_show_cursor (struct tty_display_info *tty)
348 {
349 if (tty->cursor_hidden)
350 {
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
359 }
360 }
361
362
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. */
366
367 static void
368 tty_background_highlight (struct tty_display_info *tty)
369 {
370 if (inverse_video)
371 tty_turn_on_highlight (tty);
372 else
373 tty_turn_off_highlight (tty);
374 }
375
376 /* Set standout mode to the mode specified for the text to be output. */
377
378 static void
379 tty_highlight_if_desired (struct tty_display_info *tty)
380 {
381 if (inverse_video)
382 tty_turn_on_highlight (tty);
383 else
384 tty_turn_off_highlight (tty);
385 }
386 \f
387
388 /* Move cursor to row/column position VPOS/HPOS. HPOS/VPOS are
389 frame-relative coordinates. */
390
391 static void
392 tty_cursor_to (struct frame *f, int vpos, int hpos)
393 {
394 struct tty_display_info *tty = FRAME_TTY (f);
395
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;
400
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);
409 }
410
411 /* Similar but don't take any account of the wasted characters. */
412
413 static void
414 tty_raw_cursor_to (struct frame *f, int row, int col)
415 {
416 struct tty_display_info *tty = FRAME_TTY (f);
417
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);
426 }
427 \f
428 /* Erase operations */
429
430 /* Clear from cursor to end of frame on a termcap device. */
431
432 static void
433 tty_clear_to_end (struct frame *f)
434 {
435 register int i;
436 struct tty_display_info *tty = FRAME_TTY (f);
437
438 if (tty->TS_clr_to_bottom)
439 {
440 tty_background_highlight (tty);
441 OUTPUT (tty, tty->TS_clr_to_bottom);
442 }
443 else
444 {
445 for (i = curY (tty); i < FRAME_TOTAL_LINES (f); i++)
446 {
447 cursor_to (f, i, 0);
448 clear_end_of_line (f, FRAME_COLS (f));
449 }
450 }
451 }
452
453 /* Clear an entire termcap frame. */
454
455 static void
456 tty_clear_frame (struct frame *f)
457 {
458 struct tty_display_info *tty = FRAME_TTY (f);
459
460 if (tty->TS_clr_frame)
461 {
462 tty_background_highlight (tty);
463 OUTPUT (tty, tty->TS_clr_frame);
464 cmat (tty, 0, 0);
465 }
466 else
467 {
468 cursor_to (f, 0, 0);
469 clear_to_end (f);
470 }
471 }
472
473 /* An implementation of clear_end_of_line for termcap frames.
474
475 Note that the cursor may be moved, on terminals lacking a `ce' string. */
476
477 static void
478 tty_clear_end_of_line (struct frame *f, int first_unused_hpos)
479 {
480 register int i;
481 struct tty_display_info *tty = FRAME_TTY (f);
482
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;
487
488 if (curX (tty) >= first_unused_hpos)
489 return;
490 tty_background_highlight (tty);
491 if (tty->TS_clr_line)
492 {
493 OUTPUT1 (tty, tty->TS_clr_line);
494 }
495 else
496 { /* have to do it the hard way */
497 tty_turn_off_insert (tty);
498
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--;
504
505 for (i = curX (tty); i < first_unused_hpos; i++)
506 {
507 if (tty->termscript)
508 fputc (' ', tty->termscript);
509 fputc (' ', tty->output);
510 }
511 cmplus (tty, first_unused_hpos - curX (tty));
512 }
513 }
514 \f
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;
521
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. */
525
526 unsigned char *
527 encode_terminal_code (struct glyph *src, int src_len,
528 struct coding_system *coding)
529 {
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;
536
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)
546 {
547 encode_terminal_src = xrealloc (encode_terminal_src, required);
548 encode_terminal_src_size = required;
549 }
550
551 charset_list = coding_charset_list (coding);
552
553 buf = encode_terminal_src;
554 nchars = 0;
555 while (src < src_end)
556 {
557 if (src->type == COMPOSITE_GLYPH)
558 {
559 struct composition *cmp IF_LINT (= NULL);
560 Lisp_Object gstring IF_LINT (= Qnil);
561 int i;
562
563 nbytes = buf - encode_terminal_src;
564 if (src->u.cmp.automatic)
565 {
566 gstring = composition_gstring_from_id (src->u.cmp.id);
567 required = src->slice.cmp.to - src->slice.cmp.from + 1;
568 }
569 else
570 {
571 cmp = composition_table[src->u.cmp.id];
572 required = cmp->glyph_len;
573 required *= MAX_MULTIBYTE_LENGTH;
574 }
575
576 if (encode_terminal_src_size - nbytes < required)
577 {
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;
583 }
584
585 if (src->u.cmp.automatic)
586 for (i = src->slice.cmp.from; i <= src->slice.cmp.to; i++)
587 {
588 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
589 int c = LGLYPH_CHAR (g);
590
591 if (! char_charset (c, charset_list, NULL))
592 c = '?';
593 buf += CHAR_STRING (c, buf);
594 nchars++;
595 }
596 else
597 for (i = 0; i < cmp->glyph_len; i++)
598 {
599 int c = COMPOSITION_GLYPH (cmp, i);
600
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))
606 {
607 if (CHAR_WIDTH (c) == 0
608 && i > 0 && COMPOSITION_GLYPH (cmp, i - 1) == '\t')
609 /* Should be left-padded */
610 {
611 buf += CHAR_STRING (' ', buf);
612 nchars++;
613 }
614 }
615 else
616 c = '?';
617 buf += CHAR_STRING (c, buf);
618 nchars++;
619 }
620 }
621 /* We must skip glyphs to be padded for a wide character. */
622 else if (! CHAR_GLYPH_PADDING_P (*src))
623 {
624 GLYPH g;
625 int c IF_LINT (= 0);
626 Lisp_Object string;
627
628 string = Qnil;
629 SET_GLYPH_FROM_CHAR_GLYPH (g, src[0]);
630
631 if (GLYPH_INVALID_P (g) || GLYPH_SIMPLE_P (tbase, tlen, g))
632 {
633 /* This glyph doesn't have an entry in Vglyph_table. */
634 c = src->u.ch;
635 }
636 else
637 {
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);
641
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)];
649 }
650
651 if (NILP (string))
652 {
653 nbytes = buf - encode_terminal_src;
654 if (encode_terminal_src_size - nbytes < MAX_MULTIBYTE_LENGTH)
655 {
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;
660 }
661 if (CHAR_BYTE8_P (c)
662 || char_charset (c, charset_list, NULL))
663 {
664 /* Store the multibyte form of C at BUF. */
665 buf += CHAR_STRING (c, buf);
666 nchars++;
667 }
668 else
669 {
670 /* C is not encodable. */
671 *buf++ = '?';
672 nchars++;
673 while (src + 1 < src_end && CHAR_GLYPH_PADDING_P (src[1]))
674 {
675 *buf++ = '?';
676 nchars++;
677 src++;
678 }
679 }
680 }
681 else
682 {
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))
687 {
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;
694 }
695 memcpy (buf, SDATA (string), SBYTES (string));
696 buf += SBYTES (string);
697 nchars += SCHARS (string);
698 }
699 }
700 src++;
701 }
702
703 if (nchars == 0)
704 {
705 coding->produced = 0;
706 return NULL;
707 }
708
709 nbytes = buf - encode_terminal_src;
710 coding->source = encode_terminal_src;
711 if (encode_terminal_dst_size == 0)
712 {
713 encode_terminal_dst = xrealloc (encode_terminal_dst,
714 encode_terminal_src_size);
715 encode_terminal_dst_size = encode_terminal_src_size;
716 }
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;
723
724 return (encode_terminal_dst);
725 }
726
727
728
729 /* An implementation of write_glyphs for termcap frames. */
730
731 static void
732 tty_write_glyphs (struct frame *f, struct glyph *string, int len)
733 {
734 unsigned char *conversion_buffer;
735 struct coding_system *coding;
736 int n, stringlen;
737
738 struct tty_display_info *tty = FRAME_TTY (f);
739
740 tty_turn_off_insert (tty);
741 tty_hide_cursor (tty);
742
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. */
745
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;
752
753 cmplus (tty, len);
754
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;
763
764 for (stringlen = len; stringlen != 0; stringlen -= n)
765 {
766 /* Identify a run of glyphs with the same face. */
767 int face_id = string->face_id;
768
769 for (n = 1; n < stringlen; ++n)
770 if (string[n].face_id != face_id)
771 break;
772
773 /* Turn appearance modes of the face of the run on. */
774 tty_highlight_if_desired (tty);
775 turn_on_face (f, face_id);
776
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)
782 {
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 ();
790 }
791 string += n;
792
793 /* Turn appearance modes off. */
794 turn_off_face (f, face_id);
795 tty_turn_off_highlight (tty);
796 }
797
798 cmcheckmagic (tty);
799 }
800
801 #ifdef HAVE_GPM /* Only used by GPM code. */
802
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)
806 {
807 unsigned char *conversion_buffer;
808 struct coding_system *coding;
809
810 struct tty_display_info *tty = FRAME_TTY (f);
811
812 tty_turn_off_insert (tty);
813 tty_hide_cursor (tty);
814
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. */
817
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;
824
825 cmplus (tty, len);
826
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;
835
836 /* Turn appearance modes of the face. */
837 tty_highlight_if_desired (tty);
838 turn_on_face (f, face_id);
839
840 coding->mode |= CODING_MODE_LAST_BLOCK;
841 conversion_buffer = encode_terminal_code (string, len, coding);
842 if (coding->produced > 0)
843 {
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 ();
851 }
852
853 /* Turn appearance modes off. */
854 turn_off_face (f, face_id);
855 tty_turn_off_highlight (tty);
856
857 cmcheckmagic (tty);
858 }
859 #endif
860
861 /* An implementation of insert_glyphs for termcap frames. */
862
863 static void
864 tty_insert_glyphs (struct frame *f, struct glyph *start, int len)
865 {
866 char *buf;
867 struct glyph *glyph = NULL;
868 unsigned char *conversion_buffer;
869 unsigned char space[1];
870 struct coding_system *coding;
871
872 struct tty_display_info *tty = FRAME_TTY (f);
873
874 if (tty->TS_ins_multi_chars)
875 {
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;
882 }
883
884 tty_turn_on_insert (tty);
885 cmplus (tty, len);
886
887 if (! start)
888 space[0] = SPACEGLYPH;
889
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;
898
899 while (len-- > 0)
900 {
901 OUTPUT1_IF (tty, tty->TS_ins_char);
902 if (!start)
903 {
904 conversion_buffer = space;
905 coding->produced = 1;
906 }
907 else
908 {
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))
916 {
917 OUTPUT1_IF (tty, tty->TS_ins_char);
918 start++, len--;
919 }
920
921 if (len <= 0)
922 /* This is the last glyph. */
923 coding->mode |= CODING_MODE_LAST_BLOCK;
924
925 conversion_buffer = encode_terminal_code (glyph, 1, coding);
926 }
927
928 if (coding->produced > 0)
929 {
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 ();
937 }
938
939 OUTPUT1_IF (tty, tty->TS_pad_inserted_char);
940 if (start)
941 {
942 turn_off_face (f, glyph->face_id);
943 tty_turn_off_highlight (tty);
944 }
945 }
946
947 cmcheckmagic (tty);
948 }
949
950 /* An implementation of delete_glyphs for termcap frames. */
951
952 static void
953 tty_delete_glyphs (struct frame *f, int n)
954 {
955 char *buf;
956 register int i;
957
958 struct tty_display_info *tty = FRAME_TTY (f);
959
960 if (tty->delete_in_insert_mode)
961 {
962 tty_turn_on_insert (tty);
963 }
964 else
965 {
966 tty_turn_off_insert (tty);
967 OUTPUT_IF (tty, tty->TS_delete_mode);
968 }
969
970 if (tty->TS_del_multi_chars)
971 {
972 buf = tparam (tty->TS_del_multi_chars, 0, 0, n, 0, 0, 0);
973 OUTPUT1 (tty, buf);
974 xfree (buf);
975 }
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);
981 }
982 \f
983 /* An implementation of ins_del_lines for termcap frames. */
984
985 static void
986 tty_ins_del_lines (struct frame *f, int vpos, int n)
987 {
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;
993
994 int i = eabs (n);
995 char *buf;
996
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;
1010
1011 if (multi)
1012 {
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);
1018 }
1019 else if (single)
1020 {
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;
1027 }
1028 else
1029 {
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);
1039 }
1040
1041 if (!FRAME_SCROLL_REGION_OK (f)
1042 && FRAME_MEMORY_BELOW_FRAME (f)
1043 && n < 0)
1044 {
1045 cursor_to (f, FRAME_TOTAL_LINES (f) + n, 0);
1046 clear_to_end (f);
1047 }
1048 }
1049 \f
1050 /* Compute cost of sending "str", in characters,
1051 not counting any line-dependent padding. */
1052
1053 int
1054 string_cost (const char *str)
1055 {
1056 cost = 0;
1057 if (str)
1058 tputs (str, 0, evalcost);
1059 return cost;
1060 }
1061
1062 /* Compute cost of sending "str", in characters,
1063 counting any line-dependent padding at one line. */
1064
1065 static int
1066 string_cost_one_line (const char *str)
1067 {
1068 cost = 0;
1069 if (str)
1070 tputs (str, 1, evalcost);
1071 return cost;
1072 }
1073
1074 /* Compute per line amount of line-dependent padding,
1075 in tenths of characters. */
1076
1077 int
1078 per_line_cost (const char *str)
1079 {
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;
1087 }
1088
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. */
1092
1093 int *char_ins_del_vector;
1094
1095 #define char_ins_del_cost(f) (&char_ins_del_vector[FRAME_COLS ((f))])
1096
1097 /* ARGSUSED */
1098 static void
1099 calculate_ins_del_char_costs (struct frame *f)
1100 {
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;
1106
1107 if (tty->TS_ins_multi_chars)
1108 {
1109 ins_cost_per_char = 0;
1110 ins_startup_cost = string_cost_one_line (tty->TS_ins_multi_chars);
1111 }
1112 else if (tty->TS_ins_char || tty->TS_pad_inserted_char
1113 || (tty->TS_insert_mode && tty->TS_end_insert_mode))
1114 {
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));
1119 }
1120 else
1121 {
1122 ins_startup_cost = 9999;
1123 ins_cost_per_char = 0;
1124 }
1125
1126 if (tty->TS_del_multi_chars)
1127 {
1128 del_cost_per_char = 0;
1129 del_startup_cost = string_cost_one_line (tty->TS_del_multi_chars);
1130 }
1131 else if (tty->TS_del_char)
1132 {
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);
1138 }
1139 else
1140 {
1141 del_startup_cost = 9999;
1142 del_cost_per_char = 0;
1143 }
1144
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);
1149
1150 /* Doing nothing is free */
1151 p = &char_ins_del_cost (f)[0];
1152 *p++ = 0;
1153
1154 /* Insert costs are at positive offsets */
1155 for (i = FRAME_COLS (f); --i >= 0;)
1156 *p++ = (ins_startup_cost += ins_cost_per_char);
1157 }
1158
1159 void
1160 calculate_costs (struct frame *frame)
1161 {
1162 FRAME_COST_BAUD_RATE (frame) = baud_rate;
1163
1164 if (FRAME_TERMCAP_P (frame))
1165 {
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);
1170
1171 FRAME_SCROLL_REGION_COST (frame) = string_cost (f);
1172
1173 tty->costs_set = 1;
1174
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.
1178
1179 char_ins_del_vector (i.e., char_ins_del_cost) isn't used because
1180 X turns off char_ins_del_ok. */
1181
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);
1186
1187 char_ins_del_vector =
1188 xrealloc (char_ins_del_vector,
1189 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1190
1191 memset (char_ins_del_vector, 0,
1192 (sizeof (int) + 2 * sizeof (int) * max_frame_cols));
1193
1194
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);
1205
1206 calculate_ins_del_char_costs (frame);
1207
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;
1213
1214 cmcostinit (FRAME_TTY (frame)); /* set up cursor motion costs */
1215 }
1216 }
1217 \f
1218 struct fkey_table {
1219 const char *cap, *name;
1220 };
1221
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.
1227 */
1228
1229 static const struct fkey_table keys[] =
1230 {
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 */
1243 /*
1244 * "insert" --- see below
1245 */
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 */
1252 /*
1253 * "break" goes here, but can't be reliably intercepted with termcap
1254 */
1255 {"&4", "reset"}, /* terminfo --- actually `restart' */
1256 /*
1257 * "system" and "user" --- no termcaps
1258 */
1259 {"kE", "clearline"}, /* terminfo */
1260 {"kA", "insertline"}, /* terminfo */
1261 {"kL", "deleteline"}, /* terminfo */
1262 {"kI", "insertchar"}, /* terminfo */
1263 {"kD", "deletechar"}, /* terminfo */
1264 {"kB", "backtab"}, /* terminfo */
1265 /*
1266 * "kp_backtab", "kp-space", "kp-tab" --- no termcaps
1267 */
1268 {"@8", "kp-enter"}, /* terminfo */
1269 /*
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.
1274 */
1275 {"K4", "kp-1"}, /* terminfo */
1276 /*
1277 * "kp-2" --- no termcap
1278 */
1279 {"K5", "kp-3"}, /* terminfo */
1280 /*
1281 * "kp-4" --- no termcap
1282 */
1283 {"K2", "kp-5"}, /* terminfo */
1284 /*
1285 * "kp-6" --- no termcap
1286 */
1287 {"K1", "kp-7"}, /* terminfo */
1288 /*
1289 * "kp-8" --- no termcap
1290 */
1291 {"K3", "kp-9"}, /* terminfo */
1292 /*
1293 * "kp-equal" --- no termcap
1294 */
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"},
1304
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*/
1323 };
1324
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);
1329
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. */
1333
1334 static void
1335 term_get_fkeys (char **address, KBOARD *kboard)
1336 {
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. */
1344
1345 term_get_fkeys_address = address;
1346 term_get_fkeys_kboard = kboard;
1347 internal_condition_case (term_get_fkeys_1, Qerror, Fidentity);
1348 }
1349
1350 static Lisp_Object
1351 term_get_fkeys_1 (void)
1352 {
1353 int i;
1354
1355 char **address = term_get_fkeys_address;
1356 KBOARD *kboard = term_get_fkeys_kboard;
1357
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));
1361
1362 for (i = 0; i < ARRAYELTS (keys); i++)
1363 {
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)));
1369 }
1370
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.
1375 */
1376 {
1377 const char *k_semi = tgetstr ("k;", address);
1378 const char *k0 = tgetstr ("k0", address);
1379 const char *k0_name = "f10";
1380
1381 if (k_semi)
1382 {
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")));
1390 }
1391 else if (k0)
1392 Fdefine_key (KVAR (kboard, Vinput_decode_map), build_string (k0),
1393 Fmake_vector (make_number (1), intern (k0_name)));
1394 }
1395
1396 /* Set up cookies for numbered function keys above f10. */
1397 {
1398 char fcap[3], fkey[4];
1399
1400 fcap[0] = 'F'; fcap[2] = '\0';
1401 for (i = 11; i < 64; i++)
1402 {
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;
1409
1410 {
1411 char *sequence = tgetstr (fcap, address);
1412 if (sequence)
1413 {
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)));
1418 }
1419 }
1420 }
1421 }
1422
1423 /*
1424 * Various mappings to try and get a better fit.
1425 */
1426 {
1427 #define CONDITIONAL_REASSIGN(cap1, cap2, sym) \
1428 if (!tgetstr (cap1, address)) \
1429 { \
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))); \
1435 }
1436
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
1446 }
1447
1448 return Qnil;
1449 }
1450 #endif /* not DOS_NT */
1451
1452 \f
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);
1461
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. */
1467
1468 static void
1469 append_glyph (struct it *it)
1470 {
1471 struct glyph *glyph, *end;
1472 int i;
1473
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];
1478
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)
1482 {
1483 struct glyph *g;
1484 int move_by = it->pixel_width;
1485
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;
1493 }
1494
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)
1502 {
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)
1511 {
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;
1515 }
1516 else
1517 {
1518 glyph->resolved_level = 0;
1519 glyph->bidi_type = UNKNOWN_BT;
1520 }
1521
1522 ++it->glyph_row->used[it->area];
1523 ++glyph;
1524 }
1525 }
1526
1527 /* For external use. */
1528 void
1529 tty_append_glyph (struct it *it)
1530 {
1531 append_glyph (it);
1532 }
1533
1534
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.
1543
1544 produce_glyphs also stores the result of glyph width, ascent
1545 etc. computations in *IT.
1546
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.
1550
1551 Callers usually don't call produce_glyphs directly;
1552 instead they use the macro PRODUCE_GLYPHS. */
1553
1554 void
1555 produce_glyphs (struct it *it)
1556 {
1557 /* If a hook is installed, let it do the work. */
1558
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);
1564
1565 if (it->what == IT_STRETCH)
1566 {
1567 produce_stretch_glyph (it);
1568 goto done;
1569 }
1570
1571 if (it->what == IT_COMPOSITION)
1572 {
1573 produce_composite_glyph (it);
1574 goto done;
1575 }
1576
1577 if (it->what == IT_GLYPHLESS)
1578 {
1579 produce_glyphless_glyph (it, Qnil);
1580 goto done;
1581 }
1582
1583 if (it->char_to_display >= 040 && it->char_to_display < 0177)
1584 {
1585 it->pixel_width = it->nglyphs = 1;
1586 if (it->glyph_row)
1587 append_glyph (it);
1588 }
1589 else if (it->char_to_display == '\n')
1590 it->pixel_width = it->nglyphs = 0;
1591 else if (it->char_to_display == '\t')
1592 {
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;
1600
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;
1607
1608 if (it->glyph_row)
1609 {
1610 int n = nspaces;
1611
1612 it->char_to_display = ' ';
1613 it->pixel_width = it->len = 1;
1614
1615 while (n--)
1616 append_glyph (it);
1617 }
1618
1619 it->pixel_width = nspaces;
1620 it->nglyphs = nspaces;
1621 }
1622 else if (CHAR_BYTE8_P (it->char_to_display))
1623 {
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);
1631 }
1632 else
1633 {
1634 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
1635
1636 if (char_charset (it->char_to_display, charset_list, NULL))
1637 {
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);
1642 }
1643 else
1644 {
1645 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1646
1647 eassert (it->what == IT_GLYPHLESS);
1648 produce_glyphless_glyph (it, acronym);
1649 }
1650 }
1651
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;
1659 }
1660
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. */
1665
1666 static void
1667 append_composite_glyph (struct it *it)
1668 {
1669 struct glyph *glyph;
1670
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])
1674 {
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)
1678 {
1679 struct glyph *g;
1680
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];
1685 }
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)
1690 {
1691 glyph->u.cmp.automatic = 0;
1692 glyph->u.cmp.id = it->cmp_it.id;
1693 }
1694 else
1695 {
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;
1700 }
1701
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)
1707 {
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;
1711 }
1712 else
1713 {
1714 glyph->resolved_level = 0;
1715 glyph->bidi_type = UNKNOWN_BT;
1716 }
1717
1718 ++it->glyph_row->used[it->area];
1719 ++glyph;
1720 }
1721 }
1722
1723
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. */
1728
1729 static void
1730 produce_composite_glyph (struct it *it)
1731 {
1732 if (it->cmp_it.ch < 0)
1733 {
1734 struct composition *cmp = composition_table[it->cmp_it.id];
1735
1736 it->pixel_width = cmp->width;
1737 }
1738 else
1739 {
1740 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
1741
1742 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1743 it->cmp_it.to, NULL);
1744 }
1745 it->nglyphs = 1;
1746 if (it->glyph_row)
1747 append_composite_glyph (it);
1748 }
1749
1750
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). */
1755
1756 static void
1757 append_glyphless_glyph (struct it *it, int face_id, const char *str)
1758 {
1759 struct glyph *glyph, *end;
1760 int i;
1761
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];
1765
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)
1769 {
1770 struct glyph *g;
1771 int move_by = it->pixel_width;
1772
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;
1780 }
1781
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)
1791 {
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;
1795 }
1796 else
1797 {
1798 glyph->resolved_level = 0;
1799 glyph->bidi_type = UNKNOWN_BT;
1800 }
1801
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)
1806 {
1807 if (i > 0)
1808 glyph[0] = glyph[-1];
1809 glyph->u.ch = str[i];
1810 ++it->glyph_row->used[it->area];
1811 ++glyph;
1812 }
1813 }
1814
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.
1819
1820 ACRONYM, if non-nil, is an acronym string for the character.
1821
1822 The glyphs actually produced are of type CHAR_GLYPH. */
1823
1824 static void
1825 produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
1826 {
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 = " ";
1830
1831 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1832 {
1833 /* As there's no way to produce a thin space, we produce a space
1834 of canonical width. */
1835 len = 1;
1836 }
1837 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1838 {
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;
1846 }
1847 else
1848 {
1849 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1850 {
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;
1861 }
1862 else
1863 {
1864 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
1865 len = sprintf (buf,
1866 (it->c < 0x10000 ? "\\u%04X"
1867 : it->c <= MAX_UNICODE_CHAR ? "\\U%06X"
1868 : "\\x%06X"),
1869 it->c + 0u);
1870 }
1871 str = buf;
1872 }
1873
1874 it->pixel_width = len;
1875 it->nglyphs = len;
1876 if (it->glyph_row)
1877 append_glyphless_glyph (it, face_id, str);
1878 }
1879
1880 \f
1881 /***********************************************************************
1882 Faces
1883 ***********************************************************************/
1884
1885 /* Value is non-zero if attribute ATTR may be used. ATTR should be
1886 one of the enumerators from enum no_color_bit, or a bit set built
1887 from them. Some display attributes may not be used together with
1888 color; the termcap capability `NC' specifies which ones. */
1889
1890 #define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1891 (tty->TN_max_colors > 0 \
1892 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1893 : 1)
1894
1895 /* Turn appearances of face FACE_ID on tty frame F on.
1896 FACE_ID is a realized face ID number, in the face cache. */
1897
1898 static void
1899 turn_on_face (struct frame *f, int face_id)
1900 {
1901 struct face *face = FACE_FROM_ID (f, face_id);
1902 unsigned long fg = face->foreground;
1903 unsigned long bg = face->background;
1904 struct tty_display_info *tty = FRAME_TTY (f);
1905
1906 /* Use reverse video if the face specifies that.
1907 Do this first because TS_end_standout_mode may be the same
1908 as TS_exit_attribute_mode, which turns all appearances off. */
1909 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1910 && (inverse_video
1911 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1912 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1913 tty_toggle_highlight (tty);
1914
1915 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1916 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1917
1918 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1919 {
1920 if (tty->TS_enter_italic_mode)
1921 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1922 else
1923 /* Italics mode is unavailable on many terminals. In that
1924 case, map slant to dimmed text; we want italic text to
1925 appear different and dimming is not otherwise used. */
1926 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1927 }
1928
1929 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1930 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
1931
1932 if (tty->TN_max_colors > 0)
1933 {
1934 const char *ts;
1935 char *p;
1936
1937 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
1938 if (face_tty_specified_color (fg) && ts)
1939 {
1940 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
1941 OUTPUT (tty, p);
1942 xfree (p);
1943 }
1944
1945 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
1946 if (face_tty_specified_color (bg) && ts)
1947 {
1948 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
1949 OUTPUT (tty, p);
1950 xfree (p);
1951 }
1952 }
1953 }
1954
1955
1956 /* Turn off appearances of face FACE_ID on tty frame F. */
1957
1958 static void
1959 turn_off_face (struct frame *f, int face_id)
1960 {
1961 struct face *face = FACE_FROM_ID (f, face_id);
1962 struct tty_display_info *tty = FRAME_TTY (f);
1963
1964 eassert (face != NULL);
1965
1966 if (tty->TS_exit_attribute_mode)
1967 {
1968 /* Capability "me" will turn off appearance modes double-bright,
1969 half-bright, reverse-video, standout, underline. It may or
1970 may not turn off alt-char-mode. */
1971 if (face->tty_bold_p
1972 || face->tty_italic_p
1973 || face->tty_reverse_p
1974 || face->tty_underline_p)
1975 {
1976 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1977 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1978 tty->standout_mode = 0;
1979 }
1980 }
1981 else
1982 {
1983 /* If we don't have "me" we can only have those appearances
1984 that have exit sequences defined. */
1985 if (face->tty_underline_p)
1986 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
1987 }
1988
1989 /* Switch back to default colors. */
1990 if (tty->TN_max_colors > 0
1991 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1992 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1993 || (face->background != FACE_TTY_DEFAULT_COLOR
1994 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
1995 OUTPUT1_IF (tty, tty->TS_orig_pair);
1996 }
1997
1998
1999 /* Return true if the terminal on frame F supports all of the
2000 capabilities in CAPS simultaneously. */
2001
2002 bool
2003 tty_capable_p (struct tty_display_info *tty, unsigned int caps)
2004 {
2005 #define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
2006 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
2007 return 0;
2008
2009 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
2010 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
2011 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
2012 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
2013 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
2014
2015 /* We can do it! */
2016 return 1;
2017 }
2018
2019 /* Return non-zero if the terminal is capable to display colors. */
2020
2021 DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
2022 0, 1, 0,
2023 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2024
2025 TERMINAL can be a terminal object, a frame, or nil (meaning the
2026 selected frame's terminal). This function always returns nil if
2027 TERMINAL does not refer to a text terminal. */)
2028 (Lisp_Object terminal)
2029 {
2030 struct terminal *t = decode_tty_terminal (terminal);
2031
2032 return (t && t->display_info.tty->TN_max_colors > 0) ? Qt : Qnil;
2033 }
2034
2035 /* Return the number of supported colors. */
2036 DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2037 Stty_display_color_cells, 0, 1, 0,
2038 doc: /* Return the number of colors supported by the tty device TERMINAL.
2039
2040 TERMINAL can be a terminal object, a frame, or nil (meaning the
2041 selected frame's terminal). This function always returns 0 if
2042 TERMINAL does not refer to a text terminal. */)
2043 (Lisp_Object terminal)
2044 {
2045 struct terminal *t = decode_tty_terminal (terminal);
2046
2047 return make_number (t ? t->display_info.tty->TN_max_colors : 0);
2048 }
2049
2050 #ifndef DOS_NT
2051
2052 /* Declare here rather than in the function, as in the rest of Emacs,
2053 to work around an HPUX compiler bug (?). See
2054 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
2055 static int default_max_colors;
2056 static int default_max_pairs;
2057 static int default_no_color_video;
2058 static char *default_orig_pair;
2059 static char *default_set_foreground;
2060 static char *default_set_background;
2061
2062 /* Save or restore the default color-related capabilities of this
2063 terminal. */
2064 static void
2065 tty_default_color_capabilities (struct tty_display_info *tty, bool save)
2066 {
2067
2068 if (save)
2069 {
2070 dupstring (&default_orig_pair, tty->TS_orig_pair);
2071 dupstring (&default_set_foreground, tty->TS_set_foreground);
2072 dupstring (&default_set_background, tty->TS_set_background);
2073 default_max_colors = tty->TN_max_colors;
2074 default_max_pairs = tty->TN_max_pairs;
2075 default_no_color_video = tty->TN_no_color_video;
2076 }
2077 else
2078 {
2079 tty->TS_orig_pair = default_orig_pair;
2080 tty->TS_set_foreground = default_set_foreground;
2081 tty->TS_set_background = default_set_background;
2082 tty->TN_max_colors = default_max_colors;
2083 tty->TN_max_pairs = default_max_pairs;
2084 tty->TN_no_color_video = default_no_color_video;
2085 }
2086 }
2087
2088 /* Setup one of the standard tty color schemes according to MODE.
2089 MODE's value is generally the number of colors which we want to
2090 support; zero means set up for the default capabilities, the ones
2091 we saw at init_tty time; -1 means turn off color support. */
2092 static void
2093 tty_setup_colors (struct tty_display_info *tty, int mode)
2094 {
2095 /* Canonicalize all negative values of MODE. */
2096 if (mode < -1)
2097 mode = -1;
2098
2099 switch (mode)
2100 {
2101 case -1: /* no colors at all */
2102 tty->TN_max_colors = 0;
2103 tty->TN_max_pairs = 0;
2104 tty->TN_no_color_video = 0;
2105 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
2106 break;
2107 case 0: /* default colors, if any */
2108 default:
2109 tty_default_color_capabilities (tty, 0);
2110 break;
2111 case 8: /* 8 standard ANSI colors */
2112 tty->TS_orig_pair = "\033[0m";
2113 #ifdef TERMINFO
2114 tty->TS_set_foreground = "\033[3%p1%dm";
2115 tty->TS_set_background = "\033[4%p1%dm";
2116 #else
2117 tty->TS_set_foreground = "\033[3%dm";
2118 tty->TS_set_background = "\033[4%dm";
2119 #endif
2120 tty->TN_max_colors = 8;
2121 tty->TN_max_pairs = 64;
2122 tty->TN_no_color_video = 0;
2123 break;
2124 }
2125 }
2126
2127 void
2128 set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
2129 {
2130 Lisp_Object tem, val;
2131 Lisp_Object color_mode;
2132 int mode;
2133 Lisp_Object tty_color_mode_alist
2134 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
2135
2136 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
2137 val = CONSP (tem) ? XCDR (tem) : Qnil;
2138
2139 if (INTEGERP (val))
2140 color_mode = val;
2141 else if (SYMBOLP (tty_color_mode_alist))
2142 {
2143 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
2144 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
2145 }
2146 else
2147 color_mode = Qnil;
2148
2149 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
2150
2151 if (mode != tty->previous_color_mode)
2152 {
2153 tty->previous_color_mode = mode;
2154 tty_setup_colors (tty , mode);
2155 /* This recomputes all the faces given the new color definitions. */
2156 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
2157 }
2158 }
2159
2160 #endif /* !DOS_NT */
2161
2162 DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
2163 doc: /* Return the type of the tty device that TERMINAL uses.
2164 Returns nil if TERMINAL is not on a tty device.
2165
2166 TERMINAL can be a terminal object, a frame, or nil (meaning the
2167 selected frame's terminal). */)
2168 (Lisp_Object terminal)
2169 {
2170 struct terminal *t = decode_tty_terminal (terminal);
2171
2172 return (t && t->display_info.tty->type
2173 ? build_string (t->display_info.tty->type) : Qnil);
2174 }
2175
2176 DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
2177 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
2178
2179 TERMINAL can be a terminal object, a frame, or nil (meaning the
2180 selected frame's terminal). This function always returns nil if
2181 TERMINAL is not on a tty device. */)
2182 (Lisp_Object terminal)
2183 {
2184 struct terminal *t = decode_tty_terminal (terminal);
2185
2186 return (t && !strcmp (t->display_info.tty->name, DEV_TTY) ? Qt : Qnil);
2187 }
2188
2189 DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
2190 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
2191 This is used to override the terminfo data, for certain terminals that
2192 do not really do underlining, but say that they do. This function has
2193 no effect if used on a non-tty terminal.
2194
2195 TERMINAL can be a terminal object, a frame or nil (meaning the
2196 selected frame's terminal). This function always returns nil if
2197 TERMINAL does not refer to a text terminal. */)
2198 (Lisp_Object terminal)
2199 {
2200 struct terminal *t = decode_live_terminal (terminal);
2201
2202 if (t->type == output_termcap)
2203 t->display_info.tty->TS_enter_underline_mode = 0;
2204 return Qnil;
2205 }
2206
2207 DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2208 doc: /* Return the topmost terminal frame on TERMINAL.
2209 TERMINAL can be a terminal object, a frame or nil (meaning the
2210 selected frame's terminal). This function returns nil if TERMINAL
2211 does not refer to a text terminal. Otherwise, it returns the
2212 top-most frame on the text terminal. */)
2213 (Lisp_Object terminal)
2214 {
2215 struct terminal *t = decode_live_terminal (terminal);
2216
2217 if (t->type == output_termcap)
2218 return t->display_info.tty->top_frame;
2219 return Qnil;
2220 }
2221
2222 \f
2223
2224 DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2225 doc: /* Suspend the terminal device TTY.
2226
2227 The device is restored to its default state, and Emacs ceases all
2228 access to the tty device. Frames that use the device are not deleted,
2229 but input is not read from them and if they change, their display is
2230 not updated.
2231
2232 TTY may be a terminal object, a frame, or nil for the terminal device
2233 of the currently selected frame.
2234
2235 This function runs `suspend-tty-functions' after suspending the
2236 device. The functions are run with one arg, the id of the suspended
2237 terminal device.
2238
2239 `suspend-tty' does nothing if it is called on a device that is already
2240 suspended.
2241
2242 A suspended tty may be resumed by calling `resume-tty' on it. */)
2243 (Lisp_Object tty)
2244 {
2245 struct terminal *t = decode_tty_terminal (tty);
2246 FILE *f;
2247
2248 if (!t)
2249 error ("Attempt to suspend a non-text terminal device");
2250
2251 f = t->display_info.tty->input;
2252
2253 if (f)
2254 {
2255 /* First run `suspend-tty-functions' and then clean up the tty
2256 state because `suspend-tty-functions' might need to change
2257 the tty state. */
2258 Lisp_Object term;
2259 XSETTERMINAL (term, t);
2260 CALLN (Frun_hook_with_args, intern ("suspend-tty-functions"), term);
2261
2262 reset_sys_modes (t->display_info.tty);
2263 delete_keyboard_wait_descriptor (fileno (f));
2264
2265 #ifndef MSDOS
2266 fclose (f);
2267 if (f != t->display_info.tty->output)
2268 fclose (t->display_info.tty->output);
2269 #endif
2270
2271 t->display_info.tty->input = 0;
2272 t->display_info.tty->output = 0;
2273
2274 if (FRAMEP (t->display_info.tty->top_frame))
2275 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
2276
2277 }
2278
2279 /* Clear display hooks to prevent further output. */
2280 clear_tty_hooks (t);
2281
2282 return Qnil;
2283 }
2284
2285 DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2286 doc: /* Resume the previously suspended terminal device TTY.
2287 The terminal is opened and reinitialized. Frames that are on the
2288 suspended terminal are revived.
2289
2290 It is an error to resume a terminal while another terminal is active
2291 on the same device.
2292
2293 This function runs `resume-tty-functions' after resuming the terminal.
2294 The functions are run with one arg, the id of the resumed terminal
2295 device.
2296
2297 `resume-tty' does nothing if it is called on a device that is not
2298 suspended.
2299
2300 TTY may be a terminal object, a frame, or nil (meaning the selected
2301 frame's terminal). */)
2302 (Lisp_Object tty)
2303 {
2304 struct terminal *t = decode_tty_terminal (tty);
2305 int fd;
2306
2307 if (!t)
2308 error ("Attempt to resume a non-text terminal device");
2309
2310 if (!t->display_info.tty->input)
2311 {
2312 if (get_named_terminal (t->display_info.tty->name))
2313 error ("Cannot resume display while another display is active on the same device");
2314
2315 #ifdef MSDOS
2316 t->display_info.tty->output = stdout;
2317 t->display_info.tty->input = stdin;
2318 #else /* !MSDOS */
2319 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
2320 t->display_info.tty->input = t->display_info.tty->output
2321 = fd < 0 ? 0 : fdopen (fd, "w+");
2322
2323 if (! t->display_info.tty->input)
2324 {
2325 int open_errno = errno;
2326 emacs_close (fd);
2327 report_file_errno ("Cannot reopen tty device",
2328 build_string (t->display_info.tty->name),
2329 open_errno);
2330 }
2331
2332 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
2333 dissociate_if_controlling_tty (fd);
2334 #endif
2335
2336 add_keyboard_wait_descriptor (fd);
2337
2338 if (FRAMEP (t->display_info.tty->top_frame))
2339 {
2340 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2341 int width, height;
2342 int old_height = FRAME_COLS (f);
2343 int old_width = FRAME_TOTAL_LINES (f);
2344
2345 /* Check if terminal/window size has changed while the frame
2346 was suspended. */
2347 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2348 if (width != old_width || height != old_height)
2349 change_frame_size (f, width, height - FRAME_MENU_BAR_LINES (f),
2350 0, 0, 0, 0);
2351 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
2352 }
2353
2354 set_tty_hooks (t);
2355 init_sys_modes (t->display_info.tty);
2356
2357 /* Run `resume-tty-functions'. */
2358 Lisp_Object term;
2359 XSETTERMINAL (term, t);
2360 CALLN (Frun_hook_with_args, intern ("resume-tty-functions"), term);
2361 }
2362
2363 set_tty_hooks (t);
2364
2365 return Qnil;
2366 }
2367
2368 \f
2369 /***********************************************************************
2370 Mouse
2371 ***********************************************************************/
2372
2373 #ifdef HAVE_GPM
2374
2375 #ifndef HAVE_WINDOW_SYSTEM
2376 void
2377 term_mouse_moveto (int x, int y)
2378 {
2379 /* TODO: how to set mouse position?
2380 const char *name;
2381 int fd;
2382 name = (const char *) ttyname (0);
2383 fd = emacs_open (name, O_WRONLY, 0);
2384 SOME_FUNCTION (x, y, fd);
2385 emacs_close (fd);
2386 last_mouse_x = x;
2387 last_mouse_y = y; */
2388 }
2389 #endif /* HAVE_WINDOW_SYSTEM */
2390
2391 /* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2392 void
2393 tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2394 int start_hpos, int end_hpos,
2395 enum draw_glyphs_face draw)
2396 {
2397 int nglyphs = end_hpos - start_hpos;
2398 struct frame *f = XFRAME (WINDOW_FRAME (w));
2399 struct tty_display_info *tty = FRAME_TTY (f);
2400 int face_id = tty->mouse_highlight.mouse_face_face_id;
2401 int save_x, save_y, pos_x, pos_y;
2402
2403 if (end_hpos >= row->used[TEXT_AREA])
2404 nglyphs = row->used[TEXT_AREA] - start_hpos;
2405
2406 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2407 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
2408
2409 /* Save current cursor co-ordinates. */
2410 save_y = curY (tty);
2411 save_x = curX (tty);
2412 cursor_to (f, pos_y, pos_x);
2413
2414 if (draw == DRAW_MOUSE_FACE)
2415 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2416 nglyphs, face_id);
2417 else if (draw == DRAW_NORMAL_TEXT)
2418 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
2419
2420 cursor_to (f, save_y, save_x);
2421 }
2422
2423 static bool
2424 term_mouse_movement (struct frame *frame, Gpm_Event *event)
2425 {
2426 /* Has the mouse moved off the glyph it was on at the last sighting? */
2427 if (event->x != last_mouse_x || event->y != last_mouse_y)
2428 {
2429 frame->mouse_moved = 1;
2430 note_mouse_highlight (frame, event->x, event->y);
2431 /* Remember which glyph we're now on. */
2432 last_mouse_x = event->x;
2433 last_mouse_y = event->y;
2434 return 1;
2435 }
2436 return 0;
2437 }
2438
2439 /* Return the Time that corresponds to T. Wrap around on overflow. */
2440 static Time
2441 timeval_to_Time (struct timeval const *t)
2442 {
2443 Time s_1000, ms;
2444
2445 s_1000 = t->tv_sec;
2446 s_1000 *= 1000;
2447 ms = t->tv_usec / 1000;
2448 return s_1000 + ms;
2449 }
2450
2451 /* Return the current position of the mouse.
2452
2453 Set *f to the frame the mouse is in, or zero if the mouse is in no
2454 Emacs frame. If it is set to zero, all the other arguments are
2455 garbage.
2456
2457 Set *bar_window to Qnil, and *x and *y to the column and
2458 row of the character cell the mouse is over.
2459
2460 Set *timeptr to the time the mouse was at the returned position.
2461
2462 This clears mouse_moved until the next motion
2463 event arrives. */
2464 static void
2465 term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
2466 enum scroll_bar_part *part, Lisp_Object *x,
2467 Lisp_Object *y, Time *timeptr)
2468 {
2469 struct timeval now;
2470
2471 *fp = SELECTED_FRAME ();
2472 (*fp)->mouse_moved = 0;
2473
2474 *bar_window = Qnil;
2475 *part = scroll_bar_above_handle;
2476
2477 XSETINT (*x, last_mouse_x);
2478 XSETINT (*y, last_mouse_y);
2479 gettimeofday(&now, 0);
2480 *timeptr = timeval_to_Time (&now);
2481 }
2482
2483 /* Prepare a mouse-event in *RESULT for placement in the input queue.
2484
2485 If the event is a button press, then note that we have grabbed
2486 the mouse. */
2487
2488 static Lisp_Object
2489 term_mouse_click (struct input_event *result, Gpm_Event *event,
2490 struct frame *f)
2491 {
2492 struct timeval now;
2493 int i, j;
2494
2495 result->kind = GPM_CLICK_EVENT;
2496 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2497 {
2498 if (event->buttons & j) {
2499 result->code = i; /* button number */
2500 break;
2501 }
2502 }
2503 gettimeofday(&now, 0);
2504 result->timestamp = timeval_to_Time (&now);
2505
2506 if (event->type & GPM_UP)
2507 result->modifiers = up_modifier;
2508 else if (event->type & GPM_DOWN)
2509 result->modifiers = down_modifier;
2510 else
2511 result->modifiers = 0;
2512
2513 if (event->type & GPM_SINGLE)
2514 result->modifiers |= click_modifier;
2515
2516 if (event->type & GPM_DOUBLE)
2517 result->modifiers |= double_modifier;
2518
2519 if (event->type & GPM_TRIPLE)
2520 result->modifiers |= triple_modifier;
2521
2522 if (event->type & GPM_DRAG)
2523 result->modifiers |= drag_modifier;
2524
2525 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
2526
2527 /* 1 << KG_SHIFT */
2528 if (event->modifiers & (1 << 0))
2529 result->modifiers |= shift_modifier;
2530
2531 /* 1 << KG_CTRL */
2532 if (event->modifiers & (1 << 2))
2533 result->modifiers |= ctrl_modifier;
2534
2535 /* 1 << KG_ALT || KG_ALTGR */
2536 if (event->modifiers & (1 << 3)
2537 || event->modifiers & (1 << 1))
2538 result->modifiers |= meta_modifier;
2539 }
2540
2541 XSETINT (result->x, event->x);
2542 XSETINT (result->y, event->y);
2543 XSETFRAME (result->frame_or_window, f);
2544 result->arg = Qnil;
2545 return Qnil;
2546 }
2547
2548 int
2549 handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
2550 {
2551 struct frame *f = XFRAME (tty->top_frame);
2552 struct input_event ie;
2553 bool do_help = 0;
2554 int count = 0;
2555
2556 EVENT_INIT (ie);
2557 ie.kind = NO_EVENT;
2558 ie.arg = Qnil;
2559
2560 if (event->type & (GPM_MOVE | GPM_DRAG)) {
2561 previous_help_echo_string = help_echo_string;
2562 help_echo_string = Qnil;
2563
2564 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
2565
2566 if (!term_mouse_movement (f, event))
2567 help_echo_string = previous_help_echo_string;
2568
2569 /* If the contents of the global variable help_echo_string
2570 has changed, generate a HELP_EVENT. */
2571 if (!NILP (help_echo_string)
2572 || !NILP (previous_help_echo_string))
2573 do_help = 1;
2574
2575 goto done;
2576 }
2577 else {
2578 f->mouse_moved = 0;
2579 term_mouse_click (&ie, event, f);
2580 }
2581
2582 done:
2583 if (ie.kind != NO_EVENT)
2584 {
2585 kbd_buffer_store_event_hold (&ie, hold_quit);
2586 count++;
2587 }
2588
2589 if (do_help
2590 && !(hold_quit && hold_quit->kind != NO_EVENT))
2591 {
2592 Lisp_Object frame;
2593
2594 if (f)
2595 XSETFRAME (frame, f);
2596 else
2597 frame = Qnil;
2598
2599 gen_help_event (help_echo_string, frame, help_echo_window,
2600 help_echo_object, help_echo_pos);
2601 count++;
2602 }
2603
2604 return count;
2605 }
2606
2607 DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
2608 0, 0, 0,
2609 doc: /* Open a connection to Gpm.
2610 Gpm-mouse can only be activated for one tty at a time. */)
2611 (void)
2612 {
2613 struct frame *f = SELECTED_FRAME ();
2614 struct tty_display_info *tty
2615 = ((f)->output_method == output_termcap
2616 ? (f)->terminal->display_info.tty : NULL);
2617 Gpm_Connect connection;
2618
2619 if (!tty)
2620 error ("Gpm-mouse only works in the GNU/Linux console");
2621 if (gpm_tty == tty)
2622 return Qnil; /* Already activated, nothing to do. */
2623 if (gpm_tty)
2624 error ("Gpm-mouse can only be activated for one tty at a time");
2625
2626 connection.eventMask = ~0;
2627 connection.defaultMask = ~GPM_HARD;
2628 connection.maxMod = ~0;
2629 connection.minMod = 0;
2630 gpm_zerobased = 1;
2631
2632 if (Gpm_Open (&connection, 0) < 0)
2633 error ("Gpm-mouse failed to connect to the gpm daemon");
2634 else
2635 {
2636 gpm_tty = tty;
2637 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2638 to generate SIGIOs. Apparently we need to call reset_sys_modes
2639 before calling init_sys_modes. */
2640 reset_sys_modes (tty);
2641 init_sys_modes (tty);
2642 add_gpm_wait_descriptor (gpm_fd);
2643 return Qnil;
2644 }
2645 }
2646
2647 void
2648 close_gpm (int fd)
2649 {
2650 if (fd >= 0)
2651 delete_gpm_wait_descriptor (fd);
2652 while (Gpm_Close()); /* close all the stack */
2653 gpm_tty = NULL;
2654 }
2655
2656 DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
2657 0, 0, 0,
2658 doc: /* Close a connection to Gpm. */)
2659 (void)
2660 {
2661 struct frame *f = SELECTED_FRAME ();
2662 struct tty_display_info *tty
2663 = ((f)->output_method == output_termcap
2664 ? (f)->terminal->display_info.tty : NULL);
2665
2666 if (!tty || gpm_tty != tty)
2667 return Qnil; /* Not activated on this terminal, nothing to do. */
2668
2669 close_gpm (gpm_fd);
2670 return Qnil;
2671 }
2672 #endif /* HAVE_GPM */
2673
2674 \f
2675 /***********************************************************************
2676 Menus
2677 ***********************************************************************/
2678
2679 #if !defined (MSDOS)
2680
2681 /* TTY menu implementation and main ideas are borrowed from msdos.c.
2682
2683 However, unlike on MSDOS, where the menu text is drawn directly to
2684 the display video memory, on a TTY we use display_string (see
2685 display_tty_menu_item in xdisp.c) to put the glyphs produced from
2686 the menu items into the frame's 'desired_matrix' glyph matrix, and
2687 then call update_frame_with_menu to deliver the results to the
2688 glass. The previous contents of the screen, in the form of the
2689 current_matrix, is stashed away, and used to restore screen
2690 contents when the menu selection changes or when the final
2691 selection is made and the menu should be popped down.
2692
2693 The idea of this implementation was suggested by Gerd Moellmann. */
2694
2695 #define TTYM_FAILURE -1
2696 #define TTYM_SUCCESS 1
2697 #define TTYM_NO_SELECT 2
2698 #define TTYM_IA_SELECT 3
2699 #define TTYM_NEXT 4
2700 #define TTYM_PREV 5
2701
2702 /* These hold text of the current and the previous menu help messages. */
2703 static const char *menu_help_message, *prev_menu_help_message;
2704 /* Pane number and item number of the menu item which generated the
2705 last menu help message. */
2706 static int menu_help_paneno, menu_help_itemno;
2707
2708 typedef struct tty_menu_struct
2709 {
2710 int count;
2711 char **text;
2712 struct tty_menu_struct **submenu;
2713 int *panenumber; /* Also used as enabled flag. */
2714 ptrdiff_t allocated;
2715 int panecount;
2716 int width;
2717 const char **help_text;
2718 } tty_menu;
2719
2720 /* Create a brand new menu structure. */
2721
2722 static tty_menu *
2723 tty_menu_create (void)
2724 {
2725 return xzalloc (sizeof *tty_menu_create ());
2726 }
2727
2728 /* Allocate some (more) memory for MENU ensuring that there is room for one
2729 more item. */
2730
2731 static void
2732 tty_menu_make_room (tty_menu *menu)
2733 {
2734 if (menu->allocated == menu->count)
2735 {
2736 ptrdiff_t allocated = menu->allocated;
2737 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2738 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2739 menu->submenu = xrealloc (menu->submenu,
2740 allocated * sizeof *menu->submenu);
2741 menu->panenumber = xrealloc (menu->panenumber,
2742 allocated * sizeof *menu->panenumber);
2743 menu->help_text = xrealloc (menu->help_text,
2744 allocated * sizeof *menu->help_text);
2745 menu->allocated = allocated;
2746 }
2747 }
2748
2749 /* Search the given menu structure for a given pane number. */
2750
2751 static tty_menu *
2752 tty_menu_search_pane (tty_menu *menu, int pane)
2753 {
2754 int i;
2755 tty_menu *try;
2756
2757 for (i = 0; i < menu->count; i++)
2758 if (menu->submenu[i])
2759 {
2760 if (pane == menu->panenumber[i])
2761 return menu->submenu[i];
2762 try = tty_menu_search_pane (menu->submenu[i], pane);
2763 if (try)
2764 return try;
2765 }
2766 return (tty_menu *) 0;
2767 }
2768
2769 /* Determine how much screen space a given menu needs. */
2770
2771 static void
2772 tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2773 {
2774 int i, h2, w2, maxsubwidth, maxheight;
2775
2776 maxsubwidth = menu->width;
2777 maxheight = menu->count;
2778 for (i = 0; i < menu->count; i++)
2779 {
2780 if (menu->submenu[i])
2781 {
2782 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2783 if (w2 > maxsubwidth) maxsubwidth = w2;
2784 if (i + h2 > maxheight) maxheight = i + h2;
2785 }
2786 }
2787 *width = maxsubwidth;
2788 *height = maxheight;
2789 }
2790
2791 static void
2792 mouse_get_xy (int *x, int *y)
2793 {
2794 struct frame *sf = SELECTED_FRAME ();
2795 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
2796 enum scroll_bar_part part_dummy;
2797 Time time_dummy;
2798
2799 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2800 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2801 &lisp_dummy, &part_dummy,
2802 &lmx, &lmy,
2803 &time_dummy);
2804 if (!NILP (lmx))
2805 {
2806 *x = XINT (lmx);
2807 *y = XINT (lmy);
2808 }
2809 }
2810
2811 /* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2812 (zero-based). */
2813
2814 static void
2815 tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
2816 int mx, int my, int first_item, bool disp_help)
2817 {
2818 int i, face, width, enabled, mousehere, row, col;
2819 struct frame *sf = SELECTED_FRAME ();
2820 struct tty_display_info *tty = FRAME_TTY (sf);
2821 /* Don't try to display more menu items than the console can display
2822 using the available screen lines. Exclude the echo area line, as
2823 it will be overwritten by the help-echo anyway. */
2824 int max_items = min (menu->count - first_item, FRAME_TOTAL_LINES (sf) - 1 - y);
2825
2826 menu_help_message = NULL;
2827
2828 width = menu->width;
2829 col = cursorX (tty);
2830 row = cursorY (tty);
2831 for (i = 0; i < max_items; i++)
2832 {
2833 int max_width = width + 2; /* +2 for padding blanks on each side */
2834 int j = i + first_item;
2835
2836 if (menu->submenu[j])
2837 max_width += 2; /* for displaying " >" after the item */
2838 enabled
2839 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
2840 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2841 face = faces[enabled + mousehere * 2];
2842 /* Display the menu help string for the i-th menu item even if
2843 the menu item is currently disabled. That's what the GUI
2844 code does. */
2845 if (disp_help && enabled + mousehere * 2 >= 2)
2846 {
2847 menu_help_message = menu->help_text[j];
2848 menu_help_paneno = pn - 1;
2849 menu_help_itemno = j;
2850 }
2851 /* Take note of the coordinates of the active menu item, to
2852 display the cursor there. */
2853 if (mousehere)
2854 {
2855 row = y + i;
2856 col = x;
2857 }
2858 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2859 menu->submenu[j] != NULL);
2860 }
2861 update_frame_with_menu (sf, row, col);
2862 }
2863
2864 /* --------------------------- X Menu emulation ---------------------- */
2865
2866 /* Create a new pane and place it on the outer-most level. */
2867
2868 static int
2869 tty_menu_add_pane (tty_menu *menu, const char *txt)
2870 {
2871 int len;
2872
2873 tty_menu_make_room (menu);
2874 menu->submenu[menu->count] = tty_menu_create ();
2875 menu->text[menu->count] = (char *)txt;
2876 menu->panenumber[menu->count] = ++menu->panecount;
2877 menu->help_text[menu->count] = NULL;
2878 menu->count++;
2879
2880 /* Update the menu width, if necessary. */
2881 len = menu_item_width ((const unsigned char *) txt);
2882 if (len > menu->width)
2883 menu->width = len;
2884
2885 return menu->panecount;
2886 }
2887
2888 /* Create a new item in a menu pane. */
2889
2890 static bool
2891 tty_menu_add_selection (tty_menu *menu, int pane,
2892 char *txt, bool enable, char const *help_text)
2893 {
2894 int len;
2895
2896 if (pane)
2897 {
2898 menu = tty_menu_search_pane (menu, pane);
2899 if (! menu)
2900 return 0;
2901 }
2902 tty_menu_make_room (menu);
2903 menu->submenu[menu->count] = (tty_menu *) 0;
2904 menu->text[menu->count] = txt;
2905 menu->panenumber[menu->count] = enable;
2906 menu->help_text[menu->count] = help_text;
2907 menu->count++;
2908
2909 /* Update the menu width, if necessary. */
2910 len = menu_item_width ((const unsigned char *) txt);
2911 if (len > menu->width)
2912 menu->width = len;
2913
2914 return 1;
2915 }
2916
2917 /* Decide where the menu would be placed if requested at (X,Y). */
2918
2919 static void
2920 tty_menu_locate (tty_menu *menu, int x, int y,
2921 int *ulx, int *uly, int *width, int *height)
2922 {
2923 tty_menu_calc_size (menu, width, height);
2924 *ulx = x + 1;
2925 *uly = y;
2926 *width += 2;
2927 }
2928
2929 struct tty_menu_state
2930 {
2931 struct glyph_matrix *screen_behind;
2932 tty_menu *menu;
2933 int pane;
2934 int x, y;
2935 };
2936
2937 /* Save away the contents of frame F's current frame matrix, and
2938 enable all its rows. Value is a glyph matrix holding the contents
2939 of F's current frame matrix with all its glyph rows enabled. */
2940
2941 static struct glyph_matrix *
2942 save_and_enable_current_matrix (struct frame *f)
2943 {
2944 int i;
2945 struct glyph_matrix *saved = xzalloc (sizeof *saved);
2946 saved->nrows = f->current_matrix->nrows;
2947 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
2948
2949 for (i = 0; i < saved->nrows; ++i)
2950 {
2951 struct glyph_row *from = f->current_matrix->rows + i;
2952 struct glyph_row *to = saved->rows + i;
2953 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2954
2955 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
2956 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2957 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2958 /* Make sure every row is enabled, or else update_frame will not
2959 redraw them. (Rows that are identical to what is already on
2960 screen will not be redrawn anyway.) */
2961 to->enabled_p = true;
2962 to->hash = from->hash;
2963 }
2964
2965 return saved;
2966 }
2967
2968 /* Restore the contents of frame F's desired frame matrix from SAVED,
2969 and free memory associated with SAVED. */
2970
2971 static void
2972 restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
2973 {
2974 int i;
2975
2976 for (i = 0; i < saved->nrows; ++i)
2977 {
2978 struct glyph_row *from = saved->rows + i;
2979 struct glyph_row *to = f->desired_matrix->rows + i;
2980 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
2981
2982 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
2983 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
2984 to->used[TEXT_AREA] = from->used[TEXT_AREA];
2985 to->enabled_p = from->enabled_p;
2986 to->hash = from->hash;
2987 }
2988 }
2989
2990 static void
2991 free_saved_screen (struct glyph_matrix *saved)
2992 {
2993 int i;
2994
2995 if (!saved)
2996 return; /* Already freed! */
2997
2998 for (i = 0; i < saved->nrows; ++i)
2999 {
3000 struct glyph_row *from = saved->rows + i;
3001
3002 xfree (from->glyphs[TEXT_AREA]);
3003 }
3004
3005 xfree (saved->rows);
3006 xfree (saved);
3007 }
3008
3009 /* Update the display of frame F from its saved contents. */
3010 static void
3011 screen_update (struct frame *f, struct glyph_matrix *mtx)
3012 {
3013 restore_desired_matrix (f, mtx);
3014 update_frame_with_menu (f, -1, -1);
3015 }
3016
3017 typedef enum {
3018 MI_QUIT_MENU = -1,
3019 MI_CONTINUE = 0,
3020 MI_ITEM_SELECTED = 1,
3021 MI_NEXT_ITEM = 2,
3022 MI_PREV_ITEM = 3,
3023 MI_SCROLL_FORWARD = 4,
3024 MI_SCROLL_BACK = 5
3025 } mi_result;
3026
3027 /* Read user input and return X and Y coordinates where that input
3028 puts us. We only consider mouse movement and click events, and
3029 keyboard movement commands; the rest are ignored. */
3030 static mi_result
3031 read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3032 bool *first_time)
3033 {
3034 if (*first_time)
3035 {
3036 *first_time = false;
3037 sf->mouse_moved = 1;
3038 }
3039 else
3040 {
3041 Lisp_Object cmd;
3042 bool usable_input = 1;
3043 mi_result st = MI_CONTINUE;
3044 struct tty_display_info *tty = FRAME_TTY (sf);
3045 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
3046
3047 /* Signal the keyboard reading routines we are displaying a menu
3048 on this terminal. */
3049 tty->showing_menu = 1;
3050 /* We want mouse movements be reported by read_menu_command. */
3051 do_mouse_tracking = Qt;
3052 do {
3053 cmd = read_menu_command ();
3054 } while (NILP (cmd));
3055 tty->showing_menu = 0;
3056 do_mouse_tracking = saved_mouse_tracking;
3057
3058 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3059 /* If some input switched frames under our feet, exit the
3060 menu, since the menu faces are no longer valid, and the
3061 menu is no longer relevant anyway. */
3062 || sf != SELECTED_FRAME ())
3063 return MI_QUIT_MENU;
3064 if (EQ (cmd, Qtty_menu_mouse_movement))
3065 mouse_get_xy (x, y);
3066 else if (EQ (cmd, Qtty_menu_next_menu))
3067 {
3068 usable_input = 0;
3069 st = MI_NEXT_ITEM;
3070 }
3071 else if (EQ (cmd, Qtty_menu_prev_menu))
3072 {
3073 usable_input = 0;
3074 st = MI_PREV_ITEM;
3075 }
3076 else if (EQ (cmd, Qtty_menu_next_item))
3077 {
3078 if (*y < max_y)
3079 *y += 1;
3080 else
3081 st = MI_SCROLL_FORWARD;
3082 }
3083 else if (EQ (cmd, Qtty_menu_prev_item))
3084 {
3085 if (*y > min_y)
3086 *y -= 1;
3087 else
3088 st = MI_SCROLL_BACK;
3089 }
3090 else if (EQ (cmd, Qtty_menu_select))
3091 st = MI_ITEM_SELECTED;
3092 else if (!EQ (cmd, Qtty_menu_ignore))
3093 usable_input = 0;
3094 if (usable_input)
3095 sf->mouse_moved = 1;
3096 return st;
3097 }
3098 return MI_CONTINUE;
3099 }
3100
3101 /* Display menu, wait for user's response, and return that response. */
3102 static int
3103 tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3104 int x0, int y0, char **txt,
3105 void (*help_callback)(char const *, int, int),
3106 bool kbd_navigation)
3107 {
3108 struct tty_menu_state *state;
3109 int statecount, x, y, i;
3110 bool leave, onepane;
3111 int result IF_LINT (= 0);
3112 int title_faces[4]; /* Face to display the menu title. */
3113 int faces[4], buffers_num_deleted = 0;
3114 struct frame *sf = SELECTED_FRAME ();
3115 struct tty_display_info *tty = FRAME_TTY (sf);
3116 bool first_time;
3117 Lisp_Object selectface;
3118 int first_item = 0;
3119 int col, row;
3120 USE_SAFE_ALLOCA;
3121
3122 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3123 around the display. */
3124 if (x0 <= 0)
3125 x0 = 1;
3126 if (y0 <= 0)
3127 y0 = 1;
3128
3129 SAFE_NALLOCA (state, 1, menu->panecount);
3130 memset (state, 0, sizeof (*state));
3131 faces[0]
3132 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3133 DEFAULT_FACE_ID, 1);
3134 faces[1]
3135 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3136 DEFAULT_FACE_ID, 1);
3137 selectface = intern ("tty-menu-selected-face");
3138 faces[2] = lookup_derived_face (sf, selectface,
3139 faces[0], 1);
3140 faces[3] = lookup_derived_face (sf, selectface,
3141 faces[1], 1);
3142
3143 /* Make sure the menu title is always displayed with
3144 `tty-menu-selected-face', no matter where the mouse pointer is. */
3145 for (i = 0; i < 4; i++)
3146 title_faces[i] = faces[3];
3147
3148 statecount = 1;
3149
3150 /* Don't let the title for the "Buffers" popup menu include a
3151 digit (which is ugly).
3152
3153 This is a terrible kludge, but I think the "Buffers" case is
3154 the only one where the title includes a number, so it doesn't
3155 seem to be necessary to make this more general. */
3156 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3157 {
3158 menu->text[0][7] = '\0';
3159 buffers_num_deleted = 1;
3160 }
3161
3162 /* Force update of the current frame, so that the desired and the
3163 current matrices are identical. */
3164 update_frame_with_menu (sf, -1, -1);
3165 state[0].menu = menu;
3166 state[0].screen_behind = save_and_enable_current_matrix (sf);
3167
3168 /* Display the menu title. We subtract 1 from x0 and y0 because we
3169 want to interpret them as zero-based column and row coordinates,
3170 and also because we want the first item of the menu, not its
3171 title, to appear at x0,y0. */
3172 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
3173
3174 /* Turn off the cursor. Otherwise it shows through the menu
3175 panes, which is ugly. */
3176 col = cursorX (tty);
3177 row = cursorY (tty);
3178 tty_hide_cursor (tty);
3179
3180 if (buffers_num_deleted)
3181 menu->text[0][7] = ' ';
3182 onepane = menu->count == 1 && menu->submenu[0];
3183 if (onepane)
3184 {
3185 menu->width = menu->submenu[0]->width;
3186 state[0].menu = menu->submenu[0];
3187 }
3188 else
3189 {
3190 state[0].menu = menu;
3191 }
3192 state[0].x = x0 - 1;
3193 state[0].y = y0;
3194 state[0].pane = onepane;
3195
3196 x = state[0].x;
3197 y = state[0].y;
3198 first_time = true;
3199
3200 leave = 0;
3201 while (!leave)
3202 {
3203 mi_result input_status;
3204 int min_y = state[0].y;
3205 int max_y = min (min_y + state[0].menu->count, FRAME_TOTAL_LINES (sf) - 1) - 1;
3206
3207 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
3208 if (input_status)
3209 {
3210 leave = 1;
3211 switch (input_status)
3212 {
3213 case MI_QUIT_MENU:
3214 /* Remove the last help-echo, so that it doesn't
3215 re-appear after "Quit". */
3216 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3217 result = TTYM_NO_SELECT;
3218 break;
3219 case MI_NEXT_ITEM:
3220 if (kbd_navigation)
3221 result = TTYM_NEXT;
3222 else
3223 leave = 0;
3224 break;
3225 case MI_PREV_ITEM:
3226 if (kbd_navigation)
3227 result = TTYM_PREV;
3228 else
3229 leave = 0;
3230 break;
3231 case MI_SCROLL_FORWARD:
3232 if (y - min_y == state[0].menu->count - 1 - first_item)
3233 {
3234 y = min_y;
3235 first_item = 0;
3236 }
3237 else
3238 first_item++;
3239 leave = 0;
3240 break;
3241 case MI_SCROLL_BACK:
3242 if (first_item == 0)
3243 {
3244 y = max_y;
3245 first_item = state[0].menu->count - 1 - (y - min_y);
3246 }
3247 else
3248 first_item--;
3249 leave = 0;
3250 break;
3251 default:
3252 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3253 break;
3254 }
3255 }
3256 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
3257 {
3258 sf->mouse_moved = 0;
3259 result = TTYM_IA_SELECT;
3260 for (i = 0; i < statecount; i++)
3261 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3262 {
3263 int dy = y - state[i].y + first_item;
3264 if (0 <= dy && dy < state[i].menu->count)
3265 {
3266 if (!state[i].menu->submenu[dy])
3267 {
3268 if (state[i].menu->panenumber[dy])
3269 result = TTYM_SUCCESS;
3270 else
3271 result = TTYM_IA_SELECT;
3272 }
3273 *pane = state[i].pane - 1;
3274 *selidx = dy;
3275 /* We hit some part of a menu, so drop extra menus that
3276 have been opened. That does not include an open and
3277 active submenu. */
3278 if (i != statecount - 2
3279 || state[i].menu->submenu[dy] != state[i + 1].menu)
3280 while (i != statecount - 1)
3281 {
3282 statecount--;
3283 screen_update (sf, state[statecount].screen_behind);
3284 state[statecount].screen_behind = NULL;
3285 }
3286 if (i == statecount - 1 && state[i].menu->submenu[dy])
3287 {
3288 tty_menu_display (state[i].menu,
3289 state[i].x,
3290 state[i].y,
3291 state[i].pane,
3292 faces, x, y, first_item, 1);
3293 state[statecount].menu = state[i].menu->submenu[dy];
3294 state[statecount].pane = state[i].menu->panenumber[dy];
3295 state[statecount].screen_behind
3296 = save_and_enable_current_matrix (sf);
3297 state[statecount].x
3298 = state[i].x + state[i].menu->width + 2;
3299 state[statecount].y = y;
3300 statecount++;
3301 }
3302 }
3303 }
3304 tty_menu_display (state[statecount - 1].menu,
3305 state[statecount - 1].x,
3306 state[statecount - 1].y,
3307 state[statecount - 1].pane,
3308 faces, x, y, first_item, 1);
3309 /* The call to display help-echo below will move the cursor,
3310 so remember its current position as computed by
3311 tty_menu_display. */
3312 col = cursorX (tty);
3313 row = cursorY (tty);
3314 }
3315
3316 /* Display the help-echo message for the currently-selected menu
3317 item. */
3318 if ((menu_help_message || prev_menu_help_message)
3319 && menu_help_message != prev_menu_help_message)
3320 {
3321 help_callback (menu_help_message,
3322 menu_help_paneno, menu_help_itemno);
3323 /* Move the cursor to the beginning of the current menu
3324 item, so that screen readers and other accessibility aids
3325 know where the active region is. */
3326 cursor_to (sf, row, col);
3327 prev_menu_help_message = menu_help_message;
3328 }
3329 /* Both tty_menu_display and help_callback invoke update_end,
3330 which calls tty_show_cursor. Re-hide it, so it doesn't show
3331 through the menus. */
3332 tty_hide_cursor (tty);
3333 fflush (tty->output);
3334 }
3335
3336 sf->mouse_moved = 0;
3337 screen_update (sf, state[0].screen_behind);
3338 while (statecount--)
3339 free_saved_screen (state[statecount].screen_behind);
3340 tty_show_cursor (tty); /* Turn cursor back on. */
3341 fflush (tty->output);
3342
3343 /* Clean up any mouse events that are waiting inside Emacs event queue.
3344 These events are likely to be generated before the menu was even
3345 displayed, probably because the user pressed and released the button
3346 (which invoked the menu) too quickly. If we don't remove these events,
3347 Emacs will process them after we return and surprise the user. */
3348 discard_mouse_events ();
3349 if (!kbd_buffer_events_waiting ())
3350 clear_input_pending ();
3351 SAFE_FREE ();
3352 return result;
3353 }
3354
3355 /* Dispose of a menu. */
3356
3357 static void
3358 tty_menu_destroy (tty_menu *menu)
3359 {
3360 int i;
3361 if (menu->allocated)
3362 {
3363 for (i = 0; i < menu->count; i++)
3364 if (menu->submenu[i])
3365 tty_menu_destroy (menu->submenu[i]);
3366 xfree (menu->text);
3367 xfree (menu->submenu);
3368 xfree (menu->panenumber);
3369 xfree (menu->help_text);
3370 }
3371 xfree (menu);
3372 menu_help_message = prev_menu_help_message = NULL;
3373 }
3374
3375 /* Show help HELP_STRING, or clear help if HELP_STRING is null.
3376
3377 PANE is the pane number, and ITEM is the menu item number in
3378 the menu (currently not used). */
3379
3380 static void
3381 tty_menu_help_callback (char const *help_string, int pane, int item)
3382 {
3383 Lisp_Object *first_item;
3384 Lisp_Object pane_name;
3385 Lisp_Object menu_object;
3386
3387 first_item = XVECTOR (menu_items)->contents;
3388 if (EQ (first_item[0], Qt))
3389 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3390 else if (EQ (first_item[0], Qquote))
3391 /* This shouldn't happen, see xmenu_show. */
3392 pane_name = empty_unibyte_string;
3393 else
3394 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3395
3396 /* (menu-item MENU-NAME PANE-NUMBER) */
3397 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3398 show_help_echo (help_string ? build_string (help_string) : Qnil,
3399 Qnil, menu_object, make_number (item));
3400 }
3401
3402 static void
3403 tty_pop_down_menu (Lisp_Object arg)
3404 {
3405 tty_menu *menu = XSAVE_POINTER (arg, 0);
3406
3407 block_input ();
3408 tty_menu_destroy (menu);
3409 unblock_input ();
3410 }
3411
3412 /* Return the zero-based index of the last menu-bar item on frame F. */
3413 static int
3414 tty_menu_last_menubar_item (struct frame *f)
3415 {
3416 int i = 0;
3417
3418 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3419 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3420 {
3421 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3422
3423 while (i < ASIZE (items))
3424 {
3425 Lisp_Object str;
3426
3427 str = AREF (items, i + 1);
3428 if (NILP (str))
3429 break;
3430 i += 4;
3431 }
3432 i -= 4; /* Went one too far! */
3433 }
3434 return i;
3435 }
3436
3437 /* Find in frame F's menu bar the menu item that is next or previous
3438 to the item at X/Y, and return that item's position in X/Y. WHICH
3439 says which one--next or previous--item to look for. X and Y are
3440 measured in character cells. This should only be called on TTY
3441 frames. */
3442 static void
3443 tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3444 {
3445 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3446 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3447 {
3448 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3449 int last_i = tty_menu_last_menubar_item (f);
3450 int i, prev_x;
3451
3452 /* This loop assumes a single menu-bar line, and will fail to
3453 find an item if it is not in the first line. Note that
3454 make_lispy_event in keyboard.c makes the same assumption. */
3455 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3456 {
3457 Lisp_Object pos, str;
3458 int ix;
3459
3460 str = AREF (items, i + 1);
3461 pos = AREF (items, i + 3);
3462 if (NILP (str))
3463 return;
3464 ix = XINT (pos);
3465 if (ix <= *x
3466 /* We use <= so the blank between 2 items on a TTY is
3467 considered part of the previous item. */
3468 && *x <= ix + menu_item_width (SDATA (str)))
3469 {
3470 /* Found current item. Now compute the X coordinate of
3471 the previous or next item. */
3472 if (which == TTYM_NEXT)
3473 {
3474 if (i < last_i)
3475 *x = XINT (AREF (items, i + 4 + 3));
3476 else
3477 *x = 0; /* Wrap around to the first item. */
3478 }
3479 else if (prev_x < 0)
3480 {
3481 /* Wrap around to the last item. */
3482 *x = XINT (AREF (items, last_i + 3));
3483 }
3484 else
3485 *x = prev_x;
3486 return;
3487 }
3488 prev_x = ix;
3489 }
3490 }
3491 }
3492
3493 /* WINDOWSNT uses this as menu_show_hook, see w32console.c. */
3494 Lisp_Object
3495 tty_menu_show (struct frame *f, int x, int y, int menuflags,
3496 Lisp_Object title, const char **error_name)
3497 {
3498 tty_menu *menu;
3499 int pane, selidx, lpane, status;
3500 Lisp_Object entry, pane_prefix;
3501 char *datap;
3502 int ulx, uly, width, height;
3503 int item_x, item_y;
3504 int dispwidth, dispheight;
3505 int i, j, lines, maxlines;
3506 int maxwidth;
3507 ptrdiff_t specpdl_count;
3508
3509 eassert (FRAME_TERMCAP_P (f));
3510
3511 *error_name = 0;
3512 if (menu_items_n_panes == 0)
3513 return Qnil;
3514
3515 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3516 {
3517 *error_name = "Empty menu";
3518 return Qnil;
3519 }
3520
3521 /* Make the menu on that window. */
3522 menu = tty_menu_create ();
3523
3524 /* Don't GC while we prepare and show the menu, because we give the
3525 menu functions pointers to the contents of strings. */
3526 specpdl_count = inhibit_garbage_collection ();
3527
3528 /* Avoid crashes if, e.g., another client will connect while we
3529 are in a menu. */
3530 temporarily_switch_to_single_kboard (f);
3531
3532 /* Adjust coordinates to be root-window-relative. */
3533 item_x = x += f->left_pos;
3534 item_y = y += f->top_pos;
3535
3536 /* Create all the necessary panes and their items. */
3537 USE_SAFE_ALLOCA;
3538 maxwidth = maxlines = lines = i = 0;
3539 lpane = TTYM_FAILURE;
3540 while (i < menu_items_used)
3541 {
3542 if (EQ (AREF (menu_items, i), Qt))
3543 {
3544 /* Create a new pane. */
3545 Lisp_Object pane_name, prefix;
3546 const char *pane_string;
3547
3548 maxlines = max (maxlines, lines);
3549 lines = 0;
3550 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3551 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3552 pane_string = (NILP (pane_name)
3553 ? "" : SSDATA (pane_name));
3554 if ((menuflags & MENU_KEYMAPS) && !NILP (prefix))
3555 pane_string++;
3556
3557 lpane = tty_menu_add_pane (menu, pane_string);
3558 if (lpane == TTYM_FAILURE)
3559 {
3560 tty_menu_destroy (menu);
3561 *error_name = "Can't create pane";
3562 entry = Qnil;
3563 goto tty_menu_end;
3564 }
3565 i += MENU_ITEMS_PANE_LENGTH;
3566
3567 /* Find the width of the widest item in this pane. */
3568 j = i;
3569 while (j < menu_items_used)
3570 {
3571 Lisp_Object item;
3572 item = AREF (menu_items, j);
3573 if (EQ (item, Qt))
3574 break;
3575 if (NILP (item))
3576 {
3577 j++;
3578 continue;
3579 }
3580 width = SBYTES (item);
3581 if (width > maxwidth)
3582 maxwidth = width;
3583
3584 j += MENU_ITEMS_ITEM_LENGTH;
3585 }
3586 }
3587 /* Ignore a nil in the item list.
3588 It's meaningful only for dialog boxes. */
3589 else if (EQ (AREF (menu_items, i), Qquote))
3590 i += 1;
3591 else
3592 {
3593 /* Create a new item within current pane. */
3594 Lisp_Object item_name, enable, descrip, help;
3595 char *item_data;
3596 char const *help_string;
3597
3598 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3599 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3600 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3601 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
3602 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3603
3604 if (!NILP (descrip))
3605 {
3606 item_data = SAFE_ALLOCA (maxwidth + SBYTES (descrip) + 1);
3607 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3608 for (j = SCHARS (item_name); j < maxwidth; j++)
3609 item_data[j] = ' ';
3610 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3611 item_data[j + SBYTES (descrip)] = 0;
3612 }
3613 else
3614 item_data = SSDATA (item_name);
3615
3616 if (lpane == TTYM_FAILURE
3617 || (! tty_menu_add_selection (menu, lpane, item_data,
3618 !NILP (enable), help_string)))
3619 {
3620 tty_menu_destroy (menu);
3621 *error_name = "Can't add selection to menu";
3622 entry = Qnil;
3623 goto tty_menu_end;
3624 }
3625 i += MENU_ITEMS_ITEM_LENGTH;
3626 lines++;
3627 }
3628 }
3629
3630 maxlines = max (maxlines, lines);
3631
3632 /* All set and ready to fly. */
3633 dispwidth = f->text_cols;
3634 dispheight = f->text_lines;
3635 x = min (x, dispwidth);
3636 y = min (y, dispheight);
3637 x = max (x, 1);
3638 y = max (y, 1);
3639 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
3640 if (ulx + width > dispwidth)
3641 {
3642 x -= (ulx + width) - dispwidth;
3643 ulx = dispwidth - width;
3644 }
3645 if (uly + height > dispheight)
3646 {
3647 y -= (uly + height) - dispheight;
3648 uly = dispheight - height;
3649 }
3650
3651 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
3652 {
3653 /* Move the menu away of the echo area, to avoid overwriting the
3654 menu with help echo messages or vice versa. */
3655 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3656 {
3657 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3658 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3659 }
3660 else
3661 {
3662 y -= 2;
3663 uly -= 2;
3664 }
3665 }
3666
3667 if (ulx < 0) x -= ulx;
3668 if (uly < 0) y -= uly;
3669
3670 #if 0
3671 /* This code doesn't make sense on a TTY, since it can easily annul
3672 the adjustments above that carefully avoid truncation of the menu
3673 items. I think it was written to fix some problem that only
3674 happens on X11. */
3675 if (! for_click)
3676 {
3677 /* If position was not given by a mouse click, adjust so upper left
3678 corner of the menu as a whole ends up at given coordinates. This
3679 is what x-popup-menu says in its documentation. */
3680 x += width / 2;
3681 y += 1.5 * height / (maxlines + 2);
3682 }
3683 #endif
3684
3685 pane = selidx = 0;
3686
3687 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
3688
3689 specbind (Qoverriding_terminal_local_map,
3690 Fsymbol_value (Qtty_menu_navigation_map));
3691 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
3692 tty_menu_help_callback,
3693 menuflags & MENU_KBD_NAVIGATION);
3694 entry = pane_prefix = Qnil;
3695
3696 switch (status)
3697 {
3698 case TTYM_SUCCESS:
3699 /* Find the item number SELIDX in pane number PANE. */
3700 i = 0;
3701 while (i < menu_items_used)
3702 {
3703 if (EQ (AREF (menu_items, i), Qt))
3704 {
3705 if (pane == 0)
3706 pane_prefix
3707 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
3708 pane--;
3709 i += MENU_ITEMS_PANE_LENGTH;
3710 }
3711 else
3712 {
3713 if (pane == -1)
3714 {
3715 if (selidx == 0)
3716 {
3717 entry
3718 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
3719 if (menuflags & MENU_KEYMAPS)
3720 {
3721 entry = Fcons (entry, Qnil);
3722 if (!NILP (pane_prefix))
3723 entry = Fcons (pane_prefix, entry);
3724 }
3725 break;
3726 }
3727 selidx--;
3728 }
3729 i += MENU_ITEMS_ITEM_LENGTH;
3730 }
3731 }
3732 break;
3733
3734 case TTYM_NEXT:
3735 case TTYM_PREV:
3736 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3737 entry = Fcons (make_number (item_x), make_number (item_y));
3738 break;
3739
3740 case TTYM_FAILURE:
3741 *error_name = "Can't activate menu";
3742 case TTYM_IA_SELECT:
3743 break;
3744 case TTYM_NO_SELECT:
3745 /* If the selected frame was changed while we displayed a menu,
3746 throw to top level in order to undo any temporary settings
3747 made by TTY menu code. */
3748 if (f != SELECTED_FRAME ())
3749 Ftop_level ();
3750 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3751 the menu was invoked with a mouse event as POSITION). */
3752 if (!(menuflags & MENU_FOR_CLICK))
3753 Fsignal (Qquit, Qnil);
3754 break;
3755 }
3756
3757 tty_menu_end:
3758
3759 SAFE_FREE ();
3760 unbind_to (specpdl_count, Qnil);
3761 return entry;
3762 }
3763
3764 #endif /* !MSDOS */
3765
3766 \f
3767 #ifndef MSDOS
3768 /***********************************************************************
3769 Initialization
3770 ***********************************************************************/
3771
3772 /* Initialize the tty-dependent part of frame F. The frame must
3773 already have its device initialized. */
3774
3775 void
3776 create_tty_output (struct frame *f)
3777 {
3778 struct tty_output *t = xzalloc (sizeof *t);
3779
3780 eassert (FRAME_TERMCAP_P (f));
3781
3782 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
3783
3784 f->output_data.tty = t;
3785 }
3786
3787 /* Delete frame F's face cache, and its tty-dependent part. */
3788
3789 static void
3790 tty_free_frame_resources (struct frame *f)
3791 {
3792 eassert (FRAME_TERMCAP_P (f));
3793 free_frame_faces (f);
3794 xfree (f->output_data.tty);
3795 }
3796
3797 #else /* MSDOS */
3798
3799 /* Delete frame F's face cache. */
3800
3801 static void
3802 tty_free_frame_resources (struct frame *f)
3803 {
3804 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
3805 free_frame_faces (f);
3806 }
3807 #endif /* MSDOS */
3808 \f
3809 /* Reset the hooks in TERMINAL. */
3810
3811 static void
3812 clear_tty_hooks (struct terminal *terminal)
3813 {
3814 terminal->rif = 0;
3815 terminal->cursor_to_hook = 0;
3816 terminal->raw_cursor_to_hook = 0;
3817 terminal->clear_to_end_hook = 0;
3818 terminal->clear_frame_hook = 0;
3819 terminal->clear_end_of_line_hook = 0;
3820 terminal->ins_del_lines_hook = 0;
3821 terminal->insert_glyphs_hook = 0;
3822 terminal->write_glyphs_hook = 0;
3823 terminal->delete_glyphs_hook = 0;
3824 terminal->ring_bell_hook = 0;
3825 terminal->reset_terminal_modes_hook = 0;
3826 terminal->set_terminal_modes_hook = 0;
3827 terminal->update_begin_hook = 0;
3828 terminal->update_end_hook = 0;
3829 terminal->set_terminal_window_hook = 0;
3830 terminal->mouse_position_hook = 0;
3831 terminal->frame_rehighlight_hook = 0;
3832 terminal->frame_raise_lower_hook = 0;
3833 terminal->fullscreen_hook = 0;
3834 terminal->menu_show_hook = 0;
3835 terminal->set_vertical_scroll_bar_hook = 0;
3836 terminal->set_horizontal_scroll_bar_hook = 0;
3837 terminal->condemn_scroll_bars_hook = 0;
3838 terminal->redeem_scroll_bar_hook = 0;
3839 terminal->judge_scroll_bars_hook = 0;
3840 terminal->read_socket_hook = 0;
3841 terminal->frame_up_to_date_hook = 0;
3842
3843 /* Leave these two set, or suspended frames are not deleted
3844 correctly. */
3845 terminal->delete_frame_hook = &tty_free_frame_resources;
3846 terminal->delete_terminal_hook = &delete_tty;
3847 }
3848
3849 /* Initialize hooks in TERMINAL with the values needed for a tty. */
3850
3851 static void
3852 set_tty_hooks (struct terminal *terminal)
3853 {
3854 terminal->cursor_to_hook = &tty_cursor_to;
3855 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3856 terminal->clear_to_end_hook = &tty_clear_to_end;
3857 terminal->clear_frame_hook = &tty_clear_frame;
3858 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3859 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3860 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3861 terminal->write_glyphs_hook = &tty_write_glyphs;
3862 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3863 terminal->ring_bell_hook = &tty_ring_bell;
3864 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3865 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3866 terminal->update_end_hook = &tty_update_end;
3867 #ifdef MSDOS
3868 terminal->menu_show_hook = &x_menu_show;
3869 #else
3870 terminal->menu_show_hook = &tty_menu_show;
3871 #endif
3872 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3873 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3874 terminal->delete_frame_hook = &tty_free_frame_resources;
3875 terminal->delete_terminal_hook = &delete_tty;
3876 /* Other hooks are NULL by default. */
3877 }
3878
3879 /* If FD is the controlling terminal, drop it. */
3880 static void
3881 dissociate_if_controlling_tty (int fd)
3882 {
3883 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3884 so dissociate it by invoking setsid. */
3885 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
3886 {
3887 #ifdef TIOCNOTTY
3888 /* setsid failed, presumably because Emacs is already a process
3889 group leader. Fall back on the obsolescent way to dissociate
3890 a controlling tty. */
3891 sigset_t oldset;
3892 block_tty_out_signal (&oldset);
3893 ioctl (fd, TIOCNOTTY, 0);
3894 unblock_tty_out_signal (&oldset);
3895 #endif
3896 }
3897 }
3898
3899 /* Create a termcap display on the tty device with the given name and
3900 type.
3901
3902 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3903 Otherwise NAME should be a path to the tty device file,
3904 e.g. "/dev/pts/7".
3905
3906 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3907
3908 If MUST_SUCCEED is true, then all errors are fatal. */
3909
3910 struct terminal *
3911 init_tty (const char *name, const char *terminal_type, bool must_succeed)
3912 {
3913 char *area;
3914 char **address = &area;
3915 int status;
3916 struct tty_display_info *tty = NULL;
3917 struct terminal *terminal = NULL;
3918 sigset_t oldset;
3919 bool ctty = false; /* True if asked to open controlling tty. */
3920
3921 if (!terminal_type)
3922 maybe_fatal (must_succeed, 0,
3923 "Unknown terminal type",
3924 "Unknown terminal type");
3925
3926 if (name == NULL)
3927 name = DEV_TTY;
3928 if (!strcmp (name, DEV_TTY))
3929 ctty = 1;
3930
3931 /* If we already have a terminal on the given device, use that. If
3932 all such terminals are suspended, create a new one instead. */
3933 /* XXX Perhaps this should be made explicit by having init_tty
3934 always create a new terminal and separating terminal and frame
3935 creation on Lisp level. */
3936 terminal = get_named_terminal (name);
3937 if (terminal)
3938 return terminal;
3939
3940 terminal = create_terminal (output_termcap, NULL);
3941 #ifdef MSDOS
3942 if (been_here > 0)
3943 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
3944 name, "");
3945 been_here = 1;
3946 tty = &the_only_display_info;
3947 #else
3948 tty = xzalloc (sizeof *tty);
3949 #endif
3950 tty->top_frame = Qnil;
3951 tty->next = tty_list;
3952 tty_list = tty;
3953
3954 terminal->display_info.tty = tty;
3955 tty->terminal = terminal;
3956
3957 tty->Wcm = xmalloc (sizeof *tty->Wcm);
3958 Wcm_clear (tty);
3959
3960 encode_terminal_src_size = 0;
3961 encode_terminal_dst_size = 0;
3962
3963
3964 #ifndef DOS_NT
3965 set_tty_hooks (terminal);
3966
3967 {
3968 /* Open the terminal device. */
3969
3970 /* If !ctty, don't recognize it as our controlling terminal, and
3971 don't make it the controlling tty if we don't have one now.
3972
3973 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
3974 defined on Hurd. On other systems, we need to explicitly
3975 dissociate ourselves from the controlling tty when we want to
3976 open a frame on the same terminal. */
3977 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
3978 int fd = emacs_open (name, flags, 0);
3979 tty->input = tty->output
3980 = ((fd < 0 || ! isatty (fd))
3981 ? NULL
3982 : fdopen (fd, "w+"));
3983
3984 if (! tty->input)
3985 {
3986 char const *diagnostic
3987 = (fd < 0) ? "Could not open file: %s" : "Not a tty device: %s";
3988 emacs_close (fd);
3989 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
3990 }
3991
3992 tty->name = xstrdup (name);
3993 terminal->name = xstrdup (name);
3994
3995 if (!O_IGNORE_CTTY && !ctty)
3996 dissociate_if_controlling_tty (fd);
3997 }
3998
3999 tty->type = xstrdup (terminal_type);
4000
4001 add_keyboard_wait_descriptor (fileno (tty->input));
4002
4003 Wcm_clear (tty);
4004
4005 /* On some systems, tgetent tries to access the controlling
4006 terminal. */
4007 block_tty_out_signal (&oldset);
4008 status = tgetent (tty->termcap_term_buffer, terminal_type);
4009 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4010 emacs_abort ();
4011 unblock_tty_out_signal (&oldset);
4012
4013 if (status < 0)
4014 {
4015 #ifdef TERMINFO
4016 maybe_fatal (must_succeed, terminal,
4017 "Cannot open terminfo database file",
4018 "Cannot open terminfo database file");
4019 #else
4020 maybe_fatal (must_succeed, terminal,
4021 "Cannot open termcap database file",
4022 "Cannot open termcap database file");
4023 #endif
4024 }
4025 if (status == 0)
4026 {
4027 maybe_fatal (must_succeed, terminal,
4028 "Terminal type %s is not defined",
4029 "Terminal type %s is not defined.\n\
4030 If that is not the actual type of terminal you have,\n\
4031 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4032 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4033 #ifdef TERMINFO
4034 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4035 #else
4036 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4037 #endif
4038 terminal_type);
4039 }
4040
4041 area = tty->termcap_strings_buffer;
4042 tty->TS_ins_line = tgetstr ("al", address);
4043 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4044 tty->TS_bell = tgetstr ("bl", address);
4045 BackTab (tty) = tgetstr ("bt", address);
4046 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4047 tty->TS_clr_line = tgetstr ("ce", address);
4048 tty->TS_clr_frame = tgetstr ("cl", address);
4049 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4050 AbsPosition (tty) = tgetstr ("cm", address);
4051 CR (tty) = tgetstr ("cr", address);
4052 tty->TS_set_scroll_region = tgetstr ("cs", address);
4053 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
4054 RowPosition (tty) = tgetstr ("cv", address);
4055 tty->TS_del_char = tgetstr ("dc", address);
4056 tty->TS_del_multi_chars = tgetstr ("DC", address);
4057 tty->TS_del_line = tgetstr ("dl", address);
4058 tty->TS_del_multi_lines = tgetstr ("DL", address);
4059 tty->TS_delete_mode = tgetstr ("dm", address);
4060 tty->TS_end_delete_mode = tgetstr ("ed", address);
4061 tty->TS_end_insert_mode = tgetstr ("ei", address);
4062 Home (tty) = tgetstr ("ho", address);
4063 tty->TS_ins_char = tgetstr ("ic", address);
4064 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4065 tty->TS_insert_mode = tgetstr ("im", address);
4066 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4067 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4068 tty->TS_keypad_mode = tgetstr ("ks", address);
4069 LastLine (tty) = tgetstr ("ll", address);
4070 Right (tty) = tgetstr ("nd", address);
4071 Down (tty) = tgetstr ("do", address);
4072 if (!Down (tty))
4073 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
4074 if (tgetflag ("bs"))
4075 Left (tty) = "\b"; /* Can't possibly be longer! */
4076 else /* (Actually, "bs" is obsolete...) */
4077 Left (tty) = tgetstr ("le", address);
4078 if (!Left (tty))
4079 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
4080 tty->TS_pad_char = tgetstr ("pc", address);
4081 tty->TS_repeat = tgetstr ("rp", address);
4082 tty->TS_end_standout_mode = tgetstr ("se", address);
4083 tty->TS_fwd_scroll = tgetstr ("sf", address);
4084 tty->TS_standout_mode = tgetstr ("so", address);
4085 tty->TS_rev_scroll = tgetstr ("sr", address);
4086 tty->Wcm->cm_tab = tgetstr ("ta", address);
4087 tty->TS_end_termcap_modes = tgetstr ("te", address);
4088 tty->TS_termcap_modes = tgetstr ("ti", address);
4089 Up (tty) = tgetstr ("up", address);
4090 tty->TS_visible_bell = tgetstr ("vb", address);
4091 tty->TS_cursor_normal = tgetstr ("ve", address);
4092 tty->TS_cursor_visible = tgetstr ("vs", address);
4093 tty->TS_cursor_invisible = tgetstr ("vi", address);
4094 tty->TS_set_window = tgetstr ("wi", address);
4095
4096 tty->TS_enter_underline_mode = tgetstr ("us", address);
4097 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4098 tty->TS_enter_bold_mode = tgetstr ("md", address);
4099 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
4100 tty->TS_enter_dim_mode = tgetstr ("mh", address);
4101 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4102 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4103 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4104 tty->TS_exit_attribute_mode = tgetstr ("me", address);
4105
4106 MultiUp (tty) = tgetstr ("UP", address);
4107 MultiDown (tty) = tgetstr ("DO", address);
4108 MultiLeft (tty) = tgetstr ("LE", address);
4109 MultiRight (tty) = tgetstr ("RI", address);
4110
4111 /* SVr4/ANSI color support. If "op" isn't available, don't support
4112 color because we can't switch back to the default foreground and
4113 background. */
4114 tty->TS_orig_pair = tgetstr ("op", address);
4115 if (tty->TS_orig_pair)
4116 {
4117 tty->TS_set_foreground = tgetstr ("AF", address);
4118 tty->TS_set_background = tgetstr ("AB", address);
4119 if (!tty->TS_set_foreground)
4120 {
4121 /* SVr4. */
4122 tty->TS_set_foreground = tgetstr ("Sf", address);
4123 tty->TS_set_background = tgetstr ("Sb", address);
4124 }
4125
4126 tty->TN_max_colors = tgetnum ("Co");
4127 tty->TN_max_pairs = tgetnum ("pa");
4128
4129 tty->TN_no_color_video = tgetnum ("NC");
4130 if (tty->TN_no_color_video == -1)
4131 tty->TN_no_color_video = 0;
4132 }
4133
4134 tty_default_color_capabilities (tty, 1);
4135
4136 MagicWrap (tty) = tgetflag ("xn");
4137 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4138 the former flag imply the latter. */
4139 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
4140 tty->memory_below_frame = tgetflag ("db");
4141 tty->TF_hazeltine = tgetflag ("hz");
4142 tty->must_write_spaces = tgetflag ("in");
4143 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4144 tty->TF_insmode_motion = tgetflag ("mi");
4145 tty->TF_standout_motion = tgetflag ("ms");
4146 tty->TF_underscore = tgetflag ("ul");
4147 tty->TF_teleray = tgetflag ("xt");
4148
4149 #else /* DOS_NT */
4150 #ifdef WINDOWSNT
4151 {
4152 struct frame *f = XFRAME (selected_frame);
4153 int height, width;
4154
4155 initialize_w32_display (terminal, &width, &height);
4156
4157 FrameRows (tty) = height;
4158 FrameCols (tty) = width;
4159 tty->specified_window = height;
4160
4161 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
4162 FRAME_HAS_HORIZONTAL_SCROLL_BARS (f) = 0;
4163 tty->char_ins_del_ok = 1;
4164 baud_rate = 19200;
4165 }
4166 #else /* MSDOS */
4167 {
4168 int height, width;
4169 if (strcmp (terminal_type, "internal") == 0)
4170 terminal->type = output_msdos_raw;
4171 initialize_msdos_display (terminal);
4172
4173 get_tty_size (fileno (tty->input), &width, &height);
4174 FrameCols (tty) = width;
4175 FrameRows (tty) = height;
4176 tty->char_ins_del_ok = 0;
4177 init_baud_rate (fileno (tty->input));
4178 }
4179 #endif /* MSDOS */
4180 tty->output = stdout;
4181 tty->input = stdin;
4182 /* The following two are inaccessible from w32console.c. */
4183 terminal->delete_frame_hook = &tty_free_frame_resources;
4184 terminal->delete_terminal_hook = &delete_tty;
4185
4186 tty->name = xstrdup (name);
4187 terminal->name = xstrdup (name);
4188 tty->type = xstrdup (terminal_type);
4189
4190 add_keyboard_wait_descriptor (0);
4191
4192 tty->delete_in_insert_mode = 1;
4193
4194 UseTabs (tty) = 0;
4195 tty->scroll_region_ok = 0;
4196
4197 /* Seems to insert lines when it's not supposed to, messing up the
4198 display. In doing a trace, it didn't seem to be called much, so I
4199 don't think we're losing anything by turning it off. */
4200 tty->line_ins_del_ok = 0;
4201
4202 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
4203 #endif /* DOS_NT */
4204
4205 #ifdef HAVE_GPM
4206 terminal->mouse_position_hook = term_mouse_position;
4207 tty->mouse_highlight.mouse_face_window = Qnil;
4208 #endif
4209
4210 terminal->kboard = allocate_kboard (Qnil);
4211 terminal->kboard->reference_count++;
4212 /* Don't let the initial kboard remain current longer than necessary.
4213 That would cause problems if a file loaded on startup tries to
4214 prompt in the mini-buffer. */
4215 if (current_kboard == initial_kboard)
4216 current_kboard = terminal->kboard;
4217 #ifndef DOS_NT
4218 term_get_fkeys (address, terminal->kboard);
4219
4220 /* Get frame size from system, or else from termcap. */
4221 {
4222 int height, width;
4223 get_tty_size (fileno (tty->input), &width, &height);
4224 FrameCols (tty) = width;
4225 FrameRows (tty) = height;
4226 }
4227
4228 if (FrameCols (tty) <= 0)
4229 FrameCols (tty) = tgetnum ("co");
4230 if (FrameRows (tty) <= 0)
4231 FrameRows (tty) = tgetnum ("li");
4232
4233 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
4234 maybe_fatal (must_succeed, terminal,
4235 "Screen size %dx%d is too small",
4236 "Screen size %dx%d is too small",
4237 FrameCols (tty), FrameRows (tty));
4238
4239 TabWidth (tty) = tgetnum ("tw");
4240
4241 if (!tty->TS_bell)
4242 tty->TS_bell = "\07";
4243
4244 if (!tty->TS_fwd_scroll)
4245 tty->TS_fwd_scroll = Down (tty);
4246
4247 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
4248
4249 if (TabWidth (tty) < 0)
4250 TabWidth (tty) = 8;
4251
4252 /* Turned off since /etc/termcap seems to have :ta= for most terminals
4253 and newer termcap doc does not seem to say there is a default.
4254 if (!tty->Wcm->cm_tab)
4255 tty->Wcm->cm_tab = "\t";
4256 */
4257
4258 /* We don't support standout modes that use `magic cookies', so
4259 turn off any that do. */
4260 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
4261 {
4262 tty->TS_standout_mode = 0;
4263 tty->TS_end_standout_mode = 0;
4264 }
4265 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
4266 {
4267 tty->TS_enter_underline_mode = 0;
4268 tty->TS_exit_underline_mode = 0;
4269 }
4270
4271 /* If there's no standout mode, try to use underlining instead. */
4272 if (tty->TS_standout_mode == 0)
4273 {
4274 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4275 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
4276 }
4277
4278 /* If no `se' string, try using a `me' string instead.
4279 If that fails, we can't use standout mode at all. */
4280 if (tty->TS_end_standout_mode == 0)
4281 {
4282 char *s = tgetstr ("me", address);
4283 if (s != 0)
4284 tty->TS_end_standout_mode = s;
4285 else
4286 tty->TS_standout_mode = 0;
4287 }
4288
4289 if (tty->TF_teleray)
4290 {
4291 tty->Wcm->cm_tab = 0;
4292 /* We can't support standout mode, because it uses magic cookies. */
4293 tty->TS_standout_mode = 0;
4294 /* But that means we cannot rely on ^M to go to column zero! */
4295 CR (tty) = 0;
4296 /* LF can't be trusted either -- can alter hpos. */
4297 /* If move at column 0 thru a line with TS_standout_mode. */
4298 Down (tty) = 0;
4299 }
4300
4301 tty->specified_window = FrameRows (tty);
4302
4303 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
4304 {
4305 maybe_fatal (must_succeed, terminal,
4306 "Terminal type \"%s\" is not powerful enough to run Emacs",
4307 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
4308 It lacks the ability to position the cursor.\n\
4309 If that is not the actual type of terminal you have,\n\
4310 use the Bourne shell command 'TERM=...; export TERM' (C-shell:\n\
4311 'setenv TERM ...') to specify the correct type. It may be necessary\n"
4312 # ifdef TERMINFO
4313 "to do 'unset TERMINFO' (C-shell: 'unsetenv TERMINFO') as well.",
4314 # else /* TERMCAP */
4315 "to do 'unset TERMCAP' (C-shell: 'unsetenv TERMCAP') as well.",
4316 # endif /* TERMINFO */
4317 terminal_type);
4318 }
4319
4320 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
4321 maybe_fatal (must_succeed, terminal,
4322 "Could not determine the frame size",
4323 "Could not determine the frame size");
4324
4325 tty->delete_in_insert_mode
4326 = tty->TS_delete_mode && tty->TS_insert_mode
4327 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
4328
4329 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
4330
4331 tty->scroll_region_ok
4332 = (tty->Wcm->cm_abs
4333 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
4334
4335 tty->line_ins_del_ok
4336 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4337 && (tty->TS_del_line || tty->TS_del_multi_lines))
4338 || (tty->scroll_region_ok
4339 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
4340
4341 tty->char_ins_del_ok
4342 = ((tty->TS_ins_char || tty->TS_insert_mode
4343 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4344 && (tty->TS_del_char || tty->TS_del_multi_chars));
4345
4346 init_baud_rate (fileno (tty->input));
4347
4348 #endif /* not DOS_NT */
4349
4350 /* Init system terminal modes (RAW or CBREAK, etc.). */
4351 init_sys_modes (tty);
4352
4353 return terminal;
4354 }
4355
4356
4357 static void
4358 vfatal (const char *str, va_list ap)
4359 {
4360 fprintf (stderr, "emacs: ");
4361 vfprintf (stderr, str, ap);
4362 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4363 fprintf (stderr, "\n");
4364 fflush (stderr);
4365 exit (1);
4366 }
4367
4368
4369 /* Auxiliary error-handling function for init_tty.
4370 Delete TERMINAL, then call error or fatal with str1 or str2,
4371 respectively, according to whether MUST_SUCCEED is true. */
4372
4373 static void
4374 maybe_fatal (bool must_succeed, struct terminal *terminal,
4375 const char *str1, const char *str2, ...)
4376 {
4377 va_list ap;
4378 va_start (ap, str2);
4379 if (terminal)
4380 delete_tty (terminal);
4381
4382 if (must_succeed)
4383 vfatal (str2, ap);
4384 else
4385 verror (str1, ap);
4386 }
4387
4388 void
4389 fatal (const char *str, ...)
4390 {
4391 va_list ap;
4392 va_start (ap, str);
4393 vfatal (str, ap);
4394 }
4395
4396 \f
4397
4398 /* Delete the given tty terminal, closing all frames on it. */
4399
4400 static void
4401 delete_tty (struct terminal *terminal)
4402 {
4403 struct tty_display_info *tty;
4404
4405 /* Protect against recursive calls. delete_frame in
4406 delete_terminal calls us back when it deletes our last frame. */
4407 if (!terminal->name)
4408 return;
4409
4410 eassert (terminal->type == output_termcap);
4411
4412 tty = terminal->display_info.tty;
4413
4414 if (tty == tty_list)
4415 tty_list = tty->next;
4416 else
4417 {
4418 struct tty_display_info *p;
4419 for (p = tty_list; p && p->next != tty; p = p->next)
4420 ;
4421
4422 if (! p)
4423 /* This should not happen. */
4424 emacs_abort ();
4425
4426 p->next = tty->next;
4427 tty->next = 0;
4428 }
4429
4430 /* reset_sys_modes needs a valid device, so this call needs to be
4431 before delete_terminal. */
4432 reset_sys_modes (tty);
4433
4434 delete_terminal (terminal);
4435
4436 xfree (tty->name);
4437 xfree (tty->type);
4438
4439 if (tty->input)
4440 {
4441 delete_keyboard_wait_descriptor (fileno (tty->input));
4442 if (tty->input != stdin)
4443 fclose (tty->input);
4444 }
4445 if (tty->output && tty->output != stdout && tty->output != tty->input)
4446 fclose (tty->output);
4447 if (tty->termscript)
4448 fclose (tty->termscript);
4449
4450 xfree (tty->old_tty);
4451 xfree (tty->Wcm);
4452 xfree (tty);
4453 }
4454
4455 void
4456 syms_of_term (void)
4457 {
4458 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
4459 doc: /* Non-nil means the system uses terminfo rather than termcap.
4460 This variable can be used by terminal emulator packages. */);
4461 #ifdef TERMINFO
4462 system_uses_terminfo = 1;
4463 #else
4464 system_uses_terminfo = 0;
4465 #endif
4466
4467 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
4468 doc: /* Functions run after suspending a tty.
4469 The functions are run with one argument, the terminal object to be suspended.
4470 See `suspend-tty'. */);
4471 Vsuspend_tty_functions = Qnil;
4472
4473
4474 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
4475 doc: /* Functions run after resuming a tty.
4476 The functions are run with one argument, the terminal object that was revived.
4477 See `resume-tty'. */);
4478 Vresume_tty_functions = Qnil;
4479
4480 DEFVAR_BOOL ("visible-cursor", visible_cursor,
4481 doc: /* Non-nil means to make the cursor very visible.
4482 This only has an effect when running in a text terminal.
4483 What means \"very visible\" is up to your terminal. It may make the cursor
4484 bigger, or it may make it blink, or it may do nothing at all. */);
4485 visible_cursor = 1;
4486
4487 defsubr (&Stty_display_color_p);
4488 defsubr (&Stty_display_color_cells);
4489 defsubr (&Stty_no_underline);
4490 defsubr (&Stty_type);
4491 defsubr (&Scontrolling_tty_p);
4492 defsubr (&Stty_top_frame);
4493 defsubr (&Ssuspend_tty);
4494 defsubr (&Sresume_tty);
4495 #ifdef HAVE_GPM
4496 defsubr (&Sgpm_mouse_start);
4497 defsubr (&Sgpm_mouse_stop);
4498 #endif /* HAVE_GPM */
4499
4500 #ifndef DOS_NT
4501 default_orig_pair = NULL;
4502 default_set_foreground = NULL;
4503 default_set_background = NULL;
4504 #endif /* !DOS_NT */
4505
4506 encode_terminal_src = NULL;
4507 encode_terminal_dst = NULL;
4508
4509 DEFSYM (Qtty_mode_set_strings, "tty-mode-set-strings");
4510 DEFSYM (Qtty_mode_reset_strings, "tty-mode-reset-strings");
4511
4512 #ifndef MSDOS
4513 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4514 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4515 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4516 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4517 DEFSYM (Qtty_menu_select, "tty-menu-select");
4518 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4519 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
4520 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
4521 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
4522 #endif
4523 }