Fix bug #17585 with incorrect vertical motion when linum-mode is on.
[bpt/emacs.git] / src / term.c
CommitLineData
d284f58f 1/* Terminal control module for terminals described by TERMCAP
ba318903 2 Copyright (C) 1985-1987, 1993-1995, 1998, 2000-2014 Free Software
ab422c4d 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
bf6b4923 503#ifndef DOS_NT
3d798ba7
PE
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");
1dd40212 1425#undef CONDITIONAL_REASSIGN
01d8deb0 1426 }
a168702a
GM
1427
1428 return Qnil;
5c2c7893 1429}
361358ea 1430#endif /* not DOS_NT */
5c2c7893
JB
1431
1432\f
a168702a
GM
1433/***********************************************************************
1434 Character Display Information
1435 ***********************************************************************/
f57e2426 1436static void append_glyph (struct it *);
f57e2426
J
1437static void append_composite_glyph (struct it *);
1438static void produce_composite_glyph (struct it *);
fbceeba2 1439static void append_glyphless_glyph (struct it *, int, const char *);
653d4f43 1440static void produce_glyphless_glyph (struct it *, Lisp_Object);
a168702a
GM
1441
1442/* Append glyphs to IT's glyph_row. Called from produce_glyphs for
d2b4c17d
KH
1443 terminal frames if IT->glyph_row != NULL. IT->char_to_display is
1444 the character for which to produce glyphs; IT->face_id contains the
1445 character's face. Padding glyphs are appended if IT->c has a
1446 IT->pixel_width > 1. */
177c0ea7 1447
a168702a 1448static void
d3da34e0 1449append_glyph (struct it *it)
a168702a
GM
1450{
1451 struct glyph *glyph, *end;
1452 int i;
1453
a54e2c05 1454 eassert (it->glyph_row);
a168702a
GM
1455 glyph = (it->glyph_row->glyphs[it->area]
1456 + it->glyph_row->used[it->area]);
1457 end = it->glyph_row->glyphs[1 + it->area];
1458
5e65aec0
EZ
1459 /* If the glyph row is reversed, we need to prepend the glyph rather
1460 than append it. */
1461 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1462 {
1463 struct glyph *g;
1464 int move_by = it->pixel_width;
1465
1466 /* Make room for the new glyphs. */
1467 if (move_by > end - glyph) /* don't overstep end of this area */
1468 move_by = end - glyph;
1469 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1470 g[move_by] = *g;
1471 glyph = it->glyph_row->glyphs[it->area];
1472 end = glyph + move_by;
1473 }
1474
1475 /* BIDI Note: we put the glyphs of a "multi-pixel" character left to
1476 right, even in the REVERSED_P case, since (a) all of its u.ch are
1477 identical, and (b) the PADDING_P flag needs to be set for the
1478 leftmost one, because we write to the terminal left-to-right. */
177c0ea7
JB
1479 for (i = 0;
1480 i < it->pixel_width && glyph < end;
a168702a
GM
1481 ++i)
1482 {
1483 glyph->type = CHAR_GLYPH;
d13f3e2e 1484 glyph->pixel_width = 1;
d2b4c17d 1485 glyph->u.ch = it->char_to_display;
32de38e4
KH
1486 glyph->face_id = it->face_id;
1487 glyph->padding_p = i > 0;
a168702a
GM
1488 glyph->charpos = CHARPOS (it->position);
1489 glyph->object = it->object;
5e65aec0
EZ
1490 if (it->bidi_p)
1491 {
1492 glyph->resolved_level = it->bidi_it.resolved_level;
9443b3c7 1493 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1088b922 1494 emacs_abort ();
5e65aec0
EZ
1495 glyph->bidi_type = it->bidi_it.type;
1496 }
9443b3c7
EZ
1497 else
1498 {
1499 glyph->resolved_level = 0;
1500 glyph->bidi_type = UNKNOWN_BT;
1501 }
177c0ea7 1502
a168702a
GM
1503 ++it->glyph_row->used[it->area];
1504 ++glyph;
1505 }
1506}
1507
148ae00e
EZ
1508/* For external use. */
1509void
1510tty_append_glyph (struct it *it)
1511{
1512 append_glyph (it);
1513}
1514
1515
b50fe468
RS
1516/* Produce glyphs for the display element described by IT. *IT
1517 specifies what we want to produce a glyph for (character, image, ...),
1518 and where in the glyph matrix we currently are (glyph row and hpos).
1519 produce_glyphs fills in output fields of *IT with information such as the
1520 pixel width and height of a character, and maybe output actual glyphs at
e3670e00
EZ
1521 the same time if IT->glyph_row is non-null. For an overview, see
1522 the explanation in dispextern.h, before the definition of the
1523 display_element_type enumeration.
b50fe468
RS
1524
1525 produce_glyphs also stores the result of glyph width, ascent
1526 etc. computations in *IT.
1527
1528 IT->glyph_row may be null, in which case produce_glyphs does not
1529 actually fill in the glyphs. This is used in the move_* functions
1530 in xdisp.c for text width and height computations.
1531
1532 Callers usually don't call produce_glyphs directly;
1533 instead they use the macro PRODUCE_GLYPHS. */
a168702a 1534
177c0ea7 1535void
d3da34e0 1536produce_glyphs (struct it *it)
a168702a
GM
1537{
1538 /* If a hook is installed, let it do the work. */
4c12d738
KH
1539
1540 /* Nothing but characters are supported on terminal frames. */
a54e2c05 1541 eassert (it->what == IT_CHARACTER
c7cba11d 1542 || it->what == IT_COMPOSITION
a8815b00
EZ
1543 || it->what == IT_STRETCH
1544 || it->what == IT_GLYPHLESS);
177c0ea7 1545
6b61353c
KH
1546 if (it->what == IT_STRETCH)
1547 {
1548 produce_stretch_glyph (it);
1549 goto done;
1550 }
1551
4c12d738
KH
1552 if (it->what == IT_COMPOSITION)
1553 {
1554 produce_composite_glyph (it);
1555 goto done;
1556 }
a168702a 1557
b18fad6d
KH
1558 if (it->what == IT_GLYPHLESS)
1559 {
653d4f43 1560 produce_glyphless_glyph (it, Qnil);
b18fad6d
KH
1561 goto done;
1562 }
1563
d419e1d9 1564 if (it->char_to_display >= 040 && it->char_to_display < 0177)
a168702a
GM
1565 {
1566 it->pixel_width = it->nglyphs = 1;
1567 if (it->glyph_row)
1568 append_glyph (it);
1569 }
d419e1d9 1570 else if (it->char_to_display == '\n')
a168702a 1571 it->pixel_width = it->nglyphs = 0;
d419e1d9 1572 else if (it->char_to_display == '\t')
a168702a 1573 {
2efdbcdd 1574 int absolute_x = (it->current_x
a168702a 1575 + it->continuation_lines_width);
177c0ea7
JB
1576 int next_tab_x
1577 = (((1 + absolute_x + it->tab_width - 1)
a168702a
GM
1578 / it->tab_width)
1579 * it->tab_width);
1580 int nspaces;
1581
1582 /* If part of the TAB has been displayed on the previous line
1583 which is continued now, continuation_lines_width will have
1584 been incremented already by the part that fitted on the
1585 continued line. So, we will get the right number of spaces
1586 here. */
1587 nspaces = next_tab_x - absolute_x;
177c0ea7 1588
a168702a
GM
1589 if (it->glyph_row)
1590 {
1591 int n = nspaces;
177c0ea7 1592
d2b4c17d 1593 it->char_to_display = ' ';
a168702a 1594 it->pixel_width = it->len = 1;
177c0ea7 1595
a168702a
GM
1596 while (n--)
1597 append_glyph (it);
a168702a
GM
1598 }
1599
1600 it->pixel_width = nspaces;
1601 it->nglyphs = nspaces;
1602 }
d419e1d9 1603 else if (CHAR_BYTE8_P (it->char_to_display))
add44890 1604 {
d419e1d9
KH
1605 /* Coming here means that we must send the raw 8-bit byte as is
1606 to the terminal. Although there's no way to know how many
1607 columns it occupies on a screen, it is a good assumption that
1608 a single byte code has 1-column width. */
1609 it->pixel_width = it->nglyphs = 1;
1610 if (it->glyph_row)
1611 append_glyph (it);
add44890 1612 }
a168702a
GM
1613 else
1614 {
b18fad6d 1615 Lisp_Object charset_list = FRAME_TERMINAL (it->f)->charset_list;
177c0ea7 1616
b18fad6d
KH
1617 if (char_charset (it->char_to_display, charset_list, NULL))
1618 {
1619 it->pixel_width = CHAR_WIDTH (it->char_to_display);
1620 it->nglyphs = it->pixel_width;
1621 if (it->glyph_row)
1622 append_glyph (it);
1623 }
1624 else
1625 {
1626 Lisp_Object acronym = lookup_glyphless_char_display (-1, it);
1627
a54e2c05 1628 eassert (it->what == IT_GLYPHLESS);
653d4f43 1629 produce_glyphless_glyph (it, acronym);
b18fad6d 1630 }
a168702a
GM
1631 }
1632
6b61353c 1633 done:
177c0ea7 1634 /* Advance current_x by the pixel width as a convenience for
a168702a
GM
1635 the caller. */
1636 if (it->area == TEXT_AREA)
1637 it->current_x += it->pixel_width;
cfe8a05e
GM
1638 it->ascent = it->max_ascent = it->phys_ascent = it->max_phys_ascent = 0;
1639 it->descent = it->max_descent = it->phys_descent = it->max_phys_descent = 1;
a168702a
GM
1640}
1641
4c12d738
KH
1642/* Append glyphs to IT's glyph_row for the composition IT->cmp_id.
1643 Called from produce_composite_glyph for terminal frames if
1644 IT->glyph_row != NULL. IT->face_id contains the character's
1645 face. */
1646
1647static void
d3da34e0 1648append_composite_glyph (struct it *it)
4c12d738
KH
1649{
1650 struct glyph *glyph;
1651
a54e2c05 1652 eassert (it->glyph_row);
4c12d738
KH
1653 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1654 if (glyph < it->glyph_row->glyphs[1 + it->area])
1655 {
93d68d0c
EZ
1656 /* If the glyph row is reversed, we need to prepend the glyph
1657 rather than append it. */
1658 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1659 {
1660 struct glyph *g;
1661
1662 /* Make room for the new glyph. */
1663 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1664 g[1] = *g;
1665 glyph = it->glyph_row->glyphs[it->area];
1666 }
4c12d738
KH
1667 glyph->type = COMPOSITE_GLYPH;
1668 glyph->pixel_width = it->pixel_width;
75a10786
KH
1669 glyph->u.cmp.id = it->cmp_it.id;
1670 if (it->cmp_it.ch < 0)
1671 {
1672 glyph->u.cmp.automatic = 0;
1673 glyph->u.cmp.id = it->cmp_it.id;
1674 }
1675 else
1676 {
1677 glyph->u.cmp.automatic = 1;
1678 glyph->u.cmp.id = it->cmp_it.id;
4be9765d
KH
1679 glyph->slice.cmp.from = it->cmp_it.from;
1680 glyph->slice.cmp.to = it->cmp_it.to - 1;
75a10786
KH
1681 }
1682
4c12d738
KH
1683 glyph->face_id = it->face_id;
1684 glyph->padding_p = 0;
1685 glyph->charpos = CHARPOS (it->position);
1686 glyph->object = it->object;
93d68d0c
EZ
1687 if (it->bidi_p)
1688 {
1689 glyph->resolved_level = it->bidi_it.resolved_level;
1690 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1088b922 1691 emacs_abort ();
93d68d0c
EZ
1692 glyph->bidi_type = it->bidi_it.type;
1693 }
1694 else
1695 {
1696 glyph->resolved_level = 0;
1697 glyph->bidi_type = UNKNOWN_BT;
1698 }
4c12d738
KH
1699
1700 ++it->glyph_row->used[it->area];
1701 ++glyph;
1702 }
1703}
1704
1705
1706/* Produce a composite glyph for iterator IT. IT->cmp_id is the ID of
1707 the composition. We simply produces components of the composition
2b34df4e
JB
1708 assuming that the terminal has a capability to layout/render it
1709 correctly. */
4c12d738
KH
1710
1711static void
d3da34e0 1712produce_composite_glyph (struct it *it)
4c12d738 1713{
75a10786
KH
1714 if (it->cmp_it.ch < 0)
1715 {
1716 struct composition *cmp = composition_table[it->cmp_it.id];
1717
d0984aff 1718 it->pixel_width = cmp->width;
75a10786
KH
1719 }
1720 else
1721 {
1722 Lisp_Object gstring = composition_gstring_from_id (it->cmp_it.id);
4c12d738 1723
75a10786
KH
1724 it->pixel_width = composition_gstring_width (gstring, it->cmp_it.from,
1725 it->cmp_it.to, NULL);
1726 }
1727 it->nglyphs = 1;
4c12d738
KH
1728 if (it->glyph_row)
1729 append_composite_glyph (it);
1730}
1731
1732
b18fad6d 1733/* Append a glyph for a glyphless character to IT->glyph_row. FACE_ID
0eb025fb
EZ
1734 is a face ID to be used for the glyph. What is actually appended
1735 are glyphs of type CHAR_GLYPH whose characters are in STR (which
1736 comes from it->nglyphs bytes). */
b18fad6d
KH
1737
1738static void
fbceeba2 1739append_glyphless_glyph (struct it *it, int face_id, const char *str)
b18fad6d
KH
1740{
1741 struct glyph *glyph, *end;
b18fad6d
KH
1742 int i;
1743
a54e2c05 1744 eassert (it->glyph_row);
b18fad6d
KH
1745 glyph = it->glyph_row->glyphs[it->area] + it->glyph_row->used[it->area];
1746 end = it->glyph_row->glyphs[1 + it->area];
1747
1748 /* If the glyph row is reversed, we need to prepend the glyph rather
1749 than append it. */
1750 if (it->glyph_row->reversed_p && it->area == TEXT_AREA)
1751 {
1752 struct glyph *g;
1753 int move_by = it->pixel_width;
1754
1755 /* Make room for the new glyphs. */
1756 if (move_by > end - glyph) /* don't overstep end of this area */
1757 move_by = end - glyph;
1758 for (g = glyph - 1; g >= it->glyph_row->glyphs[it->area]; g--)
1759 g[move_by] = *g;
1760 glyph = it->glyph_row->glyphs[it->area];
1761 end = glyph + move_by;
1762 }
1763
1764 if (glyph >= end)
1765 return;
1766 glyph->type = CHAR_GLYPH;
1767 glyph->pixel_width = 1;
1768 glyph->face_id = face_id;
1769 glyph->padding_p = 0;
1770 glyph->charpos = CHARPOS (it->position);
1771 glyph->object = it->object;
1772 if (it->bidi_p)
1773 {
1774 glyph->resolved_level = it->bidi_it.resolved_level;
1775 if ((it->bidi_it.type & 7) != it->bidi_it.type)
1088b922 1776 emacs_abort ();
b18fad6d
KH
1777 glyph->bidi_type = it->bidi_it.type;
1778 }
1779 else
1780 {
1781 glyph->resolved_level = 0;
1782 glyph->bidi_type = UNKNOWN_BT;
1783 }
1784
1785 /* BIDI Note: we put the glyphs of characters left to right, even in
1786 the REVERSED_P case because we write to the terminal
1787 left-to-right. */
1788 for (i = 0; i < it->nglyphs && glyph < end; ++i)
1789 {
1790 if (i > 0)
1791 glyph[0] = glyph[-1];
1792 glyph->u.ch = str[i];
1793 ++it->glyph_row->used[it->area];
1794 ++glyph;
1795 }
1796}
1797
b18fad6d
KH
1798/* Produce glyphs for a glyphless character for iterator IT.
1799 IT->glyphless_method specifies which method to use for displaying
1800 the character. See the description of enum
0eb025fb 1801 glyphless_display_method in dispextern.h for the details.
b18fad6d 1802
653d4f43 1803 ACRONYM, if non-nil, is an acronym string for the character.
b18fad6d
KH
1804
1805 The glyphs actually produced are of type CHAR_GLYPH. */
1806
1807static void
653d4f43 1808produce_glyphless_glyph (struct it *it, Lisp_Object acronym)
b18fad6d 1809{
77394d40 1810 int len, face_id = merge_glyphless_glyph_face (it);
80f2e268 1811 char buf[sizeof "\\x" + max (6, (sizeof it->c * CHAR_BIT + 3) / 4)];
fbceeba2 1812 char const *str = " ";
b18fad6d 1813
b18fad6d
KH
1814 if (it->glyphless_method == GLYPHLESS_DISPLAY_THIN_SPACE)
1815 {
0eb025fb
EZ
1816 /* As there's no way to produce a thin space, we produce a space
1817 of canonical width. */
b18fad6d
KH
1818 len = 1;
1819 }
1820 else if (it->glyphless_method == GLYPHLESS_DISPLAY_EMPTY_BOX)
1821 {
1822 len = CHAR_WIDTH (it->c);
1823 if (len == 0)
1824 len = 1;
0eb025fb 1825 else if (len > 4)
b18fad6d 1826 len = 4;
99027bdd 1827 len = sprintf (buf, "[%.*s]", len, str);
0eb025fb 1828 str = buf;
b18fad6d
KH
1829 }
1830 else
1831 {
1832 if (it->glyphless_method == GLYPHLESS_DISPLAY_ACRONYM)
1833 {
b18fad6d
KH
1834 if (! STRINGP (acronym) && CHAR_TABLE_P (Vglyphless_char_display))
1835 acronym = CHAR_TABLE_REF (Vglyphless_char_display, it->c);
16a43933
CY
1836 if (CONSP (acronym))
1837 acronym = XCDR (acronym);
b18fad6d 1838 buf[0] = '[';
51b59d79 1839 str = STRINGP (acronym) ? SSDATA (acronym) : "";
b18fad6d
KH
1840 for (len = 0; len < 6 && str[len] && ASCII_BYTE_P (str[len]); len++)
1841 buf[1 + len] = str[len];
1842 buf[1 + len] = ']';
1843 len += 2;
1844 }
1845 else
1846 {
a54e2c05 1847 eassert (it->glyphless_method == GLYPHLESS_DISPLAY_HEX_CODE);
7c2d713b
EZ
1848 len = (it->c < 0x10000 ? sprintf (buf, "\\u%04X", it->c)
1849 : it->c <= MAX_UNICODE_CHAR ? sprintf (buf, "\\U%06X", it->c)
1850 : sprintf (buf, "\\x%06X", it->c));
b18fad6d
KH
1851 }
1852 str = buf;
1853 }
1854
1855 it->pixel_width = len;
1856 it->nglyphs = len;
d284567f 1857 if (it->glyph_row)
b18fad6d
KH
1858 append_glyphless_glyph (it, face_id, str);
1859}
1860
a168702a
GM
1861\f
1862/***********************************************************************
1863 Faces
1864 ***********************************************************************/
1865
4e6ba4a4
GM
1866/* Value is non-zero if attribute ATTR may be used. ATTR should be
1867 one of the enumerators from enum no_color_bit, or a bit set built
1868 from them. Some display attributes may not be used together with
1869 color; the termcap capability `NC' specifies which ones. */
1870
fca177d4
KL
1871#define MAY_USE_WITH_COLORS_P(tty, ATTR) \
1872 (tty->TN_max_colors > 0 \
1873 ? (tty->TN_no_color_video & (ATTR)) == 0 \
1874 : 1)
a168702a 1875
072d84a6
RS
1876/* Turn appearances of face FACE_ID on tty frame F on.
1877 FACE_ID is a realized face ID number, in the face cache. */
a168702a
GM
1878
1879static void
d3da34e0 1880turn_on_face (struct frame *f, int face_id)
a168702a
GM
1881{
1882 struct face *face = FACE_FROM_ID (f, face_id);
798aef02
PE
1883 unsigned long fg = face->foreground;
1884 unsigned long bg = face->background;
28d7d09f 1885 struct tty_display_info *tty = FRAME_TTY (f);
a168702a 1886
798aef02
PE
1887 /* Use reverse video if the face specifies that.
1888 Do this first because TS_end_standout_mode may be the same
86a7d192 1889 as TS_exit_attribute_mode, which turns all appearances off. */
798aef02
PE
1890 if (MAY_USE_WITH_COLORS_P (tty, NC_REVERSE)
1891 && (inverse_video
1892 ? fg == FACE_TTY_DEFAULT_FG_COLOR || bg == FACE_TTY_DEFAULT_BG_COLOR
1893 : fg == FACE_TTY_DEFAULT_BG_COLOR || bg == FACE_TTY_DEFAULT_FG_COLOR))
1894 tty_toggle_highlight (tty);
a168702a 1895
4189ed40
CY
1896 if (face->tty_bold_p && MAY_USE_WITH_COLORS_P (tty, NC_BOLD))
1897 OUTPUT1_IF (tty, tty->TS_enter_bold_mode);
1898
cd4eb164
CY
1899 if (face->tty_italic_p && MAY_USE_WITH_COLORS_P (tty, NC_ITALIC))
1900 {
1901 if (tty->TS_enter_italic_mode)
1902 OUTPUT1 (tty, tty->TS_enter_italic_mode);
1903 else
1904 /* Italics mode is unavailable on many terminals. In that
1905 case, map slant to dimmed text; we want italic text to
1906 appear different and dimming is not otherwise used. */
1907 OUTPUT1 (tty, tty->TS_enter_dim_mode);
1908 }
a168702a 1909
fca177d4
KL
1910 if (face->tty_underline_p && MAY_USE_WITH_COLORS_P (tty, NC_UNDERLINE))
1911 OUTPUT1_IF (tty, tty->TS_enter_underline_mode);
a168702a 1912
fca177d4 1913 if (tty->TN_max_colors > 0)
a168702a 1914 {
fbceeba2
PE
1915 const char *ts;
1916 char *p;
177c0ea7 1917
fbf34973 1918 ts = tty->standout_mode ? tty->TS_set_background : tty->TS_set_foreground;
798aef02 1919 if (face_tty_specified_color (fg) && ts)
a168702a 1920 {
653d4f43 1921 p = tparam (ts, NULL, 0, fg, 0, 0, 0);
6548cf00 1922 OUTPUT (tty, p);
a168702a
GM
1923 xfree (p);
1924 }
1925
fbf34973 1926 ts = tty->standout_mode ? tty->TS_set_foreground : tty->TS_set_background;
798aef02 1927 if (face_tty_specified_color (bg) && ts)
a168702a 1928 {
653d4f43 1929 p = tparam (ts, NULL, 0, bg, 0, 0, 0);
6548cf00 1930 OUTPUT (tty, p);
a168702a
GM
1931 xfree (p);
1932 }
1933 }
1934}
177c0ea7 1935
a168702a
GM
1936
1937/* Turn off appearances of face FACE_ID on tty frame F. */
1938
1939static void
d3da34e0 1940turn_off_face (struct frame *f, int face_id)
a168702a
GM
1941{
1942 struct face *face = FACE_FROM_ID (f, face_id);
28d7d09f 1943 struct tty_display_info *tty = FRAME_TTY (f);
a168702a 1944
a54e2c05 1945 eassert (face != NULL);
a168702a 1946
fca177d4 1947 if (tty->TS_exit_attribute_mode)
a168702a
GM
1948 {
1949 /* Capability "me" will turn off appearance modes double-bright,
1950 half-bright, reverse-video, standout, underline. It may or
1951 may not turn off alt-char-mode. */
1952 if (face->tty_bold_p
cd4eb164 1953 || face->tty_italic_p
a168702a 1954 || face->tty_reverse_p
a168702a 1955 || face->tty_underline_p)
65aa5e85 1956 {
fca177d4
KL
1957 OUTPUT1_IF (tty, tty->TS_exit_attribute_mode);
1958 if (strcmp (tty->TS_exit_attribute_mode, tty->TS_end_standout_mode) == 0)
1959 tty->standout_mode = 0;
65aa5e85 1960 }
a168702a
GM
1961 }
1962 else
1963 {
1964 /* If we don't have "me" we can only have those appearances
1965 that have exit sequences defined. */
54800acb 1966 if (face->tty_underline_p)
fca177d4 1967 OUTPUT_IF (tty, tty->TS_exit_underline_mode);
a168702a
GM
1968 }
1969
1970 /* Switch back to default colors. */
fca177d4 1971 if (tty->TN_max_colors > 0
f9d2fdc4
EZ
1972 && ((face->foreground != FACE_TTY_DEFAULT_COLOR
1973 && face->foreground != FACE_TTY_DEFAULT_FG_COLOR)
1974 || (face->background != FACE_TTY_DEFAULT_COLOR
1975 && face->background != FACE_TTY_DEFAULT_BG_COLOR)))
fca177d4 1976 OUTPUT1_IF (tty, tty->TS_orig_pair);
a168702a 1977}
177c0ea7
JB
1978
1979
653d4f43 1980/* Return true if the terminal on frame F supports all of the
798aef02 1981 capabilities in CAPS simultaneously. */
b63a55ac 1982
653d4f43 1983bool
798aef02 1984tty_capable_p (struct tty_display_info *tty, unsigned int caps)
b63a55ac 1985{
fca177d4
KL
1986#define TTY_CAPABLE_P_TRY(tty, cap, TS, NC_bit) \
1987 if ((caps & (cap)) && (!(TS) || !MAY_USE_WITH_COLORS_P(tty, NC_bit))) \
b63a55ac
MB
1988 return 0;
1989
fca177d4
KL
1990 TTY_CAPABLE_P_TRY (tty, TTY_CAP_INVERSE, tty->TS_standout_mode, NC_REVERSE);
1991 TTY_CAPABLE_P_TRY (tty, TTY_CAP_UNDERLINE, tty->TS_enter_underline_mode, NC_UNDERLINE);
1992 TTY_CAPABLE_P_TRY (tty, TTY_CAP_BOLD, tty->TS_enter_bold_mode, NC_BOLD);
1993 TTY_CAPABLE_P_TRY (tty, TTY_CAP_DIM, tty->TS_enter_dim_mode, NC_DIM);
cd4eb164 1994 TTY_CAPABLE_P_TRY (tty, TTY_CAP_ITALIC, tty->TS_enter_italic_mode, NC_ITALIC);
b63a55ac
MB
1995
1996 /* We can do it! */
1997 return 1;
1998}
1999
a168702a
GM
2000/* Return non-zero if the terminal is capable to display colors. */
2001
2002DEFUN ("tty-display-color-p", Ftty_display_color_p, Stty_display_color_p,
981e4297 2003 0, 1, 0,
6ed8eeff
KL
2004 doc: /* Return non-nil if the tty device TERMINAL can display colors.
2005
401e9e57
CY
2006TERMINAL can be a terminal object, a frame, or nil (meaning the
2007selected frame's terminal). This function always returns nil if
c6bf3022 2008TERMINAL does not refer to a text terminal. */)
5842a27b 2009 (Lisp_Object terminal)
a168702a 2010{
717a00ef 2011 struct terminal *t = get_tty_terminal (terminal, 0);
6ed8eeff 2012 if (!t)
428a555e 2013 return Qnil;
3224dac1 2014 else
6ed8eeff 2015 return t->display_info.tty->TN_max_colors > 0 ? Qt : Qnil;
a168702a
GM
2016}
2017
bfa62f96
EZ
2018/* Return the number of supported colors. */
2019DEFUN ("tty-display-color-cells", Ftty_display_color_cells,
2020 Stty_display_color_cells, 0, 1, 0,
6ed8eeff
KL
2021 doc: /* Return the number of colors supported by the tty device TERMINAL.
2022
401e9e57
CY
2023TERMINAL can be a terminal object, a frame, or nil (meaning the
2024selected frame's terminal). This function always returns 0 if
c6bf3022 2025TERMINAL does not refer to a text terminal. */)
5842a27b 2026 (Lisp_Object terminal)
bfa62f96 2027{
717a00ef 2028 struct terminal *t = get_tty_terminal (terminal, 0);
6ed8eeff 2029 if (!t)
8c8d5f35 2030 return make_number (0);
3224dac1 2031 else
6ed8eeff 2032 return make_number (t->display_info.tty->TN_max_colors);
bfa62f96
EZ
2033}
2034
84704c5c 2035#ifndef DOS_NT
a168702a 2036
5205ee62
GM
2037/* Declare here rather than in the function, as in the rest of Emacs,
2038 to work around an HPUX compiler bug (?). See
57407fb4 2039 http://lists.gnu.org/archive/html/emacs-devel/2007-08/msg00410.html */
5205ee62
GM
2040static int default_max_colors;
2041static int default_max_pairs;
2042static int default_no_color_video;
2043static char *default_orig_pair;
2044static char *default_set_foreground;
2045static char *default_set_background;
fcf8ff2e 2046
ace28297
EZ
2047/* Save or restore the default color-related capabilities of this
2048 terminal. */
2049static void
653d4f43 2050tty_default_color_capabilities (struct tty_display_info *tty, bool save)
ace28297 2051{
ace28297
EZ
2052
2053 if (save)
2054 {
8268febf
PE
2055 dupstring (&default_orig_pair, tty->TS_orig_pair);
2056 dupstring (&default_set_foreground, tty->TS_set_foreground);
2057 dupstring (&default_set_background, tty->TS_set_background);
fca177d4
KL
2058 default_max_colors = tty->TN_max_colors;
2059 default_max_pairs = tty->TN_max_pairs;
2060 default_no_color_video = tty->TN_no_color_video;
ace28297
EZ
2061 }
2062 else
2063 {
fca177d4
KL
2064 tty->TS_orig_pair = default_orig_pair;
2065 tty->TS_set_foreground = default_set_foreground;
2066 tty->TS_set_background = default_set_background;
2067 tty->TN_max_colors = default_max_colors;
2068 tty->TN_max_pairs = default_max_pairs;
2069 tty->TN_no_color_video = default_no_color_video;
ace28297
EZ
2070 }
2071}
2072
2073/* Setup one of the standard tty color schemes according to MODE.
2074 MODE's value is generally the number of colors which we want to
2075 support; zero means set up for the default capabilities, the ones
a4c6993d 2076 we saw at init_tty time; -1 means turn off color support. */
ed8dad6b 2077static void
28d7d09f 2078tty_setup_colors (struct tty_display_info *tty, int mode)
ace28297 2079{
6b61353c
KH
2080 /* Canonicalize all negative values of MODE. */
2081 if (mode < -1)
2082 mode = -1;
2083
ace28297
EZ
2084 switch (mode)
2085 {
2086 case -1: /* no colors at all */
fca177d4
KL
2087 tty->TN_max_colors = 0;
2088 tty->TN_max_pairs = 0;
2089 tty->TN_no_color_video = 0;
2090 tty->TS_set_foreground = tty->TS_set_background = tty->TS_orig_pair = NULL;
ace28297
EZ
2091 break;
2092 case 0: /* default colors, if any */
2093 default:
fca177d4 2094 tty_default_color_capabilities (tty, 0);
ace28297
EZ
2095 break;
2096 case 8: /* 8 standard ANSI colors */
fca177d4 2097 tty->TS_orig_pair = "\033[0m";
ace28297 2098#ifdef TERMINFO
fca177d4
KL
2099 tty->TS_set_foreground = "\033[3%p1%dm";
2100 tty->TS_set_background = "\033[4%p1%dm";
ace28297 2101#else
fca177d4
KL
2102 tty->TS_set_foreground = "\033[3%dm";
2103 tty->TS_set_background = "\033[4%dm";
ace28297 2104#endif
fca177d4
KL
2105 tty->TN_max_colors = 8;
2106 tty->TN_max_pairs = 64;
2107 tty->TN_no_color_video = 0;
ace28297
EZ
2108 break;
2109 }
2110}
2111
2112void
d3da34e0 2113set_tty_color_mode (struct tty_display_info *tty, struct frame *f)
ace28297 2114{
ce5b453a 2115 Lisp_Object tem, val;
9b2cd403
SM
2116 Lisp_Object color_mode;
2117 int mode;
9b2cd403
SM
2118 Lisp_Object tty_color_mode_alist
2119 = Fintern_soft (build_string ("tty-color-mode-alist"), Qnil);
ace28297 2120
e69b0960 2121 tem = assq_no_quit (Qtty_color_mode, f->param_alist);
9b2cd403 2122 val = CONSP (tem) ? XCDR (tem) : Qnil;
ace28297 2123
6b61353c 2124 if (INTEGERP (val))
ace28297 2125 color_mode = val;
ce5b453a 2126 else if (SYMBOLP (tty_color_mode_alist))
ace28297 2127 {
ce5b453a 2128 tem = Fassq (val, Fsymbol_value (tty_color_mode_alist));
9b2cd403 2129 color_mode = CONSP (tem) ? XCDR (tem) : Qnil;
ace28297 2130 }
ce5b453a
SM
2131 else
2132 color_mode = Qnil;
6b61353c 2133
d311d28c 2134 mode = TYPE_RANGED_INTEGERP (int, color_mode) ? XINT (color_mode) : 0;
ace28297 2135
9b2cd403 2136 if (mode != tty->previous_color_mode)
ace28297 2137 {
9b2cd403
SM
2138 tty->previous_color_mode = mode;
2139 tty_setup_colors (tty , mode);
2140 /* This recomputes all the faces given the new color definitions. */
6cd7a139 2141 safe_call (1, intern ("tty-set-up-initial-frame-faces"));
ace28297
EZ
2142 }
2143}
2144
84704c5c 2145#endif /* !DOS_NT */
a168702a
GM
2146
2147\f
28d440ab 2148
6ed8eeff 2149/* Return the tty display object specified by TERMINAL. */
b6660415 2150
64520e5c 2151static struct terminal *
653d4f43 2152get_tty_terminal (Lisp_Object terminal, bool throw)
b6660415 2153{
717a00ef 2154 struct terminal *t = get_terminal (terminal, throw);
62af879c 2155
84704c5c 2156 if (t && t->type != output_termcap && t->type != output_msdos_raw)
717a00ef
KL
2157 {
2158 if (throw)
2159 error ("Device %d is not a termcap terminal device", t->id);
2160 else
2161 return NULL;
2162 }
b6660415 2163
6ed8eeff 2164 return t;
b6660415
KL
2165}
2166
ab797f65
KL
2167/* Return an active termcap device that uses the tty device with the
2168 given name.
b6660415 2169
7e59217d 2170 This function ignores suspended devices.
da8e1115
KL
2171
2172 Returns NULL if the named terminal device is not opened. */
f4d953fc 2173
6ed8eeff 2174struct terminal *
8ea90aa3 2175get_named_tty (const char *name)
28d440ab 2176{
6ed8eeff
KL
2177 struct terminal *t;
2178
9c253307 2179 eassert (name);
ab797f65
KL
2180
2181 for (t = terminal_list; t; t = t->next_terminal)
2182 {
5cc67f65 2183 if ((t->type == output_termcap || t->type == output_msdos_raw)
ab797f65
KL
2184 && !strcmp (t->display_info.tty->name, name)
2185 && TERMINAL_ACTIVE_P (t))
2186 return t;
2187 }
28d440ab
KL
2188
2189 return 0;
2190}
2191
2192\f
a7ca3326 2193DEFUN ("tty-type", Ftty_type, Stty_type, 0, 1, 0,
6ed8eeff 2194 doc: /* Return the type of the tty device that TERMINAL uses.
ab797f65 2195Returns nil if TERMINAL is not on a tty device.
a3fbb897 2196
401e9e57
CY
2197TERMINAL can be a terminal object, a frame, or nil (meaning the
2198selected frame's terminal). */)
5842a27b 2199 (Lisp_Object terminal)
b6660415 2200{
6ed8eeff 2201 struct terminal *t = get_terminal (terminal, 1);
819b8f00 2202
84704c5c 2203 if (t->type != output_termcap && t->type != output_msdos_raw)
ab797f65
KL
2204 return Qnil;
2205
6ed8eeff
KL
2206 if (t->display_info.tty->type)
2207 return build_string (t->display_info.tty->type);
819b8f00
KL
2208 else
2209 return Qnil;
2210}
2211
6ed8eeff 2212DEFUN ("controlling-tty-p", Fcontrolling_tty_p, Scontrolling_tty_p, 0, 1, 0,
84704c5c 2213 doc: /* Return non-nil if TERMINAL is the controlling tty of the Emacs process.
a3fbb897 2214
401e9e57
CY
2215TERMINAL can be a terminal object, a frame, or nil (meaning the
2216selected frame's terminal). This function always returns nil if
2217TERMINAL is not on a tty device. */)
5842a27b 2218 (Lisp_Object terminal)
4a933ef8 2219{
6ed8eeff 2220 struct terminal *t = get_terminal (terminal, 1);
4a933ef8 2221
84704c5c
EZ
2222 if ((t->type != output_termcap && t->type != output_msdos_raw)
2223 || strcmp (t->display_info.tty->name, DEV_TTY) != 0)
4a933ef8
KL
2224 return Qnil;
2225 else
2226 return Qt;
2227}
2228
a3fbb897 2229DEFUN ("tty-no-underline", Ftty_no_underline, Stty_no_underline, 0, 1, 0,
6ed8eeff 2230 doc: /* Declare that the tty used by TERMINAL does not handle underlining.
a3fbb897
KL
2231This is used to override the terminfo data, for certain terminals that
2232do not really do underlining, but say that they do. This function has
6ed8eeff 2233no effect if used on a non-tty terminal.
a3fbb897 2234
401e9e57
CY
2235TERMINAL can be a terminal object, a frame or nil (meaning the
2236selected frame's terminal). This function always returns nil if
c6bf3022 2237TERMINAL does not refer to a text terminal. */)
5842a27b 2238 (Lisp_Object terminal)
a3fbb897 2239{
6ed8eeff 2240 struct terminal *t = get_terminal (terminal, 1);
a3fbb897 2241
6ed8eeff
KL
2242 if (t->type == output_termcap)
2243 t->display_info.tty->TS_enter_underline_mode = 0;
a3fbb897
KL
2244 return Qnil;
2245}
2246
c6bf3022
CY
2247DEFUN ("tty-top-frame", Ftty_top_frame, Stty_top_frame, 0, 1, 0,
2248 doc: /* Return the topmost terminal frame on TERMINAL.
2249TERMINAL can be a terminal object, a frame or nil (meaning the
2250selected frame's terminal). This function returns nil if TERMINAL
2251does not refer to a text terminal. Otherwise, it returns the
2252top-most frame on the text terminal. */)
2253 (Lisp_Object terminal)
2254{
2255 struct terminal *t = get_terminal (terminal, 1);
2256
2257 if (t->type == output_termcap)
2258 return t->display_info.tty->top_frame;
2259 return Qnil;
2260}
2261
ed8dad6b
KL
2262\f
2263
2264DEFUN ("suspend-tty", Fsuspend_tty, Ssuspend_tty, 0, 1, 0,
2265 doc: /* Suspend the terminal device TTY.
2266
2267The device is restored to its default state, and Emacs ceases all
2268access to the tty device. Frames that use the device are not deleted,
2269but input is not read from them and if they change, their display is
2270not updated.
2271
401e9e57
CY
2272TTY may be a terminal object, a frame, or nil for the terminal device
2273of the currently selected frame.
ed8dad6b 2274
e4019195 2275This function runs `suspend-tty-functions' after suspending the
ed8dad6b
KL
2276device. The functions are run with one arg, the id of the suspended
2277terminal device.
2278
2279`suspend-tty' does nothing if it is called on a device that is already
2280suspended.
2281
2282A suspended tty may be resumed by calling `resume-tty' on it. */)
5842a27b 2283 (Lisp_Object tty)
ed8dad6b 2284{
717a00ef 2285 struct terminal *t = get_tty_terminal (tty, 1);
ed8dad6b 2286 FILE *f;
f4d953fc 2287
6ed8eeff 2288 if (!t)
ed8dad6b
KL
2289 error ("Unknown tty device");
2290
6ed8eeff 2291 f = t->display_info.tty->input;
f4d953fc 2292
ed8dad6b
KL
2293 if (f)
2294 {
23d4cba5
DN
2295 /* First run `suspend-tty-functions' and then clean up the tty
2296 state because `suspend-tty-functions' might need to change
2297 the tty state. */
dee091a3
JD
2298 Lisp_Object args[2];
2299 args[0] = intern ("suspend-tty-functions");
2300 XSETTERMINAL (args[1], t);
2301 Frun_hook_with_args (2, args);
23d4cba5 2302
6ed8eeff 2303 reset_sys_modes (t->display_info.tty);
ed8dad6b 2304 delete_keyboard_wait_descriptor (fileno (f));
f4d953fc 2305
84704c5c 2306#ifndef MSDOS
ed8dad6b 2307 fclose (f);
6ed8eeff
KL
2308 if (f != t->display_info.tty->output)
2309 fclose (t->display_info.tty->output);
84704c5c 2310#endif
f4d953fc 2311
6ed8eeff
KL
2312 t->display_info.tty->input = 0;
2313 t->display_info.tty->output = 0;
ed8dad6b 2314
6ed8eeff 2315 if (FRAMEP (t->display_info.tty->top_frame))
edfa7fa0 2316 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 0);
f4d953fc 2317
ed8dad6b
KL
2318 }
2319
4a665758
KL
2320 /* Clear display hooks to prevent further output. */
2321 clear_tty_hooks (t);
2322
ed8dad6b
KL
2323 return Qnil;
2324}
2325
2326DEFUN ("resume-tty", Fresume_tty, Sresume_tty, 0, 1, 0,
2327 doc: /* Resume the previously suspended terminal device TTY.
2328The terminal is opened and reinitialized. Frames that are on the
6ed8eeff 2329suspended terminal are revived.
ed8dad6b 2330
6ed8eeff
KL
2331It is an error to resume a terminal while another terminal is active
2332on the same device.
ed8dad6b 2333
e4019195 2334This function runs `resume-tty-functions' after resuming the terminal.
6ed8eeff 2335The functions are run with one arg, the id of the resumed terminal
ed8dad6b
KL
2336device.
2337
2338`resume-tty' does nothing if it is called on a device that is not
2339suspended.
2340
401e9e57
CY
2341TTY may be a terminal object, a frame, or nil (meaning the selected
2342frame's terminal). */)
5842a27b 2343 (Lisp_Object tty)
ed8dad6b 2344{
717a00ef 2345 struct terminal *t = get_tty_terminal (tty, 1);
ed8dad6b
KL
2346 int fd;
2347
6ed8eeff 2348 if (!t)
ed8dad6b
KL
2349 error ("Unknown tty device");
2350
6ed8eeff 2351 if (!t->display_info.tty->input)
ed8dad6b 2352 {
6ed8eeff 2353 if (get_named_tty (t->display_info.tty->name))
ed8dad6b
KL
2354 error ("Cannot resume display while another display is active on the same device");
2355
84704c5c
EZ
2356#ifdef MSDOS
2357 t->display_info.tty->output = stdout;
2358 t->display_info.tty->input = stdin;
2359#else /* !MSDOS */
6ed8eeff 2360 fd = emacs_open (t->display_info.tty->name, O_RDWR | O_NOCTTY, 0);
ef30e638
PE
2361 t->display_info.tty->input = t->display_info.tty->output
2362 = fd < 0 ? 0 : fdopen (fd, "w+");
ed8dad6b 2363
ef30e638
PE
2364 if (! t->display_info.tty->input)
2365 {
2366 int open_errno = errno;
2367 emacs_close (fd);
2368 report_file_errno ("Cannot reopen tty device",
2369 build_string (t->display_info.tty->name),
2370 open_errno);
2371 }
ed8dad6b 2372
b8956427 2373 if (!O_IGNORE_CTTY && strcmp (t->display_info.tty->name, DEV_TTY) != 0)
59b3194c 2374 dissociate_if_controlling_tty (fd);
84704c5c 2375#endif
78048085 2376
ed8dad6b
KL
2377 add_keyboard_wait_descriptor (fd);
2378
6ed8eeff 2379 if (FRAMEP (t->display_info.tty->top_frame))
db878925
DN
2380 {
2381 struct frame *f = XFRAME (t->display_info.tty->top_frame);
2382 int width, height;
2383 int old_height = FRAME_COLS (f);
2384 int old_width = FRAME_LINES (f);
2385
2386 /* Check if terminal/window size has changed while the frame
2387 was suspended. */
2388 get_tty_size (fileno (t->display_info.tty->input), &width, &height);
2389 if (width != old_width || height != old_height)
880e6158 2390 change_frame_size (f, width, height, 0, 0, 0, 0);
edfa7fa0 2391 SET_FRAME_VISIBLE (XFRAME (t->display_info.tty->top_frame), 1);
db878925 2392 }
ed8dad6b 2393
04f2d78b 2394 set_tty_hooks (t);
6ed8eeff 2395 init_sys_modes (t->display_info.tty);
ed8dad6b 2396
dee091a3
JD
2397 {
2398 /* Run `resume-tty-functions'. */
2399 Lisp_Object args[2];
2400 args[0] = intern ("resume-tty-functions");
2401 XSETTERMINAL (args[1], t);
2402 Frun_hook_with_args (2, args);
2403 }
ed8dad6b
KL
2404 }
2405
4a665758
KL
2406 set_tty_hooks (t);
2407
ed8dad6b
KL
2408 return Qnil;
2409}
a3fbb897 2410
819b8f00 2411\f
e882229c
NR
2412/***********************************************************************
2413 Mouse
2414 ***********************************************************************/
2415
7e5a23bd 2416#ifdef HAVE_GPM
64520e5c
PE
2417
2418#ifndef HAVE_WINDOW_SYSTEM
5faa03ba
RS
2419void
2420term_mouse_moveto (int x, int y)
94da14a0 2421{
1ec5dc77 2422 /* TODO: how to set mouse position?
94da14a0
NR
2423 const char *name;
2424 int fd;
2425 name = (const char *) ttyname (0);
406af475 2426 fd = emacs_open (name, O_WRONLY, 0);
80fb2ce0 2427 SOME_FUNCTION (x, y, fd);
bacba3c2 2428 emacs_close (fd);
94da14a0 2429 last_mouse_x = x;
80fb2ce0 2430 last_mouse_y = y; */
94da14a0 2431}
64520e5c 2432#endif /* HAVE_WINDOW_SYSTEM */
94da14a0 2433
cf482c50
EZ
2434/* Implementation of draw_row_with_mouse_face for TTY/GPM. */
2435void
2436tty_draw_row_with_mouse_face (struct window *w, struct glyph_row *row,
2437 int start_hpos, int end_hpos,
2438 enum draw_glyphs_face draw)
e882229c 2439{
cf482c50
EZ
2440 int nglyphs = end_hpos - start_hpos;
2441 struct frame *f = XFRAME (WINDOW_FRAME (w));
7be1c21a 2442 struct tty_display_info *tty = FRAME_TTY (f);
cf482c50
EZ
2443 int face_id = tty->mouse_highlight.mouse_face_face_id;
2444 int save_x, save_y, pos_x, pos_y;
7be1c21a 2445
cf482c50
EZ
2446 if (end_hpos >= row->used[TEXT_AREA])
2447 nglyphs = row->used[TEXT_AREA] - start_hpos;
e882229c 2448
cf482c50
EZ
2449 pos_y = row->y + WINDOW_TOP_EDGE_Y (w);
2450 pos_x = row->used[LEFT_MARGIN_AREA] + start_hpos + WINDOW_LEFT_EDGE_X (w);
e882229c 2451
cf482c50
EZ
2452 /* Save current cursor co-ordinates. */
2453 save_y = curY (tty);
2454 save_x = curX (tty);
2455 cursor_to (f, pos_y, pos_x);
e882229c 2456
cf482c50
EZ
2457 if (draw == DRAW_MOUSE_FACE)
2458 tty_write_glyphs_with_face (f, row->glyphs[TEXT_AREA] + start_hpos,
2459 nglyphs, face_id);
2460 else if (draw == DRAW_NORMAL_TEXT)
2461 write_glyphs (f, row->glyphs[TEXT_AREA] + start_hpos, nglyphs);
e882229c 2462
cf482c50 2463 cursor_to (f, save_y, save_x);
e882229c
NR
2464}
2465
653d4f43 2466static bool
a10c8269 2467term_mouse_movement (struct frame *frame, Gpm_Event *event)
e882229c
NR
2468{
2469 /* Has the mouse moved off the glyph it was on at the last sighting? */
2470 if (event->x != last_mouse_x || event->y != last_mouse_y)
2471 {
2472 frame->mouse_moved = 1;
cf482c50 2473 note_mouse_highlight (frame, event->x, event->y);
e882229c
NR
2474 /* Remember which glyph we're now on. */
2475 last_mouse_x = event->x;
2476 last_mouse_y = event->y;
2477 return 1;
2478 }
2479 return 0;
2480}
2481
d35af63c
PE
2482/* Return the Time that corresponds to T. Wrap around on overflow. */
2483static Time
2484timeval_to_Time (struct timeval const *t)
2485{
2486 Time s_1000, ms;
2487
2488 s_1000 = t->tv_sec;
2489 s_1000 *= 1000;
2490 ms = t->tv_usec / 1000;
2491 return s_1000 + ms;
2492}
2493
e882229c
NR
2494/* Return the current position of the mouse.
2495
2496 Set *f to the frame the mouse is in, or zero if the mouse is in no
2497 Emacs frame. If it is set to zero, all the other arguments are
2498 garbage.
2499
2500 Set *bar_window to Qnil, and *x and *y to the column and
2501 row of the character cell the mouse is over.
2502
7f3f1250 2503 Set *timeptr to the time the mouse was at the returned position.
e882229c 2504
80fb2ce0 2505 This clears mouse_moved until the next motion
94da14a0 2506 event arrives. */
e882229c 2507static void
a10c8269 2508term_mouse_position (struct frame **fp, int insist, Lisp_Object *bar_window,
e882229c 2509 enum scroll_bar_part *part, Lisp_Object *x,
08dc5ae6 2510 Lisp_Object *y, Time *timeptr)
e882229c 2511{
e882229c 2512 struct timeval now;
e882229c
NR
2513
2514 *fp = SELECTED_FRAME ();
94da14a0 2515 (*fp)->mouse_moved = 0;
e882229c
NR
2516
2517 *bar_window = Qnil;
2518 *part = 0;
2519
80fb2ce0 2520 XSETINT (*x, last_mouse_x);
94da14a0 2521 XSETINT (*y, last_mouse_y);
e882229c 2522 gettimeofday(&now, 0);
d35af63c 2523 *timeptr = timeval_to_Time (&now);
e882229c
NR
2524}
2525
2526/* Prepare a mouse-event in *RESULT for placement in the input queue.
2527
2528 If the event is a button press, then note that we have grabbed
2529 the mouse. */
2530
2531static Lisp_Object
2532term_mouse_click (struct input_event *result, Gpm_Event *event,
2533 struct frame *f)
2534{
2535 struct timeval now;
2536 int i, j;
2537
2538 result->kind = GPM_CLICK_EVENT;
2539 for (i = 0, j = GPM_B_LEFT; i < 3; i++, j >>= 1 )
2540 {
2541 if (event->buttons & j) {
2542 result->code = i; /* button number */
2543 break;
2544 }
2545 }
2546 gettimeofday(&now, 0);
d35af63c 2547 result->timestamp = timeval_to_Time (&now);
e882229c
NR
2548
2549 if (event->type & GPM_UP)
2550 result->modifiers = up_modifier;
2551 else if (event->type & GPM_DOWN)
2552 result->modifiers = down_modifier;
2553 else
2554 result->modifiers = 0;
f4d953fc 2555
e882229c
NR
2556 if (event->type & GPM_SINGLE)
2557 result->modifiers |= click_modifier;
f4d953fc 2558
e882229c
NR
2559 if (event->type & GPM_DOUBLE)
2560 result->modifiers |= double_modifier;
2561
2562 if (event->type & GPM_TRIPLE)
2563 result->modifiers |= triple_modifier;
2564
2565 if (event->type & GPM_DRAG)
2566 result->modifiers |= drag_modifier;
2567
80fb2ce0 2568 if (!(event->type & (GPM_MOVE | GPM_DRAG))) {
e882229c
NR
2569
2570 /* 1 << KG_SHIFT */
2571 if (event->modifiers & (1 << 0))
2572 result->modifiers |= shift_modifier;
2573
2574 /* 1 << KG_CTRL */
2575 if (event->modifiers & (1 << 2))
2576 result->modifiers |= ctrl_modifier;
2577
2578 /* 1 << KG_ALT || KG_ALTGR */
2579 if (event->modifiers & (1 << 3)
2580 || event->modifiers & (1 << 1))
2581 result->modifiers |= meta_modifier;
2582 }
2583
80fb2ce0
NR
2584 XSETINT (result->x, event->x);
2585 XSETINT (result->y, event->y);
e882229c
NR
2586 XSETFRAME (result->frame_or_window, f);
2587 result->arg = Qnil;
2588 return Qnil;
2589}
2590
f4d953fc 2591int
7be1c21a 2592handle_one_term_event (struct tty_display_info *tty, Gpm_Event *event, struct input_event* hold_quit)
e882229c 2593{
7be1c21a 2594 struct frame *f = XFRAME (tty->top_frame);
e882229c 2595 struct input_event ie;
653d4f43 2596 bool do_help = 0;
e882229c
NR
2597 int count = 0;
2598
2599 EVENT_INIT (ie);
2600 ie.kind = NO_EVENT;
2601 ie.arg = Qnil;
2602
80fb2ce0 2603 if (event->type & (GPM_MOVE | GPM_DRAG)) {
e882229c
NR
2604 previous_help_echo_string = help_echo_string;
2605 help_echo_string = Qnil;
2606
6178ce5e 2607 Gpm_DrawPointer (event->x, event->y, fileno (tty->output));
e882229c 2608
80fb2ce0
NR
2609 if (!term_mouse_movement (f, event))
2610 help_echo_string = previous_help_echo_string;
e882229c
NR
2611
2612 /* If the contents of the global variable help_echo_string
2613 has changed, generate a HELP_EVENT. */
2614 if (!NILP (help_echo_string)
2615 || !NILP (previous_help_echo_string))
2616 do_help = 1;
2617
2618 goto done;
2619 }
2620 else {
2621 f->mouse_moved = 0;
2622 term_mouse_click (&ie, event, f);
e882229c
NR
2623 }
2624
2625 done:
2626 if (ie.kind != NO_EVENT)
2627 {
2628 kbd_buffer_store_event_hold (&ie, hold_quit);
2629 count++;
2630 }
2631
2632 if (do_help
2633 && !(hold_quit && hold_quit->kind != NO_EVENT))
2634 {
2635 Lisp_Object frame;
2636
2637 if (f)
2638 XSETFRAME (frame, f);
2639 else
2640 frame = Qnil;
2641
2642 gen_help_event (help_echo_string, frame, help_echo_window,
2643 help_echo_object, help_echo_pos);
2644 count++;
2645 }
2646
2647 return count;
2648}
2649
6178ce5e 2650DEFUN ("gpm-mouse-start", Fgpm_mouse_start, Sgpm_mouse_start,
e882229c 2651 0, 0, 0,
71f44e7a 2652 doc: /* Open a connection to Gpm.
6178ce5e 2653Gpm-mouse can only be activated for one tty at a time. */)
5842a27b 2654 (void)
e882229c 2655{
71f44e7a
SM
2656 struct frame *f = SELECTED_FRAME ();
2657 struct tty_display_info *tty
2658 = ((f)->output_method == output_termcap
2659 ? (f)->terminal->display_info.tty : NULL);
e882229c
NR
2660 Gpm_Connect connection;
2661
6178ce5e
SM
2662 if (!tty)
2663 error ("Gpm-mouse only works in the GNU/Linux console");
4ce5ab77
SM
2664 if (gpm_tty == tty)
2665 return Qnil; /* Already activated, nothing to do. */
2666 if (gpm_tty)
2667 error ("Gpm-mouse can only be activated for one tty at a time");
71f44e7a 2668
e882229c
NR
2669 connection.eventMask = ~0;
2670 connection.defaultMask = ~GPM_HARD;
2671 connection.maxMod = ~0;
2672 connection.minMod = 0;
80fb2ce0 2673 gpm_zerobased = 1;
e882229c
NR
2674
2675 if (Gpm_Open (&connection, 0) < 0)
6178ce5e 2676 error ("Gpm-mouse failed to connect to the gpm daemon");
e882229c
NR
2677 else
2678 {
71f44e7a 2679 gpm_tty = tty;
1023cbed
SM
2680 /* `init_sys_modes' arranges for mouse movements sent through gpm_fd
2681 to generate SIGIOs. Apparently we need to call reset_sys_modes
2682 before calling init_sys_modes. */
7be1c21a
MB
2683 reset_sys_modes (tty);
2684 init_sys_modes (tty);
e882229c 2685 add_gpm_wait_descriptor (gpm_fd);
6178ce5e 2686 return Qnil;
e882229c
NR
2687 }
2688}
2689
ed5ff21d 2690void
d347e494 2691close_gpm (int fd)
ed5ff21d 2692{
d347e494
SM
2693 if (fd >= 0)
2694 delete_gpm_wait_descriptor (fd);
ed5ff21d
SM
2695 while (Gpm_Close()); /* close all the stack */
2696 gpm_tty = NULL;
2697}
2698
6178ce5e 2699DEFUN ("gpm-mouse-stop", Fgpm_mouse_stop, Sgpm_mouse_stop,
e882229c
NR
2700 0, 0, 0,
2701 doc: /* Close a connection to Gpm. */)
5842a27b 2702 (void)
e882229c 2703{
4ce5ab77
SM
2704 struct frame *f = SELECTED_FRAME ();
2705 struct tty_display_info *tty
2706 = ((f)->output_method == output_termcap
2707 ? (f)->terminal->display_info.tty : NULL);
2708
2709 if (!tty || gpm_tty != tty)
2710 return Qnil; /* Not activated on this terminal, nothing to do. */
f4d953fc 2711
d347e494 2712 close_gpm (gpm_fd);
6178ce5e 2713 return Qnil;
e882229c 2714}
7e5a23bd 2715#endif /* HAVE_GPM */
e882229c
NR
2716
2717\f
b5e9cbb6
EZ
2718/***********************************************************************
2719 Menus
2720 ***********************************************************************/
2721
7cdf484b 2722#if !defined (MSDOS)
b5e9cbb6
EZ
2723
2724/* TTY menu implementation and main ideas are borrowed from msdos.c.
2725
2726 However, unlike on MSDOS, where the menu text is drawn directly to
fa93733d
EZ
2727 the display video memory, on a TTY we use display_string (see
2728 display_tty_menu_item in xdisp.c) to put the glyphs produced from
ccd4a783
EZ
2729 the menu items into the frame's 'desired_matrix' glyph matrix, and
2730 then call update_frame_with_menu to deliver the results to the
2731 glass. The previous contents of the screen, in the form of the
2732 current_matrix, is stashed away, and used to restore screen
b5e9cbb6
EZ
2733 contents when the menu selection changes or when the final
2734 selection is made and the menu should be popped down.
2735
141f1ff7 2736 The idea of this implementation was suggested by Gerd Moellmann. */
b5e9cbb6
EZ
2737
2738#define TTYM_FAILURE -1
2739#define TTYM_SUCCESS 1
2740#define TTYM_NO_SELECT 2
2741#define TTYM_IA_SELECT 3
4a48e94d
EZ
2742#define TTYM_NEXT 4
2743#define TTYM_PREV 5
b5e9cbb6
EZ
2744
2745/* These hold text of the current and the previous menu help messages. */
2746static const char *menu_help_message, *prev_menu_help_message;
2747/* Pane number and item number of the menu item which generated the
2748 last menu help message. */
2749static int menu_help_paneno, menu_help_itemno;
2750
df782309
EZ
2751static Lisp_Object Qtty_menu_navigation_map, Qtty_menu_exit;
2752static Lisp_Object Qtty_menu_prev_item, Qtty_menu_next_item;
2753static Lisp_Object Qtty_menu_next_menu, Qtty_menu_prev_menu;
2754static Lisp_Object Qtty_menu_select, Qtty_menu_ignore;
e648f699 2755static Lisp_Object Qtty_menu_mouse_movement;
f0177f86 2756
b5e9cbb6
EZ
2757typedef struct tty_menu_struct
2758{
2759 int count;
2760 char **text;
2761 struct tty_menu_struct **submenu;
5cbcc455 2762 int *panenumber; /* Also used as enabled flag. */
3b158d11 2763 ptrdiff_t allocated;
b5e9cbb6
EZ
2764 int panecount;
2765 int width;
2766 const char **help_text;
2767} tty_menu;
2768
2769/* Create a brand new menu structure. */
2770
2771static tty_menu *
2772tty_menu_create (void)
2773{
3b158d11 2774 return xzalloc (sizeof *tty_menu_create ());
b5e9cbb6
EZ
2775}
2776
2777/* Allocate some (more) memory for MENU ensuring that there is room for one
3b158d11 2778 more item. */
b5e9cbb6
EZ
2779
2780static void
2781tty_menu_make_room (tty_menu *menu)
2782{
3b158d11 2783 if (menu->allocated == menu->count)
b5e9cbb6 2784 {
3b158d11
PE
2785 ptrdiff_t allocated = menu->allocated;
2786 menu->text = xpalloc (menu->text, &allocated, 1, -1, sizeof *menu->text);
2787 menu->text = xrealloc (menu->text, allocated * sizeof *menu->text);
2788 menu->submenu = xrealloc (menu->submenu,
2789 allocated * sizeof *menu->submenu);
2790 menu->panenumber = xrealloc (menu->panenumber,
2791 allocated * sizeof *menu->panenumber);
2792 menu->help_text = xrealloc (menu->help_text,
2793 allocated * sizeof *menu->help_text);
2794 menu->allocated = allocated;
b5e9cbb6
EZ
2795 }
2796}
2797
2798/* Search the given menu structure for a given pane number. */
2799
2800static tty_menu *
2801tty_menu_search_pane (tty_menu *menu, int pane)
2802{
2803 int i;
2804 tty_menu *try;
2805
2806 for (i = 0; i < menu->count; i++)
2807 if (menu->submenu[i])
2808 {
2809 if (pane == menu->panenumber[i])
2810 return menu->submenu[i];
798aef02
PE
2811 try = tty_menu_search_pane (menu->submenu[i], pane);
2812 if (try)
b5e9cbb6
EZ
2813 return try;
2814 }
2815 return (tty_menu *) 0;
2816}
2817
2818/* Determine how much screen space a given menu needs. */
2819
2820static void
2821tty_menu_calc_size (tty_menu *menu, int *width, int *height)
2822{
2823 int i, h2, w2, maxsubwidth, maxheight;
2824
9e30f0e1 2825 maxsubwidth = menu->width;
b5e9cbb6
EZ
2826 maxheight = menu->count;
2827 for (i = 0; i < menu->count; i++)
2828 {
2829 if (menu->submenu[i])
2830 {
2831 tty_menu_calc_size (menu->submenu[i], &w2, &h2);
2832 if (w2 > maxsubwidth) maxsubwidth = w2;
2833 if (i + h2 > maxheight) maxheight = i + h2;
2834 }
2835 }
9e30f0e1 2836 *width = maxsubwidth;
b5e9cbb6
EZ
2837 *height = maxheight;
2838}
2839
e648f699
EZ
2840static void
2841mouse_get_xy (int *x, int *y)
2842{
2843 struct frame *sf = SELECTED_FRAME ();
5cbcc455 2844 Lisp_Object lmx = Qnil, lmy = Qnil, lisp_dummy;
e648f699
EZ
2845 enum scroll_bar_part part_dummy;
2846 Time time_dummy;
2847
2848 if (FRAME_TERMINAL (sf)->mouse_position_hook)
2849 (*FRAME_TERMINAL (sf)->mouse_position_hook) (&sf, -1,
2850 &lisp_dummy, &part_dummy,
2851 &lmx, &lmy,
2852 &time_dummy);
2853 if (!NILP (lmx))
2854 {
2855 *x = XINT (lmx);
2856 *y = XINT (lmy);
2857 }
2858}
2859
ccd4a783
EZ
2860/* Display MENU at (X,Y) using FACES, starting with FIRST_ITEM
2861 (zero-based). */
b5e9cbb6 2862
b5e9cbb6 2863static void
ffc3882f 2864tty_menu_display (tty_menu *menu, int x, int y, int pn, int *faces,
798aef02 2865 int mx, int my, int first_item, bool disp_help)
b5e9cbb6 2866{
bbc10837 2867 int i, face, width, enabled, mousehere, row, col;
b5e9cbb6
EZ
2868 struct frame *sf = SELECTED_FRAME ();
2869 struct tty_display_info *tty = FRAME_TTY (sf);
48621e69
EZ
2870 /* Don't try to display more menu items than the console can display
2871 using the available screen lines. Exclude the echo area line, as
2872 it will be overwritten by the help-echo anyway. */
ccd4a783 2873 int max_items = min (menu->count - first_item, FRAME_LINES (sf) - 1 - y);
b5e9cbb6
EZ
2874
2875 menu_help_message = NULL;
2876
2877 width = menu->width;
e7873136
EZ
2878 col = cursorX (tty);
2879 row = cursorY (tty);
48621e69 2880 for (i = 0; i < max_items; i++)
b5e9cbb6 2881 {
342cf494 2882 int max_width = width + 2; /* +2 for padding blanks on each side */
ccd4a783 2883 int j = i + first_item;
b5e9cbb6 2884
ccd4a783 2885 if (menu->submenu[j])
342cf494 2886 max_width += 2; /* for displaying " >" after the item */
b5e9cbb6 2887 enabled
ccd4a783 2888 = (!menu->submenu[j] && menu->panenumber[j]) || (menu->submenu[j]);
b5e9cbb6
EZ
2889 mousehere = (y + i == my && x <= mx && mx < x + max_width);
2890 face = faces[enabled + mousehere * 2];
2891 /* Display the menu help string for the i-th menu item even if
2892 the menu item is currently disabled. That's what the GUI
2893 code does. */
2894 if (disp_help && enabled + mousehere * 2 >= 2)
2895 {
ccd4a783 2896 menu_help_message = menu->help_text[j];
b5e9cbb6 2897 menu_help_paneno = pn - 1;
ccd4a783 2898 menu_help_itemno = j;
b5e9cbb6 2899 }
a55ea27f
EZ
2900 /* Take note of the coordinates of the active menu item, to
2901 display the cursor there. */
2902 if (mousehere)
2903 {
2904 row = y + i;
2905 col = x;
2906 }
ccd4a783
EZ
2907 display_tty_menu_item (menu->text[j], max_width, face, x, y + i,
2908 menu->submenu[j] != NULL);
b5e9cbb6
EZ
2909 }
2910 update_frame_with_menu (sf);
2911 cursor_to (sf, row, col);
2912}
2913
2914/* --------------------------- X Menu emulation ---------------------- */
2915
b5e9cbb6
EZ
2916/* Create a new pane and place it on the outer-most level. */
2917
e7873136
EZ
2918static int
2919tty_menu_add_pane (tty_menu *menu, const char *txt)
b5e9cbb6
EZ
2920{
2921 int len;
3b158d11 2922 const unsigned char *p;
b5e9cbb6
EZ
2923
2924 tty_menu_make_room (menu);
2925 menu->submenu[menu->count] = tty_menu_create ();
2926 menu->text[menu->count] = (char *)txt;
2927 menu->panenumber[menu->count] = ++menu->panecount;
2928 menu->help_text[menu->count] = NULL;
2929 menu->count++;
2930
2931 /* Update the menu width, if necessary. */
3b158d11 2932 for (len = 0, p = (unsigned char *) txt; *p; )
b5e9cbb6
EZ
2933 {
2934 int ch_len;
2935 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
2936
2937 len += CHAR_WIDTH (ch);
2938 p += ch_len;
2939 }
2940
2941 if (len > menu->width)
2942 menu->width = len;
2943
2944 return menu->panecount;
2945}
2946
2947/* Create a new item in a menu pane. */
2948
798aef02 2949static bool
b5e9cbb6 2950tty_menu_add_selection (tty_menu *menu, int pane,
798aef02 2951 char *txt, bool enable, char const *help_text)
b5e9cbb6
EZ
2952{
2953 int len;
3b158d11 2954 unsigned char *p;
b5e9cbb6
EZ
2955
2956 if (pane)
798aef02
PE
2957 {
2958 menu = tty_menu_search_pane (menu, pane);
2959 if (! menu)
2960 return 0;
2961 }
b5e9cbb6
EZ
2962 tty_menu_make_room (menu);
2963 menu->submenu[menu->count] = (tty_menu *) 0;
2964 menu->text[menu->count] = txt;
2965 menu->panenumber[menu->count] = enable;
2966 menu->help_text[menu->count] = help_text;
2967 menu->count++;
2968
2969 /* Update the menu width, if necessary. */
3b158d11 2970 for (len = 0, p = (unsigned char *) txt; *p; )
b5e9cbb6
EZ
2971 {
2972 int ch_len;
2973 int ch = STRING_CHAR_AND_LENGTH (p, ch_len);
2974
2975 len += CHAR_WIDTH (ch);
2976 p += ch_len;
2977 }
2978
2979 if (len > menu->width)
2980 menu->width = len;
2981
798aef02 2982 return 1;
b5e9cbb6
EZ
2983}
2984
2985/* Decide where the menu would be placed if requested at (X,Y). */
2986
3b158d11 2987static void
b5e9cbb6
EZ
2988tty_menu_locate (tty_menu *menu, int x, int y,
2989 int *ulx, int *uly, int *width, int *height)
2990{
2991 tty_menu_calc_size (menu, width, height);
2992 *ulx = x + 1;
2993 *uly = y;
2994 *width += 2;
2995}
2996
2997struct tty_menu_state
2998{
141f1ff7 2999 struct glyph_matrix *screen_behind;
b5e9cbb6
EZ
3000 tty_menu *menu;
3001 int pane;
3002 int x, y;
3003};
3004
f34729ea
EZ
3005/* Save away the contents of frame F's current frame matrix, and
3006 enable all its rows. Value is a glyph matrix holding the contents
3007 of F's current frame matrix with all its glyph rows enabled. */
3008
4ed77415 3009static struct glyph_matrix *
f34729ea
EZ
3010save_and_enable_current_matrix (struct frame *f)
3011{
3012 int i;
3013 struct glyph_matrix *saved = xzalloc (sizeof *saved);
3014 saved->nrows = f->current_matrix->nrows;
3015 saved->rows = xzalloc (saved->nrows * sizeof *saved->rows);
3016
3017 for (i = 0; i < saved->nrows; ++i)
3018 {
3019 struct glyph_row *from = f->current_matrix->rows + i;
3020 struct glyph_row *to = saved->rows + i;
3021 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3022
3023 to->glyphs[TEXT_AREA] = xmalloc (nbytes);
3024 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3025 to->used[TEXT_AREA] = from->used[TEXT_AREA];
3026 /* Make sure every row is enabled, or else update_frame will not
3027 redraw them. (Rows that are identical to what is already on
3028 screen will not be redrawn anyway.) */
96c06863 3029 to->enabled_p = true;
f34729ea 3030 to->hash = from->hash;
f34729ea
EZ
3031 }
3032
3033 return saved;
3034}
3035
141f1ff7
EZ
3036/* Restore the contents of frame F's desired frame matrix from SAVED,
3037 and free memory associated with SAVED. */
b5e9cbb6 3038
141f1ff7
EZ
3039static void
3040restore_desired_matrix (struct frame *f, struct glyph_matrix *saved)
3041{
3042 int i;
3043
3044 for (i = 0; i < saved->nrows; ++i)
3045 {
3046 struct glyph_row *from = saved->rows + i;
3047 struct glyph_row *to = f->desired_matrix->rows + i;
3048 ptrdiff_t nbytes = from->used[TEXT_AREA] * sizeof (struct glyph);
3049
96114a30 3050 eassert (to->glyphs[TEXT_AREA] != from->glyphs[TEXT_AREA]);
141f1ff7
EZ
3051 memcpy (to->glyphs[TEXT_AREA], from->glyphs[TEXT_AREA], nbytes);
3052 to->used[TEXT_AREA] = from->used[TEXT_AREA];
fa93733d
EZ
3053 to->enabled_p = from->enabled_p;
3054 to->hash = from->hash;
141f1ff7 3055 }
141f1ff7
EZ
3056}
3057
3058static void
3059free_saved_screen (struct glyph_matrix *saved)
3060{
3061 int i;
3062
3063 if (!saved)
caecb91c 3064 return; /* Already freed! */
141f1ff7
EZ
3065
3066 for (i = 0; i < saved->nrows; ++i)
3067 {
3068 struct glyph_row *from = saved->rows + i;
3069
3070 xfree (from->glyphs[TEXT_AREA]);
141f1ff7
EZ
3071 }
3072
3073 xfree (saved->rows);
3074 xfree (saved);
3075}
3076
3077/* Update the display of frame F from its saved contents. */
3078static void
3079screen_update (struct frame *f, struct glyph_matrix *mtx)
3080{
3081 restore_desired_matrix (f, mtx);
3082 update_frame_with_menu (f);
3083}
3084
ccd4a783
EZ
3085typedef enum {
3086 MI_QUIT_MENU = -1,
3087 MI_CONTINUE = 0,
3088 MI_ITEM_SELECTED = 1,
3089 MI_NEXT_ITEM = 2,
3090 MI_PREV_ITEM = 3,
3091 MI_SCROLL_FORWARD = 4,
3092 MI_SCROLL_BACK = 5
3093} mi_result;
0de83597 3094
ccd4a783
EZ
3095/* Read user input and return X and Y coordinates where that input
3096 puts us. We only consider mouse movement and click events, and
3097 keyboard movement commands; the rest are ignored. */
3098static mi_result
df782309
EZ
3099read_menu_input (struct frame *sf, int *x, int *y, int min_y, int max_y,
3100 bool *first_time)
141f1ff7 3101{
ffc3882f
EZ
3102 if (*first_time)
3103 {
3104 *first_time = false;
3105 sf->mouse_moved = 1;
ffc3882f 3106 }
afd8eb2c 3107 else
141f1ff7 3108 {
7ace9265 3109 Lisp_Object cmd;
798aef02 3110 bool usable_input = 1;
ccd4a783 3111 mi_result st = MI_CONTINUE;
f34729ea 3112 struct tty_display_info *tty = FRAME_TTY (sf);
e648f699 3113 Lisp_Object saved_mouse_tracking = do_mouse_tracking;
f0177f86 3114
f34729ea
EZ
3115 /* Signal the keyboard reading routines we are displaying a menu
3116 on this terminal. */
3117 tty->showing_menu = 1;
e648f699
EZ
3118 /* We want mouse movements be reported by read_menu_command. */
3119 do_mouse_tracking = Qt;
7ace9265
EZ
3120 do {
3121 cmd = read_menu_command ();
e648f699 3122 } while (NILP (cmd));
f34729ea 3123 tty->showing_menu = 0;
e648f699 3124 do_mouse_tracking = saved_mouse_tracking;
7ace9265 3125
e96f7bf1
EZ
3126 if (EQ (cmd, Qt) || EQ (cmd, Qtty_menu_exit)
3127 /* If some input switched frames under our feet, exit the
3128 menu, since the menu faces are no longer valid, and the
3129 menu is no longer relevant anyway. */
3130 || sf != SELECTED_FRAME ())
ccd4a783 3131 return MI_QUIT_MENU;
e648f699 3132 if (EQ (cmd, Qtty_menu_mouse_movement))
3b158d11 3133 mouse_get_xy (x, y);
e648f699 3134 else if (EQ (cmd, Qtty_menu_next_menu))
4a48e94d
EZ
3135 {
3136 usable_input = 0;
ccd4a783 3137 st = MI_NEXT_ITEM;
4a48e94d 3138 }
df782309 3139 else if (EQ (cmd, Qtty_menu_prev_menu))
4a48e94d
EZ
3140 {
3141 usable_input = 0;
ccd4a783 3142 st = MI_PREV_ITEM;
4a48e94d 3143 }
df782309
EZ
3144 else if (EQ (cmd, Qtty_menu_next_item))
3145 {
3146 if (*y < max_y)
3147 *y += 1;
052bac0b 3148 else
ccd4a783 3149 st = MI_SCROLL_FORWARD;
df782309
EZ
3150 }
3151 else if (EQ (cmd, Qtty_menu_prev_item))
3152 {
3153 if (*y > min_y)
3154 *y -= 1;
052bac0b 3155 else
ccd4a783 3156 st = MI_SCROLL_BACK;
df782309
EZ
3157 }
3158 else if (EQ (cmd, Qtty_menu_select))
ccd4a783 3159 st = MI_ITEM_SELECTED;
df782309 3160 else if (!EQ (cmd, Qtty_menu_ignore))
e648f699 3161 usable_input = 0;
f0177f86
EZ
3162 if (usable_input)
3163 sf->mouse_moved = 1;
0de83597 3164 return st;
141f1ff7 3165 }
ccd4a783 3166 return MI_CONTINUE;
141f1ff7
EZ
3167}
3168
3169/* Display menu, wait for user's response, and return that response. */
4a48e94d 3170static int
b5e9cbb6
EZ
3171tty_menu_activate (tty_menu *menu, int *pane, int *selidx,
3172 int x0, int y0, char **txt,
4a48e94d 3173 void (*help_callback)(char const *, int, int),
798aef02 3174 bool kbd_navigation)
b5e9cbb6
EZ
3175{
3176 struct tty_menu_state *state;
798aef02
PE
3177 int statecount, x, y, i;
3178 bool leave, onepane;
3b158d11 3179 int result IF_LINT (= 0);
caecb91c 3180 int title_faces[4]; /* Face to display the menu title. */
b5e9cbb6
EZ
3181 int faces[4], buffers_num_deleted = 0;
3182 struct frame *sf = SELECTED_FRAME ();
28a16449 3183 struct tty_display_info *tty = FRAME_TTY (sf);
ffc3882f 3184 bool first_time;
3b158d11 3185 Lisp_Object selectface;
ccd4a783 3186 int first_item = 0;
a55ea27f 3187 int col, row;
b5e9cbb6
EZ
3188
3189 /* Don't allow non-positive x0 and y0, lest the menu will wrap
3190 around the display. */
3191 if (x0 <= 0)
3192 x0 = 1;
3193 if (y0 <= 0)
3194 y0 = 1;
3195
b5e9cbb6 3196 state = alloca (menu->panecount * sizeof (struct tty_menu_state));
141f1ff7 3197 memset (state, 0, sizeof (*state));
b5e9cbb6
EZ
3198 faces[0]
3199 = lookup_derived_face (sf, intern ("tty-menu-disabled-face"),
3200 DEFAULT_FACE_ID, 1);
3201 faces[1]
3202 = lookup_derived_face (sf, intern ("tty-menu-enabled-face"),
3203 DEFAULT_FACE_ID, 1);
3204 selectface = intern ("tty-menu-selected-face");
3205 faces[2] = lookup_derived_face (sf, selectface,
3206 faces[0], 1);
3207 faces[3] = lookup_derived_face (sf, selectface,
3208 faces[1], 1);
3209
3210 /* Make sure the menu title is always displayed with
50a5f95e 3211 `tty-menu-selected-face', no matter where the mouse pointer is. */
b5e9cbb6
EZ
3212 for (i = 0; i < 4; i++)
3213 title_faces[i] = faces[3];
3214
3215 statecount = 1;
3216
3217 /* Don't let the title for the "Buffers" popup menu include a
3218 digit (which is ugly).
3219
3220 This is a terrible kludge, but I think the "Buffers" case is
3221 the only one where the title includes a number, so it doesn't
3222 seem to be necessary to make this more general. */
3223 if (strncmp (menu->text[0], "Buffers 1", 9) == 0)
3224 {
3225 menu->text[0][7] = '\0';
3226 buffers_num_deleted = 1;
3227 }
3228
141f1ff7
EZ
3229 /* Force update of the current frame, so that the desired and the
3230 current matrices are identical. */
3231 update_frame_with_menu (sf);
b5e9cbb6 3232 state[0].menu = menu;
f34729ea 3233 state[0].screen_behind = save_and_enable_current_matrix (sf);
b5e9cbb6 3234
ffc3882f
EZ
3235 /* Display the menu title. We subtract 1 from x0 and y0 because we
3236 want to interpret them as zero-based column and row coordinates,
3237 and also because we want the first item of the menu, not its
3238 title, to appear at x0,y0. */
ccd4a783 3239 tty_menu_display (menu, x0 - 1, y0 - 1, 1, title_faces, x0 - 1, y0 - 1, 0, 0);
6270e29e
EZ
3240
3241 /* Turn off the cursor. Otherwise it shows through the menu
3242 panes, which is ugly. */
28c05b69
EZ
3243 col = cursorX (tty);
3244 row = cursorY (tty);
6270e29e 3245 tty_hide_cursor (tty);
28c05b69 3246
b5e9cbb6
EZ
3247 if (buffers_num_deleted)
3248 menu->text[0][7] = ' ';
798aef02
PE
3249 onepane = menu->count == 1 && menu->submenu[0];
3250 if (onepane)
b5e9cbb6
EZ
3251 {
3252 menu->width = menu->submenu[0]->width;
3253 state[0].menu = menu->submenu[0];
3254 }
3255 else
3256 {
3257 state[0].menu = menu;
3258 }
3259 state[0].x = x0 - 1;
3260 state[0].y = y0;
3261 state[0].pane = onepane;
3262
141f1ff7
EZ
3263 x = state[0].x;
3264 y = state[0].y;
ffc3882f 3265 first_time = true;
141f1ff7 3266
b5e9cbb6
EZ
3267 leave = 0;
3268 while (!leave)
3269 {
ccd4a783 3270 mi_result input_status;
48621e69 3271 int min_y = state[0].y;
052bac0b 3272 int max_y = min (min_y + state[0].menu->count, FRAME_LINES (sf) - 1) - 1;
e7873136 3273
df782309 3274 input_status = read_menu_input (sf, &x, &y, min_y, max_y, &first_time);
f0177f86
EZ
3275 if (input_status)
3276 {
4a48e94d 3277 leave = 1;
ccd4a783 3278 switch (input_status)
824682ea 3279 {
ccd4a783 3280 case MI_QUIT_MENU:
824682ea
EZ
3281 /* Remove the last help-echo, so that it doesn't
3282 re-appear after "Quit". */
3283 show_help_echo (Qnil, Qnil, Qnil, Qnil);
3284 result = TTYM_NO_SELECT;
ccd4a783
EZ
3285 break;
3286 case MI_NEXT_ITEM:
4a48e94d
EZ
3287 if (kbd_navigation)
3288 result = TTYM_NEXT;
3289 else
3290 leave = 0;
ccd4a783
EZ
3291 break;
3292 case MI_PREV_ITEM:
4a48e94d
EZ
3293 if (kbd_navigation)
3294 result = TTYM_PREV;
3295 else
3296 leave = 0;
ccd4a783
EZ
3297 break;
3298 case MI_SCROLL_FORWARD:
3299 if (y - min_y == state[0].menu->count - 1 - first_item)
3300 {
3301 y = min_y;
3302 first_item = 0;
3303 }
3304 else
3305 first_item++;
3306 leave = 0;
3307 break;
3308 case MI_SCROLL_BACK:
3309 if (first_item == 0)
3310 {
3311 y = max_y;
3312 first_item = state[0].menu->count - 1 - (y - min_y);
3313 }
3314 else
3315 first_item--;
3316 leave = 0;
3317 break;
3318 default:
3319 /* MI_ITEM_SELECTED is handled below, so nothing to do. */
3320 break;
4a48e94d 3321 }
f0177f86 3322 }
ccd4a783 3323 if (sf->mouse_moved && input_status != MI_QUIT_MENU)
b5e9cbb6
EZ
3324 {
3325 sf->mouse_moved = 0;
3326 result = TTYM_IA_SELECT;
b5e9cbb6
EZ
3327 for (i = 0; i < statecount; i++)
3328 if (state[i].x <= x && x < state[i].x + state[i].menu->width + 2)
3329 {
ccd4a783 3330 int dy = y - state[i].y + first_item;
b5e9cbb6
EZ
3331 if (0 <= dy && dy < state[i].menu->count)
3332 {
3333 if (!state[i].menu->submenu[dy])
3334 {
3335 if (state[i].menu->panenumber[dy])
3336 result = TTYM_SUCCESS;
3337 else
3338 result = TTYM_IA_SELECT;
3339 }
3340 *pane = state[i].pane - 1;
3341 *selidx = dy;
3342 /* We hit some part of a menu, so drop extra menus that
3343 have been opened. That does not include an open and
3344 active submenu. */
3345 if (i != statecount - 2
caecb91c 3346 || state[i].menu->submenu[dy] != state[i + 1].menu)
b5e9cbb6
EZ
3347 while (i != statecount - 1)
3348 {
3349 statecount--;
e7873136 3350 screen_update (sf, state[statecount].screen_behind);
141f1ff7 3351 state[statecount].screen_behind = NULL;
b5e9cbb6
EZ
3352 }
3353 if (i == statecount - 1 && state[i].menu->submenu[dy])
3354 {
3355 tty_menu_display (state[i].menu,
b5e9cbb6 3356 state[i].x,
ffc3882f 3357 state[i].y,
b5e9cbb6 3358 state[i].pane,
ccd4a783 3359 faces, x, y, first_item, 1);
b5e9cbb6
EZ
3360 state[statecount].menu = state[i].menu->submenu[dy];
3361 state[statecount].pane = state[i].menu->panenumber[dy];
141f1ff7 3362 state[statecount].screen_behind
f34729ea 3363 = save_and_enable_current_matrix (sf);
b5e9cbb6
EZ
3364 state[statecount].x
3365 = state[i].x + state[i].menu->width + 2;
3366 state[statecount].y = y;
3367 statecount++;
3368 }
3369 }
3370 }
3371 tty_menu_display (state[statecount - 1].menu,
b5e9cbb6 3372 state[statecount - 1].x,
ffc3882f 3373 state[statecount - 1].y,
b5e9cbb6 3374 state[statecount - 1].pane,
ccd4a783 3375 faces, x, y, first_item, 1);
6270e29e
EZ
3376 tty_hide_cursor (tty);
3377 fflush (tty->output);
a55ea27f
EZ
3378 /* The call to display help-echo below will move the cursor,
3379 so remember its current position as computed by
3380 tty_menu_display. */
3381 col = cursorX (tty);
3382 row = cursorY (tty);
b5e9cbb6 3383 }
824682ea
EZ
3384
3385 /* Display the help-echo message for the currently-selected menu
3386 item. */
3387 if ((menu_help_message || prev_menu_help_message)
3388 && menu_help_message != prev_menu_help_message)
b5e9cbb6 3389 {
824682ea
EZ
3390 help_callback (menu_help_message,
3391 menu_help_paneno, menu_help_itemno);
a55ea27f
EZ
3392 /* Move the cursor to the beginning of the current menu
3393 item, so that screen readers and other accessibility aids
3394 know where the active region is. */
28c05b69 3395 cursor_to (sf, row, col);
824682ea 3396 tty_hide_cursor (tty);
6270e29e 3397 fflush (tty->output);
824682ea 3398 prev_menu_help_message = menu_help_message;
b5e9cbb6 3399 }
b5e9cbb6
EZ
3400 }
3401
ffc3882f 3402 sf->mouse_moved = 0;
141f1ff7 3403 screen_update (sf, state[0].screen_behind);
b5e9cbb6 3404 while (statecount--)
141f1ff7 3405 free_saved_screen (state[statecount].screen_behind);
caecb91c 3406 tty_show_cursor (tty); /* Turn cursor back on. */
9f6a18d2 3407 fflush (tty->output);
28a16449
EZ
3408
3409/* Clean up any mouse events that are waiting inside Emacs event queue.
b5e9cbb6
EZ
3410 These events are likely to be generated before the menu was even
3411 displayed, probably because the user pressed and released the button
3412 (which invoked the menu) too quickly. If we don't remove these events,
3413 Emacs will process them after we return and surprise the user. */
3414 discard_mouse_events ();
e7873136 3415 if (!kbd_buffer_events_waiting ())
b5e9cbb6 3416 clear_input_pending ();
b5e9cbb6
EZ
3417 return result;
3418}
3419
3420/* Dispose of a menu. */
3421
3b158d11 3422static void
b5e9cbb6
EZ
3423tty_menu_destroy (tty_menu *menu)
3424{
3425 int i;
3426 if (menu->allocated)
3427 {
3428 for (i = 0; i < menu->count; i++)
3429 if (menu->submenu[i])
3430 tty_menu_destroy (menu->submenu[i]);
3431 xfree (menu->text);
3432 xfree (menu->submenu);
3433 xfree (menu->panenumber);
3434 xfree (menu->help_text);
3435 }
3436 xfree (menu);
3437 menu_help_message = prev_menu_help_message = NULL;
3438}
3439
e7873136
EZ
3440/* Show help HELP_STRING, or clear help if HELP_STRING is null.
3441
3442 PANE is the pane number, and ITEM is the menu item number in
5cbcc455 3443 the menu (currently not used). */
e7873136
EZ
3444
3445static void
3446tty_menu_help_callback (char const *help_string, int pane, int item)
3447{
3448 Lisp_Object *first_item;
3449 Lisp_Object pane_name;
3450 Lisp_Object menu_object;
3451
91f2d272 3452 first_item = XVECTOR (menu_items)->contents;
e7873136
EZ
3453 if (EQ (first_item[0], Qt))
3454 pane_name = first_item[MENU_ITEMS_PANE_NAME];
3455 else if (EQ (first_item[0], Qquote))
3456 /* This shouldn't happen, see xmenu_show. */
3457 pane_name = empty_unibyte_string;
3458 else
3459 pane_name = first_item[MENU_ITEMS_ITEM_NAME];
3460
3461 /* (menu-item MENU-NAME PANE-NUMBER) */
3462 menu_object = list3 (Qmenu_item, pane_name, make_number (pane));
3463 show_help_echo (help_string ? build_string (help_string) : Qnil,
3464 Qnil, menu_object, make_number (item));
3465}
3466
3467static void
3468tty_pop_down_menu (Lisp_Object arg)
3469{
3470 tty_menu *menu = XSAVE_POINTER (arg, 0);
3471
3472 block_input ();
3473 tty_menu_destroy (menu);
3474 unblock_input ();
3475}
3476
4a48e94d
EZ
3477/* Return the zero-based index of the last menu-bar item on frame F. */
3478static int
3479tty_menu_last_menubar_item (struct frame *f)
3480{
3481 int i = 0;
3482
3483 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3484 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3485 {
3486 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3487
3488 while (i < ASIZE (items))
3489 {
3490 Lisp_Object str;
3491
3492 str = AREF (items, i + 1);
3493 if (NILP (str))
3494 break;
3495 i += 4;
3496 }
caecb91c 3497 i -= 4; /* Went one too far! */
4a48e94d
EZ
3498 }
3499 return i;
3500}
3501
3502/* Find in frame F's menu bar the menu item that is next or previous
3503 to the item at X/Y, and return that item's position in X/Y. WHICH
3504 says which one--next or previous--item to look for. X and Y are
3505 measured in character cells. This should only be called on TTY
3506 frames. */
3507static void
3508tty_menu_new_item_coords (struct frame *f, int which, int *x, int *y)
3509{
3510 eassert (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f));
3511 if (FRAME_TERMCAP_P (f) && FRAME_LIVE_P (f))
3512 {
3513 Lisp_Object items = FRAME_MENU_BAR_ITEMS (f);
3514 int last_i = tty_menu_last_menubar_item (f);
3515 int i, prev_x;
3516
3517 /* This loop assumes a single menu-bar line, and will fail to
3518 find an item if it is not in the first line. Note that
3519 make_lispy_event in keyboard.c makes the same assumption. */
3520 for (i = 0, prev_x = -1; i < ASIZE (items); i += 4)
3521 {
3522 Lisp_Object pos, str;
3523 int ix;
3524
3525 str = AREF (items, i + 1);
3526 pos = AREF (items, i + 3);
3527 if (NILP (str))
3528 return;
3529 ix = XINT (pos);
3530 if (ix <= *x
3531 /* We use <= so the blank between 2 items on a TTY is
3532 considered part of the previous item. */
3b158d11 3533 && *x <= ix + menu_item_width (SDATA (str)))
4a48e94d
EZ
3534 {
3535 /* Found current item. Now compute the X coordinate of
3536 the previous or next item. */
3537 if (which == TTYM_NEXT)
3538 {
3539 if (i < last_i)
3540 *x = XINT (AREF (items, i + 4 + 3));
3541 else
caecb91c 3542 *x = 0; /* Wrap around to the first item. */
4a48e94d
EZ
3543 }
3544 else if (prev_x < 0)
3545 {
3546 /* Wrap around to the last item. */
3547 *x = XINT (AREF (items, last_i + 3));
3548 }
3549 else
3550 *x = prev_x;
3551 return;
3552 }
3553 prev_x = ix;
3554 }
3555 }
3556}
3557
b5e9cbb6 3558Lisp_Object
798aef02
PE
3559tty_menu_show (struct frame *f, int x, int y, bool for_click, bool keymaps,
3560 Lisp_Object title, bool kbd_navigation, const char **error_name)
b5e9cbb6
EZ
3561{
3562 tty_menu *menu;
3563 int pane, selidx, lpane, status;
3564 Lisp_Object entry, pane_prefix;
3565 char *datap;
3566 int ulx, uly, width, height;
4a48e94d 3567 int item_x, item_y;
b5e9cbb6
EZ
3568 int dispwidth, dispheight;
3569 int i, j, lines, maxlines;
3570 int maxwidth;
9428abbf 3571 ptrdiff_t specpdl_count;
b5e9cbb6 3572
9428abbf 3573 eassert (FRAME_TERMCAP_P (f));
b5e9cbb6
EZ
3574
3575 *error_name = 0;
3576 if (menu_items_n_panes == 0)
3577 return Qnil;
3578
3579 if (menu_items_used <= MENU_ITEMS_PANE_LENGTH)
3580 {
3581 *error_name = "Empty menu";
3582 return Qnil;
3583 }
3584
3585 /* Make the menu on that window. */
3586 menu = tty_menu_create ();
3587 if (menu == NULL)
3588 {
3589 *error_name = "Can't create menu";
3590 return Qnil;
3591 }
3592
3593 /* Don't GC while we prepare and show the menu, because we give the
3594 menu functions pointers to the contents of strings. */
9428abbf 3595 specpdl_count = inhibit_garbage_collection ();
b5e9cbb6
EZ
3596
3597 /* Adjust coordinates to be root-window-relative. */
4a48e94d
EZ
3598 item_x = x += f->left_pos;
3599 item_y = y += f->top_pos;
b5e9cbb6
EZ
3600
3601 /* Create all the necessary panes and their items. */
3602 maxwidth = maxlines = lines = i = 0;
3603 lpane = TTYM_FAILURE;
3604 while (i < menu_items_used)
3605 {
dfe3ac02 3606 if (EQ (AREF (menu_items, i), Qt))
b5e9cbb6
EZ
3607 {
3608 /* Create a new pane. */
3609 Lisp_Object pane_name, prefix;
3610 const char *pane_string;
3611
3612 maxlines = max (maxlines, lines);
3613 lines = 0;
dfe3ac02
EZ
3614 pane_name = AREF (menu_items, i + MENU_ITEMS_PANE_NAME);
3615 prefix = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
b5e9cbb6
EZ
3616 pane_string = (NILP (pane_name)
3617 ? "" : SSDATA (pane_name));
3618 if (keymaps && !NILP (prefix))
3619 pane_string++;
3620
3621 lpane = tty_menu_add_pane (menu, pane_string);
3622 if (lpane == TTYM_FAILURE)
3623 {
3624 tty_menu_destroy (menu);
3625 *error_name = "Can't create pane";
9428abbf
DA
3626 entry = Qnil;
3627 goto tty_menu_end;
b5e9cbb6
EZ
3628 }
3629 i += MENU_ITEMS_PANE_LENGTH;
3630
3631 /* Find the width of the widest item in this pane. */
3632 j = i;
3633 while (j < menu_items_used)
3634 {
3635 Lisp_Object item;
dfe3ac02 3636 item = AREF (menu_items, j);
b5e9cbb6
EZ
3637 if (EQ (item, Qt))
3638 break;
3639 if (NILP (item))
3640 {
3641 j++;
3642 continue;
3643 }
3644 width = SBYTES (item);
3645 if (width > maxwidth)
3646 maxwidth = width;
3647
3648 j += MENU_ITEMS_ITEM_LENGTH;
3649 }
3650 }
3651 /* Ignore a nil in the item list.
3652 It's meaningful only for dialog boxes. */
dfe3ac02 3653 else if (EQ (AREF (menu_items, i), Qquote))
b5e9cbb6
EZ
3654 i += 1;
3655 else
3656 {
3657 /* Create a new item within current pane. */
3658 Lisp_Object item_name, enable, descrip, help;
3659 char *item_data;
3660 char const *help_string;
3661
dfe3ac02
EZ
3662 item_name = AREF (menu_items, i + MENU_ITEMS_ITEM_NAME);
3663 enable = AREF (menu_items, i + MENU_ITEMS_ITEM_ENABLE);
3664 descrip = AREF (menu_items, i + MENU_ITEMS_ITEM_EQUIV_KEY);
3665 help = AREF (menu_items, i + MENU_ITEMS_ITEM_HELP);
b5e9cbb6
EZ
3666 help_string = STRINGP (help) ? SSDATA (help) : NULL;
3667
3668 if (!NILP (descrip))
3669 {
caecb91c 3670 /* If alloca is fast, use that to make the space,
b5e9cbb6
EZ
3671 to reduce gc needs. */
3672 item_data = (char *) alloca (maxwidth + SBYTES (descrip) + 1);
3673 memcpy (item_data, SSDATA (item_name), SBYTES (item_name));
3674 for (j = SCHARS (item_name); j < maxwidth; j++)
3675 item_data[j] = ' ';
3676 memcpy (item_data + j, SSDATA (descrip), SBYTES (descrip));
3677 item_data[j + SBYTES (descrip)] = 0;
3678 }
3679 else
3680 item_data = SSDATA (item_name);
3681
3682 if (lpane == TTYM_FAILURE
798aef02
PE
3683 || (! tty_menu_add_selection (menu, lpane, item_data,
3684 !NILP (enable), help_string)))
b5e9cbb6
EZ
3685 {
3686 tty_menu_destroy (menu);
3687 *error_name = "Can't add selection to menu";
9428abbf
DA
3688 entry = Qnil;
3689 goto tty_menu_end;
b5e9cbb6
EZ
3690 }
3691 i += MENU_ITEMS_ITEM_LENGTH;
3692 lines++;
3693 }
3694 }
3695
3696 maxlines = max (maxlines, lines);
3697
3698 /* All set and ready to fly. */
3699 dispwidth = f->text_cols;
3700 dispheight = f->text_lines;
3701 x = min (x, dispwidth);
3702 y = min (y, dispheight);
3703 x = max (x, 1);
3704 y = max (y, 1);
3705 tty_menu_locate (menu, x, y, &ulx, &uly, &width, &height);
9428abbf 3706 if (ulx + width > dispwidth)
b5e9cbb6
EZ
3707 {
3708 x -= (ulx + width) - dispwidth;
3709 ulx = dispwidth - width;
3710 }
9428abbf 3711 if (uly + height > dispheight)
b5e9cbb6
EZ
3712 {
3713 y -= (uly + height) - dispheight;
3714 uly = dispheight - height;
3715 }
3716
caecb91c 3717 if (FRAME_HAS_MINIBUF_P (f) && uly + height > dispheight - 2)
b5e9cbb6
EZ
3718 {
3719 /* Move the menu away of the echo area, to avoid overwriting the
3720 menu with help echo messages or vice versa. */
3721 if (BUFFERP (echo_area_buffer[0]) && WINDOWP (echo_area_window))
3722 {
df782309
EZ
3723 y -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
3724 uly -= WINDOW_TOTAL_LINES (XWINDOW (echo_area_window)) + 1;
b5e9cbb6
EZ
3725 }
3726 else
3727 {
df782309
EZ
3728 y -= 2;
3729 uly -= 2;
b5e9cbb6
EZ
3730 }
3731 }
3732
3733 if (ulx < 0) x -= ulx;
3734 if (uly < 0) y -= uly;
3735
a01f89af
EZ
3736#if 0
3737 /* This code doesn't make sense on a TTY, since it can easily annul
3738 the adjustments above that carefully avoid truncation of the menu
5cbcc455
EZ
3739 items. I think it was written to fix some problem that only
3740 happens on X11. */
b5e9cbb6
EZ
3741 if (! for_click)
3742 {
3743 /* If position was not given by a mouse click, adjust so upper left
3744 corner of the menu as a whole ends up at given coordinates. This
3745 is what x-popup-menu says in its documentation. */
caecb91c
SM
3746 x += width / 2;
3747 y += 1.5 * height / (maxlines + 2);
b5e9cbb6 3748 }
a01f89af 3749#endif
b5e9cbb6
EZ
3750
3751 pane = selidx = 0;
3752
e7873136 3753 record_unwind_protect (tty_pop_down_menu, make_save_ptr (menu));
b5e9cbb6 3754
df782309
EZ
3755 specbind (Qoverriding_terminal_local_map,
3756 Fsymbol_value (Qtty_menu_navigation_map));
b5e9cbb6 3757 status = tty_menu_activate (menu, &pane, &selidx, x, y, &datap,
4a48e94d 3758 tty_menu_help_callback, kbd_navigation);
b5e9cbb6
EZ
3759 entry = pane_prefix = Qnil;
3760
3761 switch (status)
3762 {
3763 case TTYM_SUCCESS:
3764 /* Find the item number SELIDX in pane number PANE. */
3765 i = 0;
3766 while (i < menu_items_used)
3767 {
dfe3ac02 3768 if (EQ (AREF (menu_items, i), Qt))
b5e9cbb6
EZ
3769 {
3770 if (pane == 0)
3771 pane_prefix
dfe3ac02 3772 = AREF (menu_items, i + MENU_ITEMS_PANE_PREFIX);
b5e9cbb6
EZ
3773 pane--;
3774 i += MENU_ITEMS_PANE_LENGTH;
3775 }
3776 else
3777 {
3778 if (pane == -1)
3779 {
3780 if (selidx == 0)
3781 {
3782 entry
dfe3ac02 3783 = AREF (menu_items, i + MENU_ITEMS_ITEM_VALUE);
b5e9cbb6
EZ
3784 if (keymaps != 0)
3785 {
3786 entry = Fcons (entry, Qnil);
3787 if (!NILP (pane_prefix))
3788 entry = Fcons (pane_prefix, entry);
3789 }
3790 break;
3791 }
3792 selidx--;
3793 }
3794 i += MENU_ITEMS_ITEM_LENGTH;
3795 }
3796 }
3797 break;
3798
4a48e94d
EZ
3799 case TTYM_NEXT:
3800 case TTYM_PREV:
3801 tty_menu_new_item_coords (f, status, &item_x, &item_y);
3802 entry = Fcons (make_number (item_x), make_number (item_y));
3803 break;
3804
b5e9cbb6
EZ
3805 case TTYM_FAILURE:
3806 *error_name = "Can't activate menu";
3807 case TTYM_IA_SELECT:
3808 break;
3809 case TTYM_NO_SELECT:
e96f7bf1
EZ
3810 /* If the selected frame was changed while we displayed a menu,
3811 throw to top level in order to undo any temporary settings
3812 made by TTY menu code. */
3813 if (f != SELECTED_FRAME ())
3814 Ftop_level ();
b5e9cbb6
EZ
3815 /* Make "Cancel" equivalent to C-g unless FOR_CLICK (which means
3816 the menu was invoked with a mouse event as POSITION). */
3817 if (! for_click)
3818 Fsignal (Qquit, Qnil);
3819 break;
3820 }
3821
9428abbf 3822 tty_menu_end:
b5e9cbb6 3823
9428abbf 3824 unbind_to (specpdl_count, Qnil);
b5e9cbb6
EZ
3825 return entry;
3826}
3827
7cdf484b 3828#endif /* !MSDOS */
b5e9cbb6
EZ
3829
3830\f
89ba96f4 3831#ifndef MSDOS
a168702a
GM
3832/***********************************************************************
3833 Initialization
3834 ***********************************************************************/
3835
ed8dad6b 3836/* Initialize the tty-dependent part of frame F. The frame must
7cdf484b 3837 already have its device initialized. */
3224dac1 3838
dfcf069d 3839void
ed8dad6b 3840create_tty_output (struct frame *f)
28d440ab 3841{
38182d90 3842 struct tty_output *t = xzalloc (sizeof *t);
ed8dad6b 3843
9c253307 3844 eassert (FRAME_TERMCAP_P (f));
428a555e 3845
6ed8eeff 3846 t->display_info = FRAME_TERMINAL (f)->display_info.tty;
bedb9c0e 3847
ed8dad6b 3848 f->output_data.tty = t;
3224dac1
KL
3849}
3850
7cdf484b 3851/* Delete frame F's face cache, and its tty-dependent part. */
da8e1115 3852
ed8dad6b 3853static void
9f215d25 3854tty_free_frame_resources (struct frame *f)
3224dac1 3855{
9c253307 3856 eassert (FRAME_TERMCAP_P (f));
5a80236f 3857 free_frame_faces (f);
ed8dad6b 3858 xfree (f->output_data.tty);
28d440ab
KL
3859}
3860
89ba96f4
EZ
3861#else /* MSDOS */
3862
7cdf484b 3863/* Delete frame F's face cache. */
89ba96f4
EZ
3864
3865static void
3866tty_free_frame_resources (struct frame *f)
3867{
9c253307 3868 eassert (FRAME_TERMCAP_P (f) || FRAME_MSDOS_P (f));
5a80236f 3869 free_frame_faces (f);
89ba96f4
EZ
3870}
3871#endif /* MSDOS */
ed8dad6b 3872\f
47cc8819 3873/* Reset the hooks in TERMINAL. */
ed8dad6b 3874
4a665758
KL
3875static void
3876clear_tty_hooks (struct terminal *terminal)
3877{
3878 terminal->rif = 0;
3879 terminal->cursor_to_hook = 0;
3880 terminal->raw_cursor_to_hook = 0;
3881 terminal->clear_to_end_hook = 0;
3882 terminal->clear_frame_hook = 0;
3883 terminal->clear_end_of_line_hook = 0;
3884 terminal->ins_del_lines_hook = 0;
3885 terminal->insert_glyphs_hook = 0;
3886 terminal->write_glyphs_hook = 0;
3887 terminal->delete_glyphs_hook = 0;
3888 terminal->ring_bell_hook = 0;
3889 terminal->reset_terminal_modes_hook = 0;
3890 terminal->set_terminal_modes_hook = 0;
3891 terminal->update_begin_hook = 0;
3892 terminal->update_end_hook = 0;
3893 terminal->set_terminal_window_hook = 0;
3894 terminal->mouse_position_hook = 0;
3895 terminal->frame_rehighlight_hook = 0;
3896 terminal->frame_raise_lower_hook = 0;
974b73e8 3897 terminal->fullscreen_hook = 0;
4a665758
KL
3898 terminal->set_vertical_scroll_bar_hook = 0;
3899 terminal->condemn_scroll_bars_hook = 0;
3900 terminal->redeem_scroll_bar_hook = 0;
3901 terminal->judge_scroll_bars_hook = 0;
3902 terminal->read_socket_hook = 0;
3903 terminal->frame_up_to_date_hook = 0;
3904
3905 /* Leave these two set, or suspended frames are not deleted
3906 correctly. */
9f215d25 3907 terminal->delete_frame_hook = &tty_free_frame_resources;
4a665758
KL
3908 terminal->delete_terminal_hook = &delete_tty;
3909}
3910
47cc8819
DN
3911/* Initialize hooks in TERMINAL with the values needed for a tty. */
3912
4a665758
KL
3913static void
3914set_tty_hooks (struct terminal *terminal)
3915{
3916 terminal->rif = 0; /* ttys don't support window-based redisplay. */
3917
3918 terminal->cursor_to_hook = &tty_cursor_to;
3919 terminal->raw_cursor_to_hook = &tty_raw_cursor_to;
3920
3921 terminal->clear_to_end_hook = &tty_clear_to_end;
3922 terminal->clear_frame_hook = &tty_clear_frame;
3923 terminal->clear_end_of_line_hook = &tty_clear_end_of_line;
3924
3925 terminal->ins_del_lines_hook = &tty_ins_del_lines;
3926
3927 terminal->insert_glyphs_hook = &tty_insert_glyphs;
3928 terminal->write_glyphs_hook = &tty_write_glyphs;
3929 terminal->delete_glyphs_hook = &tty_delete_glyphs;
3930
3931 terminal->ring_bell_hook = &tty_ring_bell;
f4d953fc 3932
4a665758
KL
3933 terminal->reset_terminal_modes_hook = &tty_reset_terminal_modes;
3934 terminal->set_terminal_modes_hook = &tty_set_terminal_modes;
3935 terminal->update_begin_hook = 0; /* Not needed. */
3936 terminal->update_end_hook = &tty_update_end;
3937 terminal->set_terminal_window_hook = &tty_set_terminal_window;
3938
3939 terminal->mouse_position_hook = 0; /* Not needed. */
3940 terminal->frame_rehighlight_hook = 0; /* Not needed. */
3941 terminal->frame_raise_lower_hook = 0; /* Not needed. */
3942
3943 terminal->set_vertical_scroll_bar_hook = 0; /* Not needed. */
3944 terminal->condemn_scroll_bars_hook = 0; /* Not needed. */
3945 terminal->redeem_scroll_bar_hook = 0; /* Not needed. */
3946 terminal->judge_scroll_bars_hook = 0; /* Not needed. */
3947
3948 terminal->read_socket_hook = &tty_read_avail_input; /* keyboard.c */
3949 terminal->frame_up_to_date_hook = 0; /* Not needed. */
f4d953fc 3950
9f215d25 3951 terminal->delete_frame_hook = &tty_free_frame_resources;
4a665758
KL
3952 terminal->delete_terminal_hook = &delete_tty;
3953}
3954
b8956427 3955/* If FD is the controlling terminal, drop it. */
ed8dad6b 3956static void
03a1d6bd
KL
3957dissociate_if_controlling_tty (int fd)
3958{
b8956427
PE
3959 /* If tcgetpgrp succeeds, fd is the controlling terminal,
3960 so dissociate it by invoking setsid. */
908589fd 3961 if (tcgetpgrp (fd) >= 0 && setsid () < 0)
b8956427
PE
3962 {
3963#ifdef TIOCNOTTY
3964 /* setsid failed, presumably because Emacs is already a process
3965 group leader. Fall back on the obsolescent way to dissociate
3966 a controlling tty. */
3967 block_tty_out_signal ();
3968 ioctl (fd, TIOCNOTTY, 0);
3969 unblock_tty_out_signal ();
3970#endif
3971 }
03a1d6bd
KL
3972}
3973
3224dac1
KL
3974/* Create a termcap display on the tty device with the given name and
3975 type.
3976
ab797f65 3977 If NAME is NULL, then use the controlling tty, i.e., "/dev/tty".
3224dac1
KL
3978 Otherwise NAME should be a path to the tty device file,
3979 e.g. "/dev/pts/7".
28d440ab 3980
3224dac1
KL
3981 TERMINAL_TYPE is the termcap type of the device, e.g. "vt100".
3982
a104f656 3983 If MUST_SUCCEED is true, then all errors are fatal. */
da8e1115 3984
6ed8eeff 3985struct terminal *
653d4f43 3986init_tty (const char *name, const char *terminal_type, bool must_succeed)
08a24c47 3987{
1fc8eb33 3988 char *area;
08a24c47 3989 char **address = &area;
08a24c47 3990 int status;
59b3194c
KL
3991 struct tty_display_info *tty = NULL;
3992 struct terminal *terminal = NULL;
a104f656 3993 bool ctty = false; /* True if asked to open controlling tty. */
28d440ab 3994
3224dac1 3995 if (!terminal_type)
d31eee5e 3996 maybe_fatal (must_succeed, 0,
3224dac1
KL
3997 "Unknown terminal type",
3998 "Unknown terminal type");
b6660415 3999
ab797f65 4000 if (name == NULL)
78048085
EZ
4001 name = DEV_TTY;
4002 if (!strcmp (name, DEV_TTY))
ab797f65
KL
4003 ctty = 1;
4004
6ed8eeff
KL
4005 /* If we already have a terminal on the given device, use that. If
4006 all such terminals are suspended, create a new one instead. */
a4c6993d 4007 /* XXX Perhaps this should be made explicit by having init_tty
6ed8eeff 4008 always create a new terminal and separating terminal and frame
b6660415 4009 creation on Lisp level. */
6ed8eeff
KL
4010 terminal = get_named_tty (name);
4011 if (terminal)
4012 return terminal;
78048085 4013
6ed8eeff 4014 terminal = create_terminal ();
84704c5c
EZ
4015#ifdef MSDOS
4016 if (been_here > 0)
762b15be 4017 maybe_fatal (0, 0, "Attempt to create another terminal %s", "",
84704c5c
EZ
4018 name, "");
4019 been_here = 1;
4020 tty = &the_only_display_info;
4021#else
38182d90 4022 tty = xzalloc (sizeof *tty);
84704c5c 4023#endif
c650a5de 4024 tty->top_frame = Qnil;
3224dac1
KL
4025 tty->next = tty_list;
4026 tty_list = tty;
428a555e 4027
6ed8eeff
KL
4028 terminal->type = output_termcap;
4029 terminal->display_info.tty = tty;
4030 tty->terminal = terminal;
28d440ab 4031
38182d90 4032 tty->Wcm = xmalloc (sizeof *tty->Wcm);
7b00d185 4033 Wcm_clear (tty);
daf01701 4034
dce4c2ac
DN
4035 encode_terminal_src_size = 0;
4036 encode_terminal_dst_size = 0;
4037
51b59d79 4038
84704c5c 4039#ifndef DOS_NT
4a665758 4040 set_tty_hooks (terminal);
78048085 4041
59b3194c 4042 {
49cdacda 4043 /* Open the terminal device. */
0c72d684 4044
49cdacda
PE
4045 /* If !ctty, don't recognize it as our controlling terminal, and
4046 don't make it the controlling tty if we don't have one now.
4047
4048 Alas, O_IGNORE_CTTY is a GNU extension that seems to be only
4049 defined on Hurd. On other systems, we need to explicitly
4050 dissociate ourselves from the controlling tty when we want to
4051 open a frame on the same terminal. */
4052 int flags = O_RDWR | O_NOCTTY | (ctty ? 0 : O_IGNORE_CTTY);
4053 int fd = emacs_open (name, flags, 0);
ef30e638 4054 tty->input = tty->output = fd < 0 || ! isatty (fd) ? 0 : fdopen (fd, "w+");
0c72d684 4055
ef30e638 4056 if (! tty->input)
59b3194c 4057 {
ef30e638
PE
4058 char const *diagnostic
4059 = tty->input ? "Not a tty device: %s" : "Could not open file: %s";
4060 emacs_close (fd);
4061 maybe_fatal (must_succeed, terminal, diagnostic, diagnostic, name);
59b3194c 4062 }
0c72d684 4063
ef30e638
PE
4064 tty->name = xstrdup (name);
4065 terminal->name = xstrdup (name);
4066
49cdacda 4067 if (!O_IGNORE_CTTY && !ctty)
03a1d6bd 4068 dissociate_if_controlling_tty (fd);
59b3194c 4069 }
78048085 4070
28d7d09f 4071 tty->type = xstrdup (terminal_type);
28d440ab 4072
819b8f00 4073 add_keyboard_wait_descriptor (fileno (tty->input));
08a24c47 4074
6548cf00 4075 Wcm_clear (tty);
08a24c47 4076
03a1d6bd 4077 /* On some systems, tgetent tries to access the controlling
a104f656 4078 terminal. */
b8956427
PE
4079 block_tty_out_signal ();
4080 status = tgetent (tty->termcap_term_buffer, terminal_type);
1fc8eb33
PE
4081 if (tty->termcap_term_buffer[TERMCAP_BUFFER_SIZE - 1])
4082 emacs_abort ();
b8956427 4083 unblock_tty_out_signal ();
78048085 4084
08a24c47 4085 if (status < 0)
b0347178
KH
4086 {
4087#ifdef TERMINFO
d31eee5e 4088 maybe_fatal (must_succeed, terminal,
3224dac1
KL
4089 "Cannot open terminfo database file",
4090 "Cannot open terminfo database file");
b0347178 4091#else
d31eee5e 4092 maybe_fatal (must_succeed, terminal,
3224dac1
KL
4093 "Cannot open termcap database file",
4094 "Cannot open termcap database file");
b0347178
KH
4095#endif
4096 }
08a24c47 4097 if (status == 0)
b0347178 4098 {
d31eee5e 4099 maybe_fatal (must_succeed, terminal,
3224dac1
KL
4100 "Terminal type %s is not defined",
4101 "Terminal type %s is not defined.\n\
b0347178
KH
4102If that is not the actual type of terminal you have,\n\
4103use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
84164a0d
SM
4104`setenv TERM ...') to specify the correct type. It may be necessary\n"
4105#ifdef TERMINFO
4106"to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
b0347178 4107#else
84164a0d 4108"to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
b0347178 4109#endif
84164a0d 4110 terminal_type);
b0347178 4111 }
6b61353c 4112
1fc8eb33 4113 area = tty->termcap_strings_buffer;
fca177d4
KL
4114 tty->TS_ins_line = tgetstr ("al", address);
4115 tty->TS_ins_multi_lines = tgetstr ("AL", address);
4116 tty->TS_bell = tgetstr ("bl", address);
6548cf00 4117 BackTab (tty) = tgetstr ("bt", address);
fca177d4
KL
4118 tty->TS_clr_to_bottom = tgetstr ("cd", address);
4119 tty->TS_clr_line = tgetstr ("ce", address);
4120 tty->TS_clr_frame = tgetstr ("cl", address);
6548cf00
KL
4121 ColPosition (tty) = NULL; /* tgetstr ("ch", address); */
4122 AbsPosition (tty) = tgetstr ("cm", address);
4123 CR (tty) = tgetstr ("cr", address);
fca177d4
KL
4124 tty->TS_set_scroll_region = tgetstr ("cs", address);
4125 tty->TS_set_scroll_region_1 = tgetstr ("cS", address);
6548cf00 4126 RowPosition (tty) = tgetstr ("cv", address);
fca177d4
KL
4127 tty->TS_del_char = tgetstr ("dc", address);
4128 tty->TS_del_multi_chars = tgetstr ("DC", address);
4129 tty->TS_del_line = tgetstr ("dl", address);
4130 tty->TS_del_multi_lines = tgetstr ("DL", address);
4131 tty->TS_delete_mode = tgetstr ("dm", address);
4132 tty->TS_end_delete_mode = tgetstr ("ed", address);
4133 tty->TS_end_insert_mode = tgetstr ("ei", address);
6548cf00 4134 Home (tty) = tgetstr ("ho", address);
fca177d4
KL
4135 tty->TS_ins_char = tgetstr ("ic", address);
4136 tty->TS_ins_multi_chars = tgetstr ("IC", address);
4137 tty->TS_insert_mode = tgetstr ("im", address);
4138 tty->TS_pad_inserted_char = tgetstr ("ip", address);
4139 tty->TS_end_keypad_mode = tgetstr ("ke", address);
4140 tty->TS_keypad_mode = tgetstr ("ks", address);
6548cf00
KL
4141 LastLine (tty) = tgetstr ("ll", address);
4142 Right (tty) = tgetstr ("nd", address);
4143 Down (tty) = tgetstr ("do", address);
4144 if (!Down (tty))
a104f656 4145 Down (tty) = tgetstr ("nl", address); /* Obsolete name for "do". */
08a24c47 4146 if (tgetflag ("bs"))
a104f656
SM
4147 Left (tty) = "\b"; /* Can't possibly be longer! */
4148 else /* (Actually, "bs" is obsolete...) */
6548cf00
KL
4149 Left (tty) = tgetstr ("le", address);
4150 if (!Left (tty))
a104f656 4151 Left (tty) = tgetstr ("bc", address); /* Obsolete name for "le". */
fca177d4
KL
4152 tty->TS_pad_char = tgetstr ("pc", address);
4153 tty->TS_repeat = tgetstr ("rp", address);
4154 tty->TS_end_standout_mode = tgetstr ("se", address);
4155 tty->TS_fwd_scroll = tgetstr ("sf", address);
4156 tty->TS_standout_mode = tgetstr ("so", address);
4157 tty->TS_rev_scroll = tgetstr ("sr", address);
6548cf00 4158 tty->Wcm->cm_tab = tgetstr ("ta", address);
fca177d4
KL
4159 tty->TS_end_termcap_modes = tgetstr ("te", address);
4160 tty->TS_termcap_modes = tgetstr ("ti", address);
6548cf00 4161 Up (tty) = tgetstr ("up", address);
fca177d4
KL
4162 tty->TS_visible_bell = tgetstr ("vb", address);
4163 tty->TS_cursor_normal = tgetstr ("ve", address);
4164 tty->TS_cursor_visible = tgetstr ("vs", address);
4165 tty->TS_cursor_invisible = tgetstr ("vi", address);
4166 tty->TS_set_window = tgetstr ("wi", address);
4167
4168 tty->TS_enter_underline_mode = tgetstr ("us", address);
4169 tty->TS_exit_underline_mode = tgetstr ("ue", address);
4170 tty->TS_enter_bold_mode = tgetstr ("md", address);
cd4eb164 4171 tty->TS_enter_italic_mode = tgetstr ("ZH", address);
fca177d4 4172 tty->TS_enter_dim_mode = tgetstr ("mh", address);
fca177d4
KL
4173 tty->TS_enter_reverse_mode = tgetstr ("mr", address);
4174 tty->TS_enter_alt_charset_mode = tgetstr ("as", address);
4175 tty->TS_exit_alt_charset_mode = tgetstr ("ae", address);
4176 tty->TS_exit_attribute_mode = tgetstr ("me", address);
177c0ea7 4177
6548cf00
KL
4178 MultiUp (tty) = tgetstr ("UP", address);
4179 MultiDown (tty) = tgetstr ("DO", address);
4180 MultiLeft (tty) = tgetstr ("LE", address);
4181 MultiRight (tty) = tgetstr ("RI", address);
08a24c47 4182
5c32d3f2 4183 /* SVr4/ANSI color support. If "op" isn't available, don't support
e7f90eab
GM
4184 color because we can't switch back to the default foreground and
4185 background. */
fca177d4
KL
4186 tty->TS_orig_pair = tgetstr ("op", address);
4187 if (tty->TS_orig_pair)
a168702a 4188 {
fca177d4
KL
4189 tty->TS_set_foreground = tgetstr ("AF", address);
4190 tty->TS_set_background = tgetstr ("AB", address);
4191 if (!tty->TS_set_foreground)
e7f90eab
GM
4192 {
4193 /* SVr4. */
fca177d4
KL
4194 tty->TS_set_foreground = tgetstr ("Sf", address);
4195 tty->TS_set_background = tgetstr ("Sb", address);
e7f90eab 4196 }
177c0ea7 4197
fca177d4
KL
4198 tty->TN_max_colors = tgetnum ("Co");
4199 tty->TN_max_pairs = tgetnum ("pa");
177c0ea7 4200
fca177d4
KL
4201 tty->TN_no_color_video = tgetnum ("NC");
4202 if (tty->TN_no_color_video == -1)
4203 tty->TN_no_color_video = 0;
a168702a 4204 }
a168702a 4205
fca177d4 4206 tty_default_color_capabilities (tty, 1);
ace28297 4207
6548cf00 4208 MagicWrap (tty) = tgetflag ("xn");
e4058338
KH
4209 /* Since we make MagicWrap terminals look like AutoWrap, we need to have
4210 the former flag imply the latter. */
6548cf00 4211 AutoWrap (tty) = MagicWrap (tty) || tgetflag ("am");
77e3b1b7 4212 tty->memory_below_frame = tgetflag ("db");
fca177d4 4213 tty->TF_hazeltine = tgetflag ("hz");
77e3b1b7 4214 tty->must_write_spaces = tgetflag ("in");
fca177d4
KL
4215 tty->meta_key = tgetflag ("km") || tgetflag ("MT");
4216 tty->TF_insmode_motion = tgetflag ("mi");
4217 tty->TF_standout_motion = tgetflag ("ms");
4218 tty->TF_underscore = tgetflag ("ul");
4219 tty->TF_teleray = tgetflag ("xt");
08a24c47 4220
dce4c2ac
DN
4221#else /* DOS_NT */
4222#ifdef WINDOWSNT
4223 {
4224 struct frame *f = XFRAME (selected_frame);
9337e206 4225 int height, width;
dce4c2ac 4226
9337e206 4227 initialize_w32_display (terminal, &width, &height);
dce4c2ac 4228
9337e206
EZ
4229 FrameRows (tty) = height;
4230 FrameCols (tty) = width;
4231 tty->specified_window = height;
dce4c2ac 4232
dce4c2ac 4233 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = vertical_scroll_bar_none;
77e3b1b7 4234 tty->char_ins_del_ok = 1;
dce4c2ac
DN
4235 baud_rate = 19200;
4236 }
4237#else /* MSDOS */
4238 {
4239 int height, width;
4240 if (strcmp (terminal_type, "internal") == 0)
4241 terminal->type = output_msdos_raw;
4242 initialize_msdos_display (terminal);
4243
4244 get_tty_size (fileno (tty->input), &width, &height);
4245 FrameCols (tty) = width;
4246 FrameRows (tty) = height;
77e3b1b7 4247 tty->char_ins_del_ok = 0;
dce4c2ac
DN
4248 init_baud_rate (fileno (tty->input));
4249 }
4250#endif /* MSDOS */
4251 tty->output = stdout;
4252 tty->input = stdin;
4253 /* The following two are inaccessible from w32console.c. */
4254 terminal->delete_frame_hook = &tty_free_frame_resources;
4255 terminal->delete_terminal_hook = &delete_tty;
4256
4257 tty->name = xstrdup (name);
4258 terminal->name = xstrdup (name);
4259 tty->type = xstrdup (terminal_type);
4260
4261 add_keyboard_wait_descriptor (0);
4262
dce4c2ac
DN
4263 tty->delete_in_insert_mode = 1;
4264
4265 UseTabs (tty) = 0;
77e3b1b7 4266 tty->scroll_region_ok = 0;
dce4c2ac
DN
4267
4268 /* Seems to insert lines when it's not supposed to, messing up the
4269 display. In doing a trace, it didn't seem to be called much, so I
4270 don't think we're losing anything by turning it off. */
77e3b1b7 4271 tty->line_ins_del_ok = 0;
dce4c2ac 4272
a104f656 4273 tty->TN_max_colors = 16; /* Must be non-zero for tty-display-color-p. */
dce4c2ac
DN
4274#endif /* DOS_NT */
4275
6bc8cd65
JB
4276#ifdef HAVE_GPM
4277 terminal->mouse_position_hook = term_mouse_position;
4278 tty->mouse_highlight.mouse_face_window = Qnil;
4279#endif
4280
1afcba63 4281 terminal->kboard = allocate_kboard (Qnil);
6ed8eeff 4282 terminal->kboard->reference_count++;
e7cf0fa0
KL
4283 /* Don't let the initial kboard remain current longer than necessary.
4284 That would cause problems if a file loaded on startup tries to
4285 prompt in the mini-buffer. */
4286 if (current_kboard == initial_kboard)
6ed8eeff 4287 current_kboard = terminal->kboard;
84704c5c 4288#ifndef DOS_NT
6ed8eeff 4289 term_get_fkeys (address, terminal->kboard);
5c2c7893 4290
ff11dfa1 4291 /* Get frame size from system, or else from termcap. */
3b12ce12
RS
4292 {
4293 int height, width;
0b0d3e0b 4294 get_tty_size (fileno (tty->input), &width, &height);
0a125897
KL
4295 FrameCols (tty) = width;
4296 FrameRows (tty) = height;
3b12ce12
RS
4297 }
4298
0a125897
KL
4299 if (FrameCols (tty) <= 0)
4300 FrameCols (tty) = tgetnum ("co");
4301 if (FrameRows (tty) <= 0)
4302 FrameRows (tty) = tgetnum ("li");
177c0ea7 4303
0a125897 4304 if (FrameRows (tty) < 3 || FrameCols (tty) < 3)
d31eee5e 4305 maybe_fatal (must_succeed, terminal,
b3ffc17c 4306 "Screen size %dx%d is too small",
3224dac1 4307 "Screen size %dx%d is too small",
0a125897 4308 FrameCols (tty), FrameRows (tty));
ee7a2de4 4309
6548cf00 4310 TabWidth (tty) = tgetnum ("tw");
08a24c47 4311
fca177d4
KL
4312 if (!tty->TS_bell)
4313 tty->TS_bell = "\07";
08a24c47 4314
fca177d4
KL
4315 if (!tty->TS_fwd_scroll)
4316 tty->TS_fwd_scroll = Down (tty);
08a24c47 4317
fca177d4 4318 PC = tty->TS_pad_char ? *tty->TS_pad_char : 0;
08a24c47 4319
6548cf00
KL
4320 if (TabWidth (tty) < 0)
4321 TabWidth (tty) = 8;
177c0ea7 4322
08a24c47
JB
4323/* Turned off since /etc/termcap seems to have :ta= for most terminals
4324 and newer termcap doc does not seem to say there is a default.
6548cf00
KL
4325 if (!tty->Wcm->cm_tab)
4326 tty->Wcm->cm_tab = "\t";
08a24c47
JB
4327*/
4328
54800acb
MB
4329 /* We don't support standout modes that use `magic cookies', so
4330 turn off any that do. */
fca177d4 4331 if (tty->TS_standout_mode && tgetnum ("sg") >= 0)
54800acb 4332 {
fca177d4
KL
4333 tty->TS_standout_mode = 0;
4334 tty->TS_end_standout_mode = 0;
54800acb 4335 }
fca177d4 4336 if (tty->TS_enter_underline_mode && tgetnum ("ug") >= 0)
54800acb 4337 {
fca177d4
KL
4338 tty->TS_enter_underline_mode = 0;
4339 tty->TS_exit_underline_mode = 0;
54800acb
MB
4340 }
4341
4342 /* If there's no standout mode, try to use underlining instead. */
fca177d4 4343 if (tty->TS_standout_mode == 0)
08a24c47 4344 {
fca177d4
KL
4345 tty->TS_standout_mode = tty->TS_enter_underline_mode;
4346 tty->TS_end_standout_mode = tty->TS_exit_underline_mode;
08a24c47
JB
4347 }
4348
afd359c4
RS
4349 /* If no `se' string, try using a `me' string instead.
4350 If that fails, we can't use standout mode at all. */
fca177d4 4351 if (tty->TS_end_standout_mode == 0)
afd359c4 4352 {
e4bfb3b6 4353 char *s = tgetstr ("me", address);
afd359c4 4354 if (s != 0)
fca177d4 4355 tty->TS_end_standout_mode = s;
afd359c4 4356 else
fca177d4 4357 tty->TS_standout_mode = 0;
afd359c4
RS
4358 }
4359
fca177d4 4360 if (tty->TF_teleray)
08a24c47 4361 {
6548cf00 4362 tty->Wcm->cm_tab = 0;
54800acb 4363 /* We can't support standout mode, because it uses magic cookies. */
fca177d4 4364 tty->TS_standout_mode = 0;
a104f656 4365 /* But that means we cannot rely on ^M to go to column zero! */
6548cf00 4366 CR (tty) = 0;
a104f656
SM
4367 /* LF can't be trusted either -- can alter hpos. */
4368 /* If move at column 0 thru a line with TS_standout_mode. */
6548cf00 4369 Down (tty) = 0;
08a24c47
JB
4370 }
4371
0a125897 4372 tty->specified_window = FrameRows (tty);
08a24c47 4373
a104f656 4374 if (Wcm_init (tty) == -1) /* Can't do cursor motion. */
3224dac1 4375 {
d31eee5e 4376 maybe_fatal (must_succeed, terminal,
3224dac1 4377 "Terminal type \"%s\" is not powerful enough to run Emacs",
3224dac1 4378 "Terminal type \"%s\" is not powerful enough to run Emacs.\n\
37dad45a
RS
4379It lacks the ability to position the cursor.\n\
4380If that is not the actual type of terminal you have,\n\
4381use the Bourne shell command `TERM=... export TERM' (C-shell:\n\
84164a0d
SM
4382`setenv TERM ...') to specify the correct type. It may be necessary\n"
4383# ifdef TERMINFO
4384"to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.",
37dad45a 4385# else /* TERMCAP */
84164a0d 4386"to do `unset TERMCAP' (C-shell: `unsetenv TERMCAP') as well.",
37dad45a 4387# endif /* TERMINFO */
3224dac1 4388 terminal_type);
fca177d4 4389 }
daf01701 4390
0a125897 4391 if (FrameRows (tty) <= 0 || FrameCols (tty) <= 0)
d31eee5e 4392 maybe_fatal (must_succeed, terminal,
3224dac1
KL
4393 "Could not determine the frame size",
4394 "Could not determine the frame size");
08a24c47 4395
fca177d4
KL
4396 tty->delete_in_insert_mode
4397 = tty->TS_delete_mode && tty->TS_insert_mode
4398 && !strcmp (tty->TS_delete_mode, tty->TS_insert_mode);
08a24c47 4399
0b0d3e0b 4400 UseTabs (tty) = tabs_safe_p (fileno (tty->input)) && TabWidth (tty) == 8;
08a24c47 4401
77e3b1b7 4402 tty->scroll_region_ok
6548cf00 4403 = (tty->Wcm->cm_abs
fca177d4 4404 && (tty->TS_set_window || tty->TS_set_scroll_region || tty->TS_set_scroll_region_1));
08a24c47 4405
77e3b1b7 4406 tty->line_ins_del_ok
fca177d4
KL
4407 = (((tty->TS_ins_line || tty->TS_ins_multi_lines)
4408 && (tty->TS_del_line || tty->TS_del_multi_lines))
77e3b1b7 4409 || (tty->scroll_region_ok
fca177d4 4410 && tty->TS_fwd_scroll && tty->TS_rev_scroll));
08a24c47 4411
77e3b1b7 4412 tty->char_ins_del_ok
fca177d4
KL
4413 = ((tty->TS_ins_char || tty->TS_insert_mode
4414 || tty->TS_pad_inserted_char || tty->TS_ins_multi_chars)
4415 && (tty->TS_del_char || tty->TS_del_multi_chars));
08a24c47 4416
0b0d3e0b 4417 init_baud_rate (fileno (tty->input));
20a558dc 4418
84704c5c 4419#endif /* not DOS_NT */
635e3b29 4420
0a125897
KL
4421 /* Init system terminal modes (RAW or CBREAK, etc.). */
4422 init_sys_modes (tty);
daf01701 4423
6ed8eeff 4424 return terminal;
08a24c47
JB
4425}
4426
b3ffc17c
DN
4427
4428static void
4429vfatal (const char *str, va_list ap)
4430{
4431 fprintf (stderr, "emacs: ");
4432 vfprintf (stderr, str, ap);
4433 if (!(strlen (str) > 0 && str[strlen (str) - 1] == '\n'))
4434 fprintf (stderr, "\n");
b3ffc17c
DN
4435 fflush (stderr);
4436 exit (1);
4437}
4438
4439
a4c6993d 4440/* Auxiliary error-handling function for init_tty.
d31eee5e 4441 Delete TERMINAL, then call error or fatal with str1 or str2,
653d4f43 4442 respectively, according to whether MUST_SUCCEED is true. */
6b61353c 4443
3224dac1 4444static void
653d4f43 4445maybe_fatal (bool must_succeed, struct terminal *terminal,
b3ffc17c 4446 const char *str1, const char *str2, ...)
3224dac1 4447{
b3ffc17c
DN
4448 va_list ap;
4449 va_start (ap, str2);
6ed8eeff
KL
4450 if (terminal)
4451 delete_tty (terminal);
f4d953fc 4452
3224dac1 4453 if (must_succeed)
b3ffc17c 4454 vfatal (str2, ap);
3224dac1 4455 else
b3ffc17c 4456 verror (str1, ap);
08a24c47
JB
4457}
4458
dfcf069d 4459void
7c401d15 4460fatal (const char *str, ...)
08a24c47 4461{
7c401d15
DN
4462 va_list ap;
4463 va_start (ap, str);
b3ffc17c 4464 vfatal (str, ap);
08a24c47 4465}
07c57952 4466
819b8f00
KL
4467\f
4468
6ed8eeff 4469/* Delete the given tty terminal, closing all frames on it. */
da8e1115 4470
ed8dad6b 4471static void
6ed8eeff 4472delete_tty (struct terminal *terminal)
072d84a6 4473{
428a555e 4474 struct tty_display_info *tty;
f4d953fc 4475
e2749141 4476 /* Protect against recursive calls. delete_frame in
ab797f65 4477 delete_terminal calls us back when it deletes our last frame. */
59a7bc63 4478 if (!terminal->name)
0a125897 4479 return;
fca177d4 4480
9c253307 4481 eassert (terminal->type == output_termcap);
428a555e 4482
6ed8eeff 4483 tty = terminal->display_info.tty;
f4d953fc 4484
fca177d4
KL
4485 if (tty == tty_list)
4486 tty_list = tty->next;
4487 else
4488 {
28d7d09f 4489 struct tty_display_info *p;
fca177d4
KL
4490 for (p = tty_list; p && p->next != tty; p = p->next)
4491 ;
4492
4493 if (! p)
4494 /* This should not happen. */
1088b922 4495 emacs_abort ();
fca177d4 4496
0a125897
KL
4497 p->next = tty->next;
4498 tty->next = 0;
fca177d4
KL
4499 }
4500
7e59217d 4501 /* reset_sys_modes needs a valid device, so this call needs to be
6ed8eeff 4502 before delete_terminal. */
04c3243c 4503 reset_sys_modes (tty);
fca177d4 4504
6ed8eeff 4505 delete_terminal (terminal);
3224dac1 4506
70fdbb46
JM
4507 xfree (tty->name);
4508 xfree (tty->type);
daf01701 4509
fca177d4 4510 if (tty->input)
819b8f00
KL
4511 {
4512 delete_keyboard_wait_descriptor (fileno (tty->input));
4513 if (tty->input != stdin)
4514 fclose (tty->input);
4515 }
4516 if (tty->output && tty->output != stdout && tty->output != tty->input)
fca177d4
KL
4517 fclose (tty->output);
4518 if (tty->termscript)
4519 fclose (tty->termscript);
daf01701 4520
70fdbb46
JM
4521 xfree (tty->old_tty);
4522 xfree (tty->Wcm);
fca177d4 4523 xfree (tty);
fca177d4
KL
4524}
4525
dfcf069d 4526void
d3da34e0 4527syms_of_term (void)
07c57952 4528{
29208e82 4529 DEFVAR_BOOL ("system-uses-terminfo", system_uses_terminfo,
7ee72033 4530 doc: /* Non-nil means the system uses terminfo rather than termcap.
228299fa 4531This variable can be used by terminal emulator packages. */);
07c57952
KH
4532#ifdef TERMINFO
4533 system_uses_terminfo = 1;
4534#else
4535 system_uses_terminfo = 0;
4536#endif
c291d9ef 4537
29208e82 4538 DEFVAR_LISP ("suspend-tty-functions", Vsuspend_tty_functions,
e5d9c0d1 4539 doc: /* Functions run after suspending a tty.
fdc496e7 4540The functions are run with one argument, the terminal object to be suspended.
0b0d3e0b 4541See `suspend-tty'. */);
e4019195 4542 Vsuspend_tty_functions = Qnil;
0b0d3e0b
KL
4543
4544
29208e82 4545 DEFVAR_LISP ("resume-tty-functions", Vresume_tty_functions,
e5d9c0d1 4546 doc: /* Functions run after resuming a tty.
fdc496e7 4547The functions are run with one argument, the terminal object that was revived.
0b0d3e0b 4548See `resume-tty'. */);
e4019195 4549 Vresume_tty_functions = Qnil;
a168702a 4550
29208e82 4551 DEFVAR_BOOL ("visible-cursor", visible_cursor,
0db017c0
SM
4552 doc: /* Non-nil means to make the cursor very visible.
4553This only has an effect when running in a text terminal.
4554What means \"very visible\" is up to your terminal. It may make the cursor
4555bigger, or it may make it blink, or it may do nothing at all. */);
4556 visible_cursor = 1;
4557
a168702a 4558 defsubr (&Stty_display_color_p);
bfa62f96 4559 defsubr (&Stty_display_color_cells);
072d84a6 4560 defsubr (&Stty_no_underline);
6ed8eeff
KL
4561 defsubr (&Stty_type);
4562 defsubr (&Scontrolling_tty_p);
c6bf3022 4563 defsubr (&Stty_top_frame);
0b0d3e0b
KL
4564 defsubr (&Ssuspend_tty);
4565 defsubr (&Sresume_tty);
7e5a23bd 4566#ifdef HAVE_GPM
6178ce5e
SM
4567 defsubr (&Sgpm_mouse_start);
4568 defsubr (&Sgpm_mouse_stop);
7e5a23bd 4569#endif /* HAVE_GPM */
3a7c5d40 4570
84704c5c 4571#ifndef DOS_NT
3a7c5d40
CY
4572 default_orig_pair = NULL;
4573 default_set_foreground = NULL;
4574 default_set_background = NULL;
84704c5c 4575#endif /* !DOS_NT */
d31eee5e
CY
4576
4577 encode_terminal_src = NULL;
4578 encode_terminal_dst = NULL;
f0177f86 4579
bf6b4923 4580#ifndef MSDOS
df782309
EZ
4581 DEFSYM (Qtty_menu_next_item, "tty-menu-next-item");
4582 DEFSYM (Qtty_menu_prev_item, "tty-menu-prev-item");
4583 DEFSYM (Qtty_menu_next_menu, "tty-menu-next-menu");
4584 DEFSYM (Qtty_menu_prev_menu, "tty-menu-prev-menu");
4585 DEFSYM (Qtty_menu_select, "tty-menu-select");
4586 DEFSYM (Qtty_menu_ignore, "tty-menu-ignore");
4587 DEFSYM (Qtty_menu_exit, "tty-menu-exit");
e648f699 4588 DEFSYM (Qtty_menu_mouse_movement, "tty-menu-mouse-movement");
df782309 4589 DEFSYM (Qtty_menu_navigation_map, "tty-menu-navigation-map");
bf6b4923 4590#endif
07c57952 4591}