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