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