input.c revision f2e35a3a
1/* $XTermId: input.c,v 1.365 2020/10/12 19:21:53 tom Exp $ */
2
3/*
4 * Copyright 1999-2019,2020 by Thomas E. Dickey
5 *
6 *                         All Rights Reserved
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the
10 * "Software"), to deal in the Software without restriction, including
11 * without limitation the rights to use, copy, modify, merge, publish,
12 * distribute, sublicense, and/or sell copies of the Software, and to
13 * permit persons to whom the Software is furnished to do so, subject to
14 * the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included
17 * in all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
20 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22 * IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
23 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 *
27 * Except as contained in this notice, the name(s) of the above copyright
28 * holders shall not be used in advertising or otherwise to promote the
29 * sale, use or other dealings in this Software without prior written
30 * authorization.
31 *
32 *
33 * Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
34 *
35 *                         All Rights Reserved
36 *
37 * Permission to use, copy, modify, and distribute this software and its
38 * documentation for any purpose and without fee is hereby granted,
39 * provided that the above copyright notice appear in all copies and that
40 * both that copyright notice and this permission notice appear in
41 * supporting documentation, and that the name of Digital Equipment
42 * Corporation not be used in advertising or publicity pertaining to
43 * distribution of the software without specific, written prior permission.
44 *
45 *
46 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
47 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
48 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
49 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
50 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
51 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
52 * SOFTWARE.
53 */
54
55/* input.c */
56
57#include <xterm.h>
58
59#include <X11/keysym.h>
60
61#ifdef VMS
62#include <X11/keysymdef.h>
63#endif
64
65#if HAVE_X11_DECKEYSYM_H
66#include <X11/DECkeysym.h>
67#endif
68
69#if HAVE_X11_SUNKEYSYM_H
70#include <X11/Sunkeysym.h>
71#endif
72
73#if HAVE_X11_XF86KEYSYM_H
74#include <X11/XF86keysym.h>
75#endif
76
77#if !defined(HAVE_CONFIG_H) && defined(_X_DEPRECATED)
78#define HAVE_XKBKEYCODETOKEYSYM 1
79#endif
80
81#ifdef HAVE_XKBKEYCODETOKEYSYM
82#include <X11/XKBlib.h>
83#endif
84
85#include <X11/Xutil.h>
86#include <stdio.h>
87#include <ctype.h>
88
89#include <xutf8.h>
90
91#include <data.h>
92#include <fontutils.h>
93#include <xstrings.h>
94#include <xtermcap.h>
95
96/*
97 * Xutil.h has no macro to check for the complete set of function- and
98 * modifier-keys that might be returned.  Fake it.
99 */
100#ifdef XK_ISO_Lock
101#define IsPredefinedKey(n) ((n) >= XK_ISO_Lock && (n) <= XK_Delete)
102#else
103#define IsPredefinedKey(n) ((n) >= XK_BackSpace && (n) <= XK_Delete)
104#endif
105
106#ifdef XK_ISO_Left_Tab
107#define IsTabKey(n) ((n) == XK_Tab || (n) == XK_ISO_Left_Tab)
108#else
109#define IsTabKey(n) ((n) == XK_Tab)
110#endif
111
112#ifndef IsPrivateKeypadKey
113#define IsPrivateKeypadKey(k) (0)
114#endif
115
116#define IsBackarrowToggle(keyboard, keysym, state) \
117	((((keyboard->flags & MODE_DECBKM) == 0) \
118	    ^ ((state & ControlMask) != 0)) \
119	&& (keysym == XK_BackSpace))
120
121#define MAP(from, to) case from: result = to; break
122#define Masked(value,mask) ((value) & (unsigned) (~(mask)))
123
124#define KEYSYM_FMT "0x%04lX"	/* simplify matching <X11/keysymdef.h> */
125
126#define TEK4014_GIN(tw) (tw != 0 && TekScreenOf(tw)->TekGIN)
127
128typedef struct {
129    KeySym keysym;
130    Bool is_fkey;
131    int nbytes;
132#define STRBUFSIZE 500
133    char strbuf[STRBUFSIZE];
134} KEY_DATA;
135
136static
137const char kypd_num[] = " XXXXXXXX\tXXX\rXXXxxxxXXXXXXXXXXXXXXXXXXXXX*+,-./0123456789XXX=";
138/*                       0123456789 abc def0123456789abcdef0123456789abcdef0123456789abcd */
139static
140const char kypd_apl[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ??????abcdefghijklmnopqrstuvwxyzXXX";
141/*                       0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd */
142static
143const char curfinal[] = "HDACB  FE";
144
145static int decfuncvalue(KEY_DATA *);
146static void sunfuncvalue(ANSI *, KEY_DATA *);
147static void hpfuncvalue(ANSI *, KEY_DATA *);
148static void scofuncvalue(ANSI *, KEY_DATA *);
149
150static void
151AdjustAfterInput(XtermWidget xw)
152{
153    TScreen *screen = TScreenOf(xw);
154
155    if (screen->scrollkey && screen->topline != 0)
156	WindowScroll(xw, 0, False);
157    if (screen->marginbell) {
158	int col = screen->max_col - screen->nmarginbell;
159	if (screen->bellArmed >= 0) {
160	    if (screen->bellArmed == screen->cur_row) {
161		if (screen->cur_col >= col) {
162		    Bell(xw, XkbBI_MarginBell, 0);
163		    screen->bellArmed = -1;
164		}
165	    } else {
166		screen->bellArmed =
167		    screen->cur_col < col ? screen->cur_row : -1;
168	    }
169	} else if (screen->cur_col < col)
170	    screen->bellArmed = screen->cur_row;
171    }
172}
173
174/*
175 * Return true if the key is on the editing keypad.  This overlaps with
176 * IsCursorKey() and IsKeypadKey() and must be tested before those macros to
177 * distinguish it from them.
178 *
179 * VT220  emulation  uses  the  VT100  numeric  keypad as well as a 6-key
180 * editing keypad. Here's a picture of the VT220 editing keypad:
181 *      +--------+--------+--------+
182 *      | Find   | Insert | Remove |
183 *      +--------+--------+--------+
184 *      | Select | Prev   | Next   |
185 *      +--------+--------+--------+
186 *
187 * and the similar Sun and PC keypads:
188 *      +--------+--------+--------+
189 *      | Insert | Home   | PageUp |
190 *      +--------+--------+--------+
191 *      | Delete | End    | PageDn |
192 *      +--------+--------+--------+
193 */
194static Bool
195IsEditKeypad(XtermWidget xw, KeySym keysym)
196{
197    Bool result;
198
199    switch (keysym) {
200    case XK_Delete:
201	result = !xtermDeleteIsDEL(xw);
202	break;
203    case XK_Prior:
204    case XK_Next:
205    case XK_Insert:
206    case XK_Find:
207    case XK_Select:
208#ifdef DXK_Remove
209    case DXK_Remove:
210#endif
211	result = True;
212	break;
213    default:
214	result = False;
215	break;
216    }
217    return result;
218}
219
220/*
221 * Editing-keypad, plus other editing keys which are not included in the
222 * other macros.
223 */
224static Bool
225IsEditFunctionKey(XtermWidget xw, KeySym keysym)
226{
227    Bool result;
228
229    switch (keysym) {
230#ifdef XK_KP_Delete
231    case XK_KP_Delete:		/* editing key on numeric keypad */
232    case XK_KP_Insert:		/* editing key on numeric keypad */
233#endif
234#ifdef XK_ISO_Left_Tab
235    case XK_ISO_Left_Tab:
236#endif
237	result = True;
238	break;
239    default:
240	result = IsEditKeypad(xw, keysym);
241	break;
242    }
243    return result;
244}
245
246#if OPT_MOD_FKEYS
247#define IS_CTRL(n) ((n) < ANSI_SPA || ((n) >= 0x7f && (n) <= 0x9f))
248
249/*
250 * Return true if the keysym corresponds to one of the control characters,
251 * or one of the common ASCII characters that is combined with control to
252 * make a control character.
253 */
254static Bool
255IsControlInput(KEY_DATA * kd)
256{
257    return ((kd->keysym) >= 0x40 && (kd->keysym) <= 0x7f);
258}
259
260static Bool
261IsControlOutput(KEY_DATA * kd)
262{
263    return IS_CTRL(kd->keysym);
264}
265
266/*
267 * X "normally" has some built-in translations, which the user may want to
268 * suppress when processing the modifyOtherKeys resource.  In particular, the
269 * control modifier applied to some of the keyboard digits gives results for
270 * control characters.
271 *
272 * control 2   0    NUL
273 * control SPC 0    NUL
274 * control @   0    NUL
275 * control `   0    NUL
276 * control 3   0x1b ESC
277 * control 4   0x1c FS
278 * control \   0x1c FS
279 * control 5   0x1d GS
280 * control 6   0x1e RS
281 * control ^   0x1e RS
282 * control ~   0x1e RS
283 * control 7   0x1f US
284 * control /   0x1f US
285 * control _   0x1f US
286 * control 8   0x7f DEL
287 *
288 * It is possible that some other keyboards do not work for these combinations,
289 * but they do work with modifyOtherKeys=2 for the US keyboard:
290 *
291 * control `   0    NUL
292 * control [   0x1b ESC
293 * control \   0x1c FS
294 * control ]   0x1d GS
295 * control ?   0x7f DEL
296 */
297static Bool
298IsControlAlias(KEY_DATA * kd)
299{
300    Bool result = False;
301
302    if (kd->nbytes == 1) {
303	result = IS_CTRL(CharOf(kd->strbuf[0]));
304    }
305    return result;
306}
307
308/*
309 * If we are in the non-VT220/VT52 keyboard state, allow modifiers to add a
310 * parameter to the function-key control sequences.
311 *
312 * Note that we generally cannot capture the Shift-modifier for the numeric
313 * keypad since this is commonly used to act as a type of NumLock, e.g.,
314 * making the keypad send "7" (actually XK_KP_7) where the unshifted code
315 * would be Home (XK_KP_Home).  The other modifiers work, subject to the
316 * usual window-manager assignments.
317 */
318#if OPT_SUNPC_KBD
319#define LegacyAllows(code) (!is_legacy || (code & xw->keyboard.modify_now.allow_keys) != 0)
320#else
321#define LegacyAllows(code) True
322#endif
323
324static Bool
325allowModifierParm(XtermWidget xw, KEY_DATA * kd)
326{
327    TKeyboard *keyboard = &(xw->keyboard);
328    int is_legacy = (keyboard->type == keyboardIsLegacy);
329    Bool result = False;
330
331#if OPT_SUNPC_KBD
332    if (keyboard->type == keyboardIsVT220)
333	is_legacy = True;
334#endif
335
336#if OPT_VT52_MODE
337    if (TScreenOf(xw)->vtXX_level != 0)
338#endif
339    {
340	if (IsCursorKey(kd->keysym) || IsEditFunctionKey(xw, kd->keysym)) {
341	    result = LegacyAllows(2);
342	} else if (IsKeypadKey(kd->keysym)) {
343	    result = LegacyAllows(1);
344	} else if (IsFunctionKey(kd->keysym)) {
345	    result = LegacyAllows(4);
346	} else if (IsMiscFunctionKey(kd->keysym)) {
347	    result = LegacyAllows(8);
348	}
349    }
350    if (xw->keyboard.modify_now.other_keys != 0) {
351	result = True;
352    }
353    return result;
354}
355
356/*
357* Modifier codes:
358*       None                  1
359*       Shift                 2 = 1(None)+1(Shift)
360*       Alt                   3 = 1(None)+2(Alt)
361*       Alt+Shift             4 = 1(None)+1(Shift)+2(Alt)
362*       Ctrl                  5 = 1(None)+4(Ctrl)
363*       Ctrl+Shift            6 = 1(None)+1(Shift)+4(Ctrl)
364*       Ctrl+Alt              7 = 1(None)+2(Alt)+4(Ctrl)
365*       Ctrl+Alt+Shift        8 = 1(None)+1(Shift)+2(Alt)+4(Ctrl)
366*       Meta                  9 = 1(None)+8(Meta)
367*       Meta+Shift           10 = 1(None)+8(Meta)+1(Shift)
368*       Meta+Alt             11 = 1(None)+8(Meta)+2(Alt)
369*       Meta+Alt+Shift       12 = 1(None)+8(Meta)+1(Shift)+2(Alt)
370*       Meta+Ctrl            13 = 1(None)+8(Meta)+4(Ctrl)
371*       Meta+Ctrl+Shift      14 = 1(None)+8(Meta)+1(Shift)+4(Ctrl)
372*       Meta+Ctrl+Alt        15 = 1(None)+8(Meta)+2(Alt)+4(Ctrl)
373*       Meta+Ctrl+Alt+Shift  16 = 1(None)+8(Meta)+1(Shift)+2(Alt)+4(Ctrl)
374*/
375
376unsigned
377xtermParamToState(XtermWidget xw, unsigned param)
378{
379    unsigned result = 0;
380#if OPT_NUM_LOCK
381    if (param > MOD_NONE) {
382	if ((param - MOD_NONE) & MOD_SHIFT)
383	    UIntSet(result, ShiftMask);
384	if ((param - MOD_NONE) & MOD_CTRL)
385	    UIntSet(result, ControlMask);
386	if ((param - MOD_NONE) & MOD_ALT)
387	    UIntSet(result, xw->work.alt_mods);
388	if ((param - MOD_NONE) & MOD_META)
389	    UIntSet(result, xw->work.meta_mods);
390    }
391#else
392    (void) xw;
393    (void) param;
394#endif
395    TRACE(("xtermParamToState(%d) %s%s%s%s -> %#x\n", param,
396	   MODIFIER_NAME(param, MOD_SHIFT),
397	   MODIFIER_NAME(param, MOD_ALT),
398	   MODIFIER_NAME(param, MOD_CTRL),
399	   MODIFIER_NAME(param, MOD_META),
400	   result));
401    return result;
402}
403
404unsigned
405xtermStateToParam(XtermWidget xw, unsigned state)
406{
407    unsigned modify_parm = MOD_NONE;
408
409    TRACE(("xtermStateToParam %#x\n", state));
410#if OPT_NUM_LOCK
411    if (state & ShiftMask) {
412	modify_parm += MOD_SHIFT;
413	UIntClr(state, ShiftMask);
414    }
415    if (state & ControlMask) {
416	modify_parm += MOD_CTRL;
417	UIntClr(state, ControlMask);
418    }
419    if ((state & xw->work.alt_mods) != 0) {
420	modify_parm += MOD_ALT;
421	UIntClr(state, xw->work.alt_mods);
422    }
423    if ((state & xw->work.meta_mods) != 0) {
424	modify_parm += MOD_META;
425	/* UIntClr(state, xw->work.meta_mods); */
426    }
427    if (modify_parm == MOD_NONE)
428	modify_parm = 0;
429#else
430    (void) xw;
431    (void) state;
432#endif
433    TRACE(("...xtermStateToParam %d%s%s%s%s\n", modify_parm,
434	   MODIFIER_NAME(modify_parm, MOD_SHIFT),
435	   MODIFIER_NAME(modify_parm, MOD_ALT),
436	   MODIFIER_NAME(modify_parm, MOD_CTRL),
437	   MODIFIER_NAME(modify_parm, MOD_META)));
438    return modify_parm;
439}
440
441#define computeMaskedModifier(xw, state, mask) \
442	xtermStateToParam(xw, Masked(state, mask))
443
444#if OPT_NUM_LOCK
445static unsigned
446filterAltMeta(unsigned result, unsigned mask, Bool enable, KEY_DATA * kd)
447{
448    if ((result & mask) != 0) {
449	/*
450	 * metaSendsEscape makes the meta key independent of
451	 * modifyOtherKeys.
452	 */
453	if (enable) {
454	    result &= ~mask;
455	}
456	/*
457	 * A bare meta-modifier is independent of modifyOtherKeys.  If it
458	 * is combined with other modifiers, make it depend.
459	 */
460	if ((result & ~(mask)) == 0) {
461	    result &= ~mask;
462	}
463	/*
464	 * Check for special cases of control+meta which are used by some
465	 * applications, e.g., emacs.
466	 */
467	if ((IsControlInput(kd)
468	     || IsControlOutput(kd))
469	    && (result & ControlMask) != 0) {
470	    result &= ~(mask | ControlMask);
471	}
472	if (kd->keysym == XK_Return || kd->keysym == XK_Tab) {
473	    result &= ~(mask | ControlMask);
474	}
475    }
476    return result;
477}
478#endif /* OPT_NUM_LOCK */
479
480/*
481 * Single characters (not function-keys) are allowed fewer modifiers when
482 * interpreting modifyOtherKeys due to pre-existing associations with some
483 * modifiers.
484 */
485static unsigned
486allowedCharModifiers(XtermWidget xw, unsigned state, KEY_DATA * kd)
487{
488#if OPT_NUM_LOCK
489    unsigned a_or_m = (state & (xw->work.meta_mods | xw->work.alt_mods));
490#else
491    unsigned a_or_m = 0;
492#endif
493    /*
494     * Start by limiting the result to the modifiers we might want to use.
495     */
496    unsigned result = (state & (ControlMask
497				| ShiftMask
498				| a_or_m));
499
500    /*
501     * If modifyOtherKeys is off or medium (0 or 1), moderate its effects by
502     * excluding the common cases for modifiers.
503     */
504    if (xw->keyboard.modify_now.other_keys <= 1) {
505	if (IsControlInput(kd)
506	    && Masked(result, ControlMask) == 0) {
507	    /* These keys are already associated with the control-key */
508	    if (xw->keyboard.modify_now.other_keys == 0) {
509		UIntClr(result, ControlMask);
510	    }
511	} else if (kd->keysym == XK_Tab || kd->keysym == XK_Return) {
512	    /* EMPTY */ ;
513	} else if (IsControlAlias(kd)) {
514	    /* Things like "^_" work here... */
515	    if (Masked(result, (ControlMask | ShiftMask)) == 0) {
516		result = 0;
517	    }
518	} else if (!IsControlOutput(kd) && !IsPredefinedKey(kd->keysym)) {
519	    /* Printable keys are already associated with the shift-key */
520	    if (!(result & ControlMask)) {
521		UIntClr(result, ShiftMask);
522	    }
523	}
524#if OPT_NUM_LOCK
525	result = filterAltMeta(result,
526			       xw->work.meta_mods,
527			       TScreenOf(xw)->meta_sends_esc, kd);
528	if (TScreenOf(xw)->alt_is_not_meta) {
529	    result = filterAltMeta(result,
530				   xw->work.alt_mods,
531				   TScreenOf(xw)->alt_sends_esc, kd);
532	}
533#endif
534    }
535    TRACE(("...allowedCharModifiers(state=%u" FMT_MODIFIER_NAMES
536	   ", ch=" KEYSYM_FMT ") ->"
537	   "%u" FMT_MODIFIER_NAMES "\n",
538	   state, ARG_MODIFIER_NAMES(state), kd->keysym,
539	   result, ARG_MODIFIER_NAMES(result)));
540    return result;
541}
542
543/*
544 * Decide if we should generate a special escape sequence for "other" keys
545 * than cursor-, function-keys, etc., as per the modifyOtherKeys resource.
546 */
547static Bool
548ModifyOtherKeys(XtermWidget xw,
549		unsigned state,
550		KEY_DATA * kd,
551		unsigned modify_parm)
552{
553    TKeyboard *keyboard = &(xw->keyboard);
554    Bool result = False;
555
556    /*
557     * Exclude the keys already covered by a modifier.
558     */
559    if (kd->is_fkey
560	|| IsEditFunctionKey(xw, kd->keysym)
561	|| IsKeypadKey(kd->keysym)
562	|| IsCursorKey(kd->keysym)
563	|| IsPFKey(kd->keysym)
564	|| IsMiscFunctionKey(kd->keysym)
565	|| IsPrivateKeypadKey(kd->keysym)) {
566	result = False;
567    } else if (modify_parm != 0) {
568	if (IsBackarrowToggle(keyboard, kd->keysym, state)) {
569	    kd->keysym = XK_Delete;
570	    UIntClr(state, ControlMask);
571	}
572	if (!IsPredefinedKey(kd->keysym)) {
573	    state = allowedCharModifiers(xw, state, kd);
574	}
575	if (state != 0) {
576	    switch (keyboard->modify_now.other_keys) {
577	    default:
578		break;
579	    case 1:
580		switch (kd->keysym) {
581		case XK_BackSpace:
582		case XK_Delete:
583		    result = False;
584		    break;
585#ifdef XK_ISO_Left_Tab
586		case XK_ISO_Left_Tab:
587		    if (computeMaskedModifier(xw, state, ShiftMask))
588			result = True;
589		    break;
590#endif
591		case XK_Return:
592		case XK_Tab:
593		    result = (modify_parm != 0);
594		    break;
595		default:
596		    if (IsControlInput(kd)) {
597			if (state == ControlMask || state == ShiftMask) {
598			    result = False;
599			} else {
600			    result = (modify_parm != 0);
601			}
602		    } else if (IsControlAlias(kd)) {
603			if (state == ShiftMask)
604			    result = False;
605			else if (computeMaskedModifier(xw, state, ControlMask)) {
606			    result = True;
607			}
608		    } else {
609			result = True;
610		    }
611		    break;
612		}
613		break;
614	    case 2:
615		switch (kd->keysym) {
616		case XK_BackSpace:
617		    /* strip ControlMask as per IsBackarrowToggle() */
618		    if (computeMaskedModifier(xw, state, ControlMask))
619			result = True;
620		    break;
621		case XK_Delete:
622		    result = (xtermStateToParam(xw, state) != 0);
623		    break;
624#ifdef XK_ISO_Left_Tab
625		case XK_ISO_Left_Tab:
626		    if (computeMaskedModifier(xw, state, ShiftMask))
627			result = True;
628		    break;
629#endif
630		case XK_Return:
631		case XK_Tab:
632		    result = (modify_parm != 0);
633		    break;
634		default:
635		    if (IsControlInput(kd)) {
636			result = True;
637		    } else if (state == ShiftMask) {
638			result = (kd->keysym == ' ' || kd->keysym == XK_Return);
639		    } else if (computeMaskedModifier(xw, state, ShiftMask)) {
640			result = True;
641		    }
642		    break;
643		}
644		break;
645	    }
646	}
647    }
648    TRACE(("...ModifyOtherKeys(%d,%d) %s\n",
649	   keyboard->modify_now.other_keys,
650	   modify_parm,
651	   BtoS(result)));
652    return result;
653}
654
655#define APPEND_PARM(number) \
656	    reply->a_param[reply->a_nparam] = (ParmType) number; \
657	    reply->a_nparam++
658
659/*
660 * Function-key code 27 happens to not be used in the vt220-style encoding.
661 * xterm uses this to represent modified non-function-keys such as control/+ in
662 * the Sun/PC keyboard layout.  See the modifyOtherKeys resource in the manpage
663 * for more information.
664 */
665static Bool
666modifyOtherKey(ANSI *reply, int input_char, unsigned modify_parm, int format_keys)
667{
668    Bool result = False;
669
670    if (input_char >= 0) {
671	reply->a_type = ANSI_CSI;
672	if (format_keys) {
673	    APPEND_PARM(input_char);
674	    APPEND_PARM(modify_parm);
675	    reply->a_final = 'u';
676	} else {
677	    APPEND_PARM(27);
678	    APPEND_PARM(modify_parm);
679	    APPEND_PARM(input_char);
680	    reply->a_final = '~';
681	}
682
683	result = True;
684    }
685    return result;
686}
687
688static void
689modifyCursorKey(ANSI *reply, int modify, unsigned *modify_parm)
690{
691    if (*modify_parm != 0) {
692	if (modify < 0) {
693	    *modify_parm = 0;
694	}
695	if (modify > 0) {
696	    reply->a_type = ANSI_CSI;	/* SS3 should not have params */
697	}
698	if (modify > 1 && reply->a_nparam == 0) {
699	    APPEND_PARM(1);	/* force modifier to 2nd param */
700	}
701	if (modify > 2) {
702	    reply->a_pintro = '>';	/* mark this as "private" */
703	}
704    }
705}
706#else
707#define modifyCursorKey(reply, modify, parm)	/* nothing */
708#endif /* OPT_MOD_FKEYS */
709
710#if OPT_SUNPC_KBD
711/*
712 * If we have told xterm that our keyboard is really a Sun/PC keyboard, this is
713 * enough to make a reasonable approximation to DEC vt220 numeric and editing
714 * keypads.
715 */
716static KeySym
717TranslateFromSUNPC(KeySym keysym)
718{
719    /* *INDENT-OFF* */
720    static struct {
721	    KeySym before, after;
722    } table[] = {
723#ifdef DXK_Remove
724	{ XK_Delete,       DXK_Remove },
725#endif
726	{ XK_Home,         XK_Find },
727	{ XK_End,          XK_Select },
728#ifdef XK_KP_Home
729	{ XK_Delete,       XK_KP_Decimal },
730	{ XK_KP_Delete,    XK_KP_Decimal },
731	{ XK_KP_Insert,    XK_KP_0 },
732	{ XK_KP_End,       XK_KP_1 },
733	{ XK_KP_Down,      XK_KP_2 },
734	{ XK_KP_Next,      XK_KP_3 },
735	{ XK_KP_Left,      XK_KP_4 },
736	{ XK_KP_Begin,     XK_KP_5 },
737	{ XK_KP_Right,     XK_KP_6 },
738	{ XK_KP_Home,      XK_KP_7 },
739	{ XK_KP_Up,        XK_KP_8 },
740	{ XK_KP_Prior,     XK_KP_9 },
741#endif
742    };
743    /* *INDENT-ON* */
744
745    unsigned n;
746
747    for (n = 0; n < sizeof(table) / sizeof(table[0]); n++) {
748	if (table[n].before == keysym) {
749	    TRACE(("...Input keypad before was " KEYSYM_FMT "\n", keysym));
750	    keysym = table[n].after;
751	    TRACE(("...Input keypad changed to " KEYSYM_FMT "\n", keysym));
752	    break;
753	}
754    }
755    return keysym;
756}
757#endif /* OPT_SUNPC_KBD */
758
759#define VT52_KEYPAD \
760	if_OPT_VT52_MODE(screen,{ \
761		reply.a_type = ANSI_ESC; \
762		reply.a_pintro = '?'; \
763		})
764
765#define VT52_CURSOR_KEYS \
766	if_OPT_VT52_MODE(screen,{ \
767		reply.a_type = ANSI_ESC; \
768		})
769
770#undef  APPEND_PARM
771#define APPEND_PARM(number) \
772	    reply.a_param[reply.a_nparam] = (ParmType) number, \
773	    reply.a_nparam++
774
775#if OPT_MOD_FKEYS
776#define MODIFIER_PARM \
777	if (modify_parm != 0) APPEND_PARM(modify_parm)
778#else
779#define MODIFIER_PARM		/*nothing */
780#endif
781
782/*
783 * Determine if we use the \E[3~ sequence for Delete, or the legacy ^?.  We
784 * maintain the delete_is_del value as 3 states:  unspecified(2), true and
785 * false.  If unspecified, it is handled differently according to whether the
786 * legacy keyboard support is enabled, or if xterm emulates a VT220.
787 *
788 * Once the user (or application) has specified delete_is_del via resource
789 * setting, popup menu or escape sequence, it overrides the keyboard type
790 * rather than the reverse.
791 */
792Bool
793xtermDeleteIsDEL(XtermWidget xw)
794{
795    Bool result = True;
796
797    if (xw->keyboard.type == keyboardIsDefault
798	|| xw->keyboard.type == keyboardIsVT220)
799	result = (TScreenOf(xw)->delete_is_del == True);
800
801    if (xw->keyboard.type == keyboardIsLegacy)
802	result = (TScreenOf(xw)->delete_is_del != False);
803
804    TRACE(("xtermDeleteIsDEL(%d/%d) = %d\n",
805	   xw->keyboard.type,
806	   TScreenOf(xw)->delete_is_del,
807	   result));
808
809    return result;
810}
811
812static Boolean
813lookupKeyData(KEY_DATA * kd, XtermWidget xw, XKeyEvent *event)
814{
815    TScreen *screen = TScreenOf(xw);
816    Boolean result = True;
817#if OPT_INPUT_METHOD
818#if OPT_MOD_FKEYS
819    TKeyboard *keyboard = &(xw->keyboard);
820#endif
821#endif
822
823    (void) screen;
824
825    TRACE(("%s %#x\n", visibleEventType(event->type), event->keycode));
826
827    kd->keysym = 0;
828    kd->is_fkey = False;
829#if OPT_TCAP_QUERY
830    if (screen->tc_query_code >= 0) {
831	kd->keysym = (KeySym) screen->tc_query_code;
832	kd->is_fkey = screen->tc_query_fkey;
833	if (kd->keysym != XK_BackSpace) {
834	    kd->nbytes = 0;
835	    kd->strbuf[0] = 0;
836	} else {
837	    kd->nbytes = 1;
838	    kd->strbuf[0] = 8;
839	}
840    } else
841#endif
842    {
843#if OPT_INPUT_METHOD
844	TInput *input = lookupTInput(xw, (Widget) xw);
845	if (input && input->xic) {
846	    Status status_return;
847#if OPT_WIDE_CHARS
848	    if (screen->utf8_mode) {
849		kd->nbytes = Xutf8LookupString(input->xic, event,
850					       kd->strbuf, (int) sizeof(kd->strbuf),
851					       &(kd->keysym), &status_return);
852	    } else
853#endif
854	    {
855		kd->nbytes = XmbLookupString(input->xic, event,
856					     kd->strbuf, (int) sizeof(kd->strbuf),
857					     &(kd->keysym), &status_return);
858	    }
859#if OPT_MOD_FKEYS
860	    /*
861	     * Fill-in some code useful with IsControlAlias():
862	     */
863	    if (status_return == XLookupBoth
864		&& kd->nbytes <= 1
865		&& !IsPredefinedKey(kd->keysym)
866		&& (keyboard->modify_now.other_keys > 1)
867		&& !IsControlInput(kd)) {
868		kd->nbytes = 1;
869		kd->strbuf[0] = (char) kd->keysym;
870	    }
871#endif /* OPT_MOD_FKEYS */
872	} else
873#endif /* OPT_INPUT_METHOD */
874	{
875	    static XComposeStatus compose_status =
876	    {NULL, 0};
877	    kd->nbytes = XLookupString(event,
878				       kd->strbuf, (int) sizeof(kd->strbuf),
879				       &(kd->keysym), &compose_status);
880	}
881	kd->is_fkey = IsFunctionKey(kd->keysym);
882    }
883    return result;
884}
885
886void
887Input(XtermWidget xw,
888      XKeyEvent *event,
889      Bool eightbit)
890{
891    Char *string;
892
893    TKeyboard *keyboard = &(xw->keyboard);
894    TScreen *screen = TScreenOf(xw);
895
896    int j;
897    int key = False;
898    ANSI reply;
899    int dec_code;
900    unsigned modify_parm = 0;
901    int keypad_mode = ((keyboard->flags & MODE_DECKPAM) != 0);
902    unsigned evt_state = event->state;
903    unsigned mod_state;
904    KEY_DATA kd;
905
906    /* Ignore characters typed at the keyboard */
907    if (keyboard->flags & MODE_KAM)
908	return;
909
910    lookupKeyData(&kd, xw, event);
911
912    memset(&reply, 0, sizeof(reply));
913
914    TRACE(("Input(%d,%d) keysym "
915	   KEYSYM_FMT
916	   ", %d:'%s'%s" FMT_MODIFIER_NAMES "%s%s%s%s%s%s\n",
917	   screen->cur_row, screen->cur_col,
918	   kd.keysym,
919	   kd.nbytes,
920	   visibleChars((Char *) kd.strbuf,
921			((kd.nbytes > 0)
922			 ? (unsigned) kd.nbytes
923			 : 0)),
924	   ARG_MODIFIER_NAMES(evt_state),
925	   eightbit ? " 8bit" : " 7bit",
926	   IsKeypadKey(kd.keysym) ? " KeypadKey" : "",
927	   IsCursorKey(kd.keysym) ? " CursorKey" : "",
928	   IsPFKey(kd.keysym) ? " PFKey" : "",
929	   kd.is_fkey ? " FKey" : "",
930	   IsMiscFunctionKey(kd.keysym) ? " MiscFKey" : "",
931	   IsEditFunctionKey(xw, kd.keysym) ? " EditFkey" : ""));
932
933#if OPT_SUNPC_KBD
934    /*
935     * DEC keyboards don't have keypad(+), but do have keypad(,) instead.
936     * Other (Sun, PC) keyboards commonly have keypad(+), but no keypad(,)
937     * - it's a pain for users to work around.
938     */
939    if (keyboard->type == keyboardIsVT220
940	&& (evt_state & ShiftMask) == 0) {
941	if (kd.keysym == XK_KP_Add) {
942	    kd.keysym = XK_KP_Separator;
943	    UIntClr(evt_state, ShiftMask);
944	    TRACE(("...Input keypad(+), change keysym to "
945		   KEYSYM_FMT
946		   "\n",
947		   kd.keysym));
948	}
949	if ((evt_state & ControlMask) != 0
950	    && kd.keysym == XK_KP_Separator) {
951	    kd.keysym = XK_KP_Subtract;
952	    UIntClr(evt_state, ControlMask);
953	    TRACE(("...Input control/keypad(,), change keysym to "
954		   KEYSYM_FMT
955		   "\n",
956		   kd.keysym));
957	}
958    }
959#endif
960
961    /*
962     * The keyboard tables may give us different keypad codes according to
963     * whether NumLock is pressed.  Use this check to simplify the process
964     * of determining whether we generate an escape sequence for a keypad
965     * key, or force it to the value kypd_num[].  There is no fixed
966     * modifier for this feature, so we assume that it is the one assigned
967     * to the NumLock key.
968     *
969     * This check used to try to return the contents of strbuf, but that
970     * does not work properly when a control modifier is given (trash is
971     * returned in the buffer in some cases -- perhaps an X bug).
972     */
973#if OPT_NUM_LOCK
974    if (kd.nbytes == 1
975	&& IsKeypadKey(kd.keysym)
976	&& xw->misc.real_NumLock
977	&& (xw->work.num_lock & evt_state) != 0) {
978	keypad_mode = 0;
979	TRACE(("...Input num_lock, force keypad_mode off\n"));
980    }
981#endif
982
983#if OPT_MOD_FKEYS
984    if (evt_state != 0
985	&& allowModifierParm(xw, &kd)) {
986	modify_parm = xtermStateToParam(xw, evt_state);
987    }
988
989    /*
990     * Shift-tab is often mapped to XK_ISO_Left_Tab which is classified as
991     * IsEditFunctionKey(), and the conversion does not produce any bytes.
992     * Check for this special case so we have data when handling the
993     * modifyOtherKeys resource.
994     */
995    if (keyboard->modify_now.other_keys > 1) {
996	if (IsTabKey(kd.keysym) && kd.nbytes == 0) {
997	    kd.nbytes = 1;
998	    kd.strbuf[0] = '\t';
999	}
1000    }
1001#ifdef XK_ISO_Left_Tab
1002    else if (IsTabKey(kd.keysym)
1003	     && kd.nbytes <= 1
1004	     && modify_parm == (MOD_NONE + MOD_SHIFT)) {
1005	kd.keysym = XK_ISO_Left_Tab;
1006    }
1007#endif
1008#endif /* OPT_MOD_FKEYS */
1009
1010    /* VT300 & up: backarrow toggle */
1011    if ((kd.nbytes == 1)
1012	&& IsBackarrowToggle(keyboard, kd.keysym, evt_state)) {
1013	kd.strbuf[0] = ANSI_DEL;
1014	TRACE(("...Input backarrow changed to %d\n", kd.strbuf[0]));
1015    }
1016#if OPT_SUNPC_KBD
1017    /* make an DEC editing-keypad from a Sun or PC editing-keypad */
1018    if (keyboard->type == keyboardIsVT220
1019	&& (kd.keysym != XK_Delete || !xtermDeleteIsDEL(xw)))
1020	kd.keysym = TranslateFromSUNPC(kd.keysym);
1021    else
1022#endif
1023    {
1024#ifdef XK_KP_Home
1025	if (kd.keysym >= XK_KP_Home && kd.keysym <= XK_KP_Begin) {
1026	    TRACE(("...Input keypad before was " KEYSYM_FMT "\n", kd.keysym));
1027	    kd.keysym += (KeySym) (XK_Home - XK_KP_Home);
1028	    TRACE(("...Input keypad changed to " KEYSYM_FMT "\n", kd.keysym));
1029	}
1030#endif
1031    }
1032
1033    /*
1034     * Map the Sun afterthought-keys in as F36 and F37.
1035     */
1036#ifdef SunXK_F36
1037    if (!kd.is_fkey) {
1038	if (kd.keysym == SunXK_F36) {
1039	    kd.keysym = XK_Fn(36);
1040	    kd.is_fkey = True;
1041	}
1042	if (kd.keysym == SunXK_F37) {
1043	    kd.keysym = XK_Fn(37);
1044	    kd.is_fkey = True;
1045	}
1046    }
1047#endif
1048
1049    /*
1050     * Use the control- and shift-modifiers to obtain more function keys than
1051     * the keyboard provides.  We can do this if there is no conflicting use of
1052     * those modifiers:
1053     *
1054     * a) for VT220 keyboard, we use only the control-modifier.  The keyboard
1055     * uses shift-modifier for UDK's.
1056     *
1057     * b) for non-VT220 keyboards, we only have to check if the
1058     * modifyFunctionKeys resource is inactive.
1059     *
1060     * Thereafter, we note when we have a function-key and keep that
1061     * distinction when testing for "function-key" values.
1062     */
1063    if ((evt_state & (ControlMask | ShiftMask)) != 0
1064	&& kd.is_fkey) {
1065
1066	/* VT220 keyboard uses shift for UDK */
1067	if (keyboard->type == keyboardIsVT220
1068	    || keyboard->type == keyboardIsLegacy) {
1069
1070	    TRACE(("...map XK_F%ld", kd.keysym - XK_Fn(1) + 1));
1071	    if (evt_state & ControlMask) {
1072		kd.keysym += (KeySym) xw->misc.ctrl_fkeys;
1073		UIntClr(evt_state, ControlMask);
1074	    }
1075	    TRACE((" to XK_F%ld\n", kd.keysym - XK_Fn(1) + 1));
1076
1077	}
1078#if OPT_MOD_FKEYS
1079	else if (keyboard->modify_now.function_keys < 0) {
1080
1081	    TRACE(("...map XK_F%ld", kd.keysym - XK_Fn(1) + 1));
1082	    if (evt_state & ShiftMask) {
1083		kd.keysym += (KeySym) (xw->misc.ctrl_fkeys * 1);
1084		UIntClr(evt_state, ShiftMask);
1085	    }
1086	    if (evt_state & ControlMask) {
1087		kd.keysym += (KeySym) (xw->misc.ctrl_fkeys * 2);
1088		UIntClr(evt_state, ControlMask);
1089	    }
1090	    TRACE((" to XK_F%ld\n", kd.keysym - XK_Fn(1) + 1));
1091
1092	}
1093	/*
1094	 * Reevaluate the modifier parameter, stripping off the modifiers
1095	 * that we just used.
1096	 */
1097	if (modify_parm) {
1098	    modify_parm = xtermStateToParam(xw, evt_state);
1099	}
1100#endif /* OPT_MOD_FKEYS */
1101    }
1102
1103    /*
1104     * Test for one of the keyboard variants.
1105     */
1106    switch (keyboard->type) {
1107    case keyboardIsHP:
1108	hpfuncvalue(&reply, &kd);
1109	break;
1110    case keyboardIsSCO:
1111	scofuncvalue(&reply, &kd);
1112	break;
1113    case keyboardIsSun:
1114	sunfuncvalue(&reply, &kd);
1115	break;
1116    case keyboardIsTermcap:
1117#if OPT_TCAP_FKEYS
1118	if (xtermcapString(xw, (int) kd.keysym, evt_state))
1119	    return;
1120#endif
1121	break;
1122    case keyboardIsDefault:
1123    case keyboardIsLegacy:
1124    case keyboardIsVT220:
1125	break;
1126    }
1127
1128    if (reply.a_final) {
1129	/*
1130	 * The key symbol matches one of the variants.  Most of those are
1131	 * function-keys, though some cursor- and editing-keys are mixed in.
1132	 */
1133	modifyCursorKey(&reply,
1134			((kd.is_fkey
1135			  || IsMiscFunctionKey(kd.keysym)
1136			  || IsEditFunctionKey(xw, kd.keysym))
1137			 ? keyboard->modify_now.function_keys
1138			 : keyboard->modify_now.cursor_keys),
1139			&modify_parm);
1140	MODIFIER_PARM;
1141	unparseseq(xw, &reply);
1142    } else if (((kd.is_fkey
1143		 || IsMiscFunctionKey(kd.keysym)
1144		 || IsEditFunctionKey(xw, kd.keysym))
1145#if OPT_MOD_FKEYS
1146		&& !ModifyOtherKeys(xw, evt_state, &kd, modify_parm)
1147#endif
1148	       ) || (kd.keysym == XK_Delete
1149		     && ((modify_parm != 0)
1150			 || !xtermDeleteIsDEL(xw)))) {
1151	dec_code = decfuncvalue(&kd);
1152	if ((evt_state & ShiftMask)
1153#if OPT_SUNPC_KBD
1154	    && keyboard->type == keyboardIsVT220
1155#endif
1156	    && ((string = (Char *) udk_lookup(xw, dec_code, &kd.nbytes)) != 0)) {
1157	    /* UIntClr(evt_state, ShiftMask); */
1158	    while (kd.nbytes-- > 0)
1159		unparseputc(xw, CharOf(*string++));
1160	}
1161	/*
1162	 * Interpret F1-F4 as PF1-PF4 for VT52, VT100
1163	 */
1164	else if (keyboard->type != keyboardIsLegacy
1165		 && (dec_code >= 11 && dec_code <= 14)) {
1166	    reply.a_type = ANSI_SS3;
1167	    VT52_CURSOR_KEYS;
1168	    reply.a_final = (Char) A2E(dec_code - 11 + E2A('P'));
1169	    modifyCursorKey(&reply,
1170			    keyboard->modify_now.function_keys,
1171			    &modify_parm);
1172	    MODIFIER_PARM;
1173	    unparseseq(xw, &reply);
1174	} else {
1175	    reply.a_type = ANSI_CSI;
1176	    reply.a_final = 0;
1177
1178#ifdef XK_ISO_Left_Tab
1179	    if (kd.keysym == XK_ISO_Left_Tab) {
1180		reply.a_nparam = 0;
1181		reply.a_final = 'Z';
1182#if OPT_MOD_FKEYS
1183		if (keyboard->modify_now.other_keys > 1
1184		    && computeMaskedModifier(xw, evt_state, ShiftMask))
1185		    modifyOtherKey(&reply, '\t', modify_parm, keyboard->format_keys);
1186#endif
1187	    } else
1188#endif /* XK_ISO_Left_Tab */
1189	    {
1190		reply.a_nparam = 1;
1191#if OPT_MOD_FKEYS
1192		if (kd.is_fkey) {
1193		    modifyCursorKey(&reply,
1194				    keyboard->modify_now.function_keys,
1195				    &modify_parm);
1196		}
1197		MODIFIER_PARM;
1198#endif
1199		reply.a_param[0] = (ParmType) dec_code;
1200		reply.a_final = '~';
1201	    }
1202	    if (reply.a_final != 0
1203		&& (reply.a_nparam == 0 || reply.a_param[0] >= 0))
1204		unparseseq(xw, &reply);
1205	}
1206	key = True;
1207    } else if (IsPFKey(kd.keysym)) {
1208	reply.a_type = ANSI_SS3;
1209	reply.a_final = (Char) ((kd.keysym - XK_KP_F1) + 'P');
1210	VT52_CURSOR_KEYS;
1211	MODIFIER_PARM;
1212	unparseseq(xw, &reply);
1213	key = True;
1214    } else if (IsKeypadKey(kd.keysym)) {
1215	if (keypad_mode) {
1216	    reply.a_type = ANSI_SS3;
1217	    reply.a_final = (Char) (kypd_apl[kd.keysym - XK_KP_Space]);
1218	    VT52_KEYPAD;
1219	    MODIFIER_PARM;
1220	    unparseseq(xw, &reply);
1221	} else {
1222	    unparseputc(xw, kypd_num[kd.keysym - XK_KP_Space]);
1223	}
1224	key = True;
1225    } else if (IsCursorKey(kd.keysym)) {
1226	if (keyboard->flags & MODE_DECCKM) {
1227	    reply.a_type = ANSI_SS3;
1228	} else {
1229	    reply.a_type = ANSI_CSI;
1230	}
1231	modifyCursorKey(&reply, keyboard->modify_now.cursor_keys, &modify_parm);
1232	reply.a_final = (Char) (curfinal[kd.keysym - XK_Home]);
1233	VT52_CURSOR_KEYS;
1234	MODIFIER_PARM;
1235	unparseseq(xw, &reply);
1236	key = True;
1237    } else if (kd.nbytes > 0) {
1238
1239#if OPT_TEK4014
1240	if (TEK4014_GIN(tekWidget)) {
1241	    TekEnqMouse(tekWidget, kd.strbuf[0]);
1242	    TekGINoff(tekWidget);
1243	    kd.nbytes--;
1244	    for (j = 0; j < kd.nbytes; ++j) {
1245		kd.strbuf[j] = kd.strbuf[j + 1];
1246	    }
1247	}
1248#endif
1249#if OPT_MOD_FKEYS
1250	if ((keyboard->modify_now.other_keys > 0)
1251	    && ModifyOtherKeys(xw, evt_state, &kd, modify_parm)
1252	    && (mod_state = allowedCharModifiers(xw, evt_state, &kd)) != 0) {
1253	    int input_char;
1254
1255	    evt_state = mod_state;
1256
1257	    modify_parm = xtermStateToParam(xw, evt_state);
1258
1259	    /*
1260	     * We want to show a keycode that corresponds to the 8-bit value
1261	     * of the key.  If the keysym is less than 256, that is good
1262	     * enough.  Special keys such as Tab may result in a value that
1263	     * is usable as well.  For the latter (special cases), try to use
1264	     * the result from the X library lookup.
1265	     */
1266	    input_char = ((kd.keysym < 256)
1267			  ? (int) kd.keysym
1268			  : ((kd.nbytes == 1)
1269			     ? CharOf(kd.strbuf[0])
1270			     : -1));
1271
1272	    TRACE(("...modifyOtherKeys %d;%d\n", modify_parm, input_char));
1273	    if (modifyOtherKey(&reply, input_char, modify_parm, keyboard->format_keys)) {
1274		unparseseq(xw, &reply);
1275	    } else {
1276		Bell(xw, XkbBI_MinorError, 0);
1277	    }
1278	} else
1279#endif /* OPT_MOD_FKEYS */
1280	{
1281	    int prefix = 0;
1282
1283#if OPT_NUM_LOCK
1284	    /*
1285	     * Send ESC if we have a META modifier and metaSendsEcape is true.
1286	     * Like eightBitInput, except that it is not associated with
1287	     * terminal settings.
1288	     */
1289	    if (kd.nbytes != 0) {
1290		if (screen->meta_sends_esc
1291		    && (evt_state & xw->work.meta_mods) != 0) {
1292		    TRACE(("...input-char is modified by META\n"));
1293		    UIntClr(evt_state, xw->work.meta_mods);
1294		    eightbit = False;
1295		    prefix = ANSI_ESC;
1296		} else if (eightbit) {
1297		    /* it might be overridden, but this helps for debugging */
1298		    TRACE(("...input-char is shifted by META\n"));
1299		}
1300		if (screen->alt_is_not_meta
1301		    && (evt_state & xw->work.alt_mods) != 0) {
1302		    UIntClr(evt_state, xw->work.alt_mods);
1303		    if (screen->alt_sends_esc) {
1304			TRACE(("...input-char is modified by ALT\n"));
1305			eightbit = False;
1306			prefix = ANSI_ESC;
1307		    } else if (!eightbit) {
1308			TRACE(("...input-char is shifted by ALT\n"));
1309			eightbit = True;
1310		    }
1311		}
1312	    }
1313#endif
1314	    /*
1315	     * If metaSendsEscape is false, fall through to this chunk, which
1316	     * implements the eightBitInput resource.
1317	     *
1318	     * It is normally executed when the user presses Meta plus a
1319	     * printable key, e.g., Meta+space.  The presence of the Meta
1320	     * modifier is not guaranteed since what really happens is the
1321	     * "insert-eight-bit" or "insert-seven-bit" action, which we
1322	     * distinguish by the eightbit parameter to this function.  So the
1323	     * eightBitInput resource really means that we use this shifting
1324	     * logic in the "insert-eight-bit" action.
1325	     */
1326	    if (eightbit && (kd.nbytes == 1) && screen->input_eight_bits) {
1327		IChar ch = CharOf(kd.strbuf[0]);
1328		if ((ch < 128) && (screen->eight_bit_meta == ebTrue)) {
1329		    kd.strbuf[0] |= (char) 0x80;
1330		    TRACE(("...input shift from %d to %d (%#x to %#x)\n",
1331			   ch, CharOf(kd.strbuf[0]),
1332			   ch, CharOf(kd.strbuf[0])));
1333#if OPT_WIDE_CHARS
1334		    if (screen->utf8_mode) {
1335			/*
1336			 * We could interpret the incoming code as "in the
1337			 * current locale", but it's simpler to treat it as
1338			 * a Unicode value to translate to UTF-8.
1339			 */
1340			ch = CharOf(kd.strbuf[0]);
1341			kd.nbytes = 2;
1342			kd.strbuf[0] = (char) (0xc0 | ((ch >> 6) & 0x3));
1343			kd.strbuf[1] = (char) (0x80 | (ch & 0x3f));
1344			TRACE(("...encoded %#x in UTF-8 as %#x,%#x\n",
1345			       ch, CharOf(kd.strbuf[0]), CharOf(kd.strbuf[1])));
1346		    }
1347#endif
1348		}
1349		eightbit = False;
1350	    }
1351#if OPT_WIDE_CHARS
1352	    if (kd.nbytes == 1)	/* cannot do NRC on UTF-8, for instance */
1353#endif
1354	    {
1355		/* VT220 & up: National Replacement Characters */
1356		if ((xw->flags & NATIONAL) != 0) {
1357		    unsigned cmp = xtermCharSetIn(xw,
1358						  CharOf(kd.strbuf[0]),
1359						  (DECNRCM_codes)
1360						  screen->keyboard_dialect[0]);
1361		    TRACE(("...input NRC %d, %s %d\n",
1362			   CharOf(kd.strbuf[0]),
1363			   (CharOf(kd.strbuf[0]) == cmp)
1364			   ? "unchanged"
1365			   : "changed to",
1366			   CharOf(cmp)));
1367		    kd.strbuf[0] = (char) cmp;
1368		} else if (eightbit) {
1369		    prefix = ANSI_ESC;
1370		} else if (kd.strbuf[0] == '?'
1371			   && (evt_state & ControlMask) != 0) {
1372		    kd.strbuf[0] = ANSI_DEL;
1373		}
1374	    }
1375	    if (prefix != 0)
1376		unparseputc(xw, prefix);	/* escape */
1377	    for (j = 0; j < kd.nbytes; ++j)
1378		unparseputc(xw, CharOf(kd.strbuf[j]));
1379	}
1380	key = ((kd.keysym != ANSI_XOFF) && (kd.keysym != ANSI_XON));
1381    }
1382    unparse_end(xw);
1383
1384    if (key && !TEK4014_ACTIVE(xw))
1385	AdjustAfterInput(xw);
1386
1387    xtermShowPointer(xw, False);
1388    return;
1389}
1390
1391void
1392StringInput(XtermWidget xw, const Char *string, size_t nbytes)
1393{
1394    TRACE(("InputString (%s,%lu)\n",
1395	   visibleChars(string, (unsigned) nbytes),
1396	   (unsigned long) nbytes));
1397#if OPT_TEK4014
1398    if (nbytes && TEK4014_GIN(tekWidget)) {
1399	TekEnqMouse(tekWidget, *string++);
1400	TekGINoff(tekWidget);
1401	nbytes--;
1402    }
1403#endif
1404    while (nbytes-- != 0)
1405	unparseputc(xw, *string++);
1406    if (!TEK4014_ACTIVE(xw))
1407	AdjustAfterInput(xw);
1408    unparse_end(xw);
1409}
1410
1411/* These definitions are DEC-style (e.g., vt320) */
1412static int
1413decfuncvalue(KEY_DATA * kd)
1414{
1415    int result;
1416
1417    if (kd->is_fkey) {
1418	switch (kd->keysym) {
1419	    MAP(XK_Fn(1), 11);
1420	    MAP(XK_Fn(2), 12);
1421	    MAP(XK_Fn(3), 13);
1422	    MAP(XK_Fn(4), 14);
1423	    MAP(XK_Fn(5), 15);
1424	    MAP(XK_Fn(6), 17);
1425	    MAP(XK_Fn(7), 18);
1426	    MAP(XK_Fn(8), 19);
1427	    MAP(XK_Fn(9), 20);
1428	    MAP(XK_Fn(10), 21);
1429	    MAP(XK_Fn(11), 23);
1430	    MAP(XK_Fn(12), 24);
1431	    MAP(XK_Fn(13), 25);
1432	    MAP(XK_Fn(14), 26);
1433	    MAP(XK_Fn(15), 28);
1434	    MAP(XK_Fn(16), 29);
1435	    MAP(XK_Fn(17), 31);
1436	    MAP(XK_Fn(18), 32);
1437	    MAP(XK_Fn(19), 33);
1438	    MAP(XK_Fn(20), 34);
1439	default:
1440	    /* after F20 the codes are made up and do not correspond to any
1441	     * real terminal.  So they are simply numbered sequentially.
1442	     */
1443	    result = 42 + (int) (kd->keysym - XK_Fn(21));
1444	    break;
1445	}
1446    } else {
1447	switch (kd->keysym) {
1448	    MAP(XK_Find, 1);
1449	    MAP(XK_Insert, 2);
1450	    MAP(XK_Delete, 3);
1451#ifdef XK_KP_Insert
1452	    MAP(XK_KP_Insert, 2);
1453	    MAP(XK_KP_Delete, 3);
1454#endif
1455#ifdef DXK_Remove
1456	    MAP(DXK_Remove, 3);
1457#endif
1458	    MAP(XK_Select, 4);
1459	    MAP(XK_Prior, 5);
1460	    MAP(XK_Next, 6);
1461#ifdef XK_ISO_Left_Tab
1462	    MAP(XK_ISO_Left_Tab, 'Z');
1463#endif
1464	    MAP(XK_Help, 28);
1465	    MAP(XK_Menu, 29);
1466	default:
1467	    result = -1;
1468	    break;
1469	}
1470    }
1471    return result;
1472}
1473
1474static void
1475hpfuncvalue(ANSI *reply, KEY_DATA * kd)
1476{
1477#if OPT_HP_FUNC_KEYS
1478    int result;
1479
1480    if (kd->is_fkey) {
1481	switch (kd->keysym) {
1482	    MAP(XK_Fn(1), 'p');
1483	    MAP(XK_Fn(2), 'q');
1484	    MAP(XK_Fn(3), 'r');
1485	    MAP(XK_Fn(4), 's');
1486	    MAP(XK_Fn(5), 't');
1487	    MAP(XK_Fn(6), 'u');
1488	    MAP(XK_Fn(7), 'v');
1489	    MAP(XK_Fn(8), 'w');
1490	default:
1491	    result = -1;
1492	    break;
1493	}
1494    } else {
1495	switch (kd->keysym) {
1496	    MAP(XK_Up, 'A');
1497	    MAP(XK_Down, 'B');
1498	    MAP(XK_Right, 'C');
1499	    MAP(XK_Left, 'D');
1500	    MAP(XK_End, 'F');
1501	    MAP(XK_Clear, 'J');
1502	    MAP(XK_Delete, 'P');
1503	    MAP(XK_Insert, 'Q');
1504	    MAP(XK_Next, 'S');
1505	    MAP(XK_Prior, 'T');
1506	    MAP(XK_Home, 'h');
1507#ifdef XK_KP_Insert
1508	    MAP(XK_KP_Delete, 'P');
1509	    MAP(XK_KP_Insert, 'Q');
1510#endif
1511#ifdef DXK_Remove
1512	    MAP(DXK_Remove, 'P');
1513#endif
1514	    MAP(XK_Select, 'F');
1515	    MAP(XK_Find, 'h');
1516	default:
1517	    result = -1;
1518	    break;
1519	}
1520    }
1521    if (result > 0) {
1522	reply->a_type = ANSI_ESC;
1523	reply->a_final = (Char) result;
1524    }
1525#else
1526    (void) reply;
1527    (void) kd;
1528#endif /* OPT_HP_FUNC_KEYS */
1529}
1530
1531static void
1532scofuncvalue(ANSI *reply, KEY_DATA * kd)
1533{
1534#if OPT_SCO_FUNC_KEYS
1535    int result;
1536
1537    if (kd->is_fkey) {
1538	switch (kd->keysym) {
1539	    MAP(XK_Fn(1), 'M');
1540	    MAP(XK_Fn(2), 'N');
1541	    MAP(XK_Fn(3), 'O');
1542	    MAP(XK_Fn(4), 'P');
1543	    MAP(XK_Fn(5), 'Q');
1544	    MAP(XK_Fn(6), 'R');
1545	    MAP(XK_Fn(7), 'S');
1546	    MAP(XK_Fn(8), 'T');
1547	    MAP(XK_Fn(9), 'U');
1548	    MAP(XK_Fn(10), 'V');
1549	    MAP(XK_Fn(11), 'W');
1550	    MAP(XK_Fn(12), 'X');
1551	    MAP(XK_Fn(13), 'Y');
1552	    MAP(XK_Fn(14), 'Z');
1553	    MAP(XK_Fn(15), 'a');
1554	    MAP(XK_Fn(16), 'b');
1555	    MAP(XK_Fn(17), 'c');
1556	    MAP(XK_Fn(18), 'd');
1557	    MAP(XK_Fn(19), 'e');
1558	    MAP(XK_Fn(20), 'f');
1559	    MAP(XK_Fn(21), 'g');
1560	    MAP(XK_Fn(22), 'h');
1561	    MAP(XK_Fn(23), 'i');
1562	    MAP(XK_Fn(24), 'j');
1563	    MAP(XK_Fn(25), 'k');
1564	    MAP(XK_Fn(26), 'l');
1565	    MAP(XK_Fn(27), 'm');
1566	    MAP(XK_Fn(28), 'n');
1567	    MAP(XK_Fn(29), 'o');
1568	    MAP(XK_Fn(30), 'p');
1569	    MAP(XK_Fn(31), 'q');
1570	    MAP(XK_Fn(32), 'r');
1571	    MAP(XK_Fn(33), 's');
1572	    MAP(XK_Fn(34), 't');
1573	    MAP(XK_Fn(35), 'u');
1574	    MAP(XK_Fn(36), 'v');
1575	    MAP(XK_Fn(37), 'w');
1576	    MAP(XK_Fn(38), 'x');
1577	    MAP(XK_Fn(39), 'y');
1578	    MAP(XK_Fn(40), 'z');
1579	    MAP(XK_Fn(41), '@');
1580	    MAP(XK_Fn(42), '[');
1581	    MAP(XK_Fn(43), '\\');
1582	    MAP(XK_Fn(44), ']');
1583	    MAP(XK_Fn(45), '^');
1584	    MAP(XK_Fn(46), '_');
1585	    MAP(XK_Fn(47), '`');
1586	    MAP(XK_Fn(48), L_CURL);
1587	default:
1588	    result = -1;
1589	    break;
1590	}
1591    } else {
1592	switch (kd->keysym) {
1593	    MAP(XK_Up, 'A');
1594	    MAP(XK_Down, 'B');
1595	    MAP(XK_Right, 'C');
1596	    MAP(XK_Left, 'D');
1597	    MAP(XK_Begin, 'E');
1598	    MAP(XK_End, 'F');
1599	    MAP(XK_Insert, 'L');
1600	    MAP(XK_Next, 'G');
1601	    MAP(XK_Prior, 'I');
1602	    MAP(XK_Home, 'H');
1603#ifdef XK_KP_Insert
1604	    MAP(XK_KP_Insert, 'L');
1605#endif
1606	default:
1607	    result = -1;
1608	    break;
1609	}
1610    }
1611    if (result > 0) {
1612	reply->a_type = ANSI_CSI;
1613	reply->a_final = (Char) result;
1614    }
1615#else
1616    (void) reply;
1617    (void) kd;
1618#endif /* OPT_SCO_FUNC_KEYS */
1619}
1620
1621static void
1622sunfuncvalue(ANSI *reply, KEY_DATA * kd)
1623{
1624#if OPT_SUN_FUNC_KEYS
1625    ParmType result;
1626
1627    if (kd->is_fkey) {
1628	switch (kd->keysym) {
1629	    /* kf1-kf20 are numbered sequentially */
1630	    MAP(XK_Fn(1), 224);
1631	    MAP(XK_Fn(2), 225);
1632	    MAP(XK_Fn(3), 226);
1633	    MAP(XK_Fn(4), 227);
1634	    MAP(XK_Fn(5), 228);
1635	    MAP(XK_Fn(6), 229);
1636	    MAP(XK_Fn(7), 230);
1637	    MAP(XK_Fn(8), 231);
1638	    MAP(XK_Fn(9), 232);
1639	    MAP(XK_Fn(10), 233);
1640	    MAP(XK_Fn(11), 192);
1641	    MAP(XK_Fn(12), 193);
1642	    MAP(XK_Fn(13), 194);
1643	    MAP(XK_Fn(14), 195);	/* kund */
1644	    MAP(XK_Fn(15), 196);
1645	    MAP(XK_Fn(16), 197);	/* kcpy */
1646	    MAP(XK_Fn(17), 198);
1647	    MAP(XK_Fn(18), 199);
1648	    MAP(XK_Fn(19), 200);	/* kfnd */
1649	    MAP(XK_Fn(20), 201);
1650
1651	    /* kf31-kf36 are numbered sequentially */
1652	    MAP(XK_Fn(21), 208);	/* kf31 */
1653	    MAP(XK_Fn(22), 209);
1654	    MAP(XK_Fn(23), 210);
1655	    MAP(XK_Fn(24), 211);
1656	    MAP(XK_Fn(25), 212);
1657	    MAP(XK_Fn(26), 213);	/* kf36 */
1658
1659	    /* kf37-kf47 are interspersed with keypad keys */
1660	    MAP(XK_Fn(27), 214);	/* khome */
1661	    MAP(XK_Fn(28), 215);	/* kf38 */
1662	    MAP(XK_Fn(29), 216);	/* kpp */
1663	    MAP(XK_Fn(30), 217);	/* kf40 */
1664	    MAP(XK_Fn(31), 218);	/* kb2 */
1665	    MAP(XK_Fn(32), 219);	/* kf42 */
1666	    MAP(XK_Fn(33), 220);	/* kend */
1667	    MAP(XK_Fn(34), 221);	/* kf44 */
1668	    MAP(XK_Fn(35), 222);	/* knp */
1669	    MAP(XK_Fn(36), 234);	/* kf46 */
1670	    MAP(XK_Fn(37), 235);	/* kf47 */
1671	default:
1672	    result = -1;
1673	    break;
1674	}
1675    } else {
1676	switch (kd->keysym) {
1677	    MAP(XK_Help, 196);	/* khlp */
1678	    MAP(XK_Menu, 197);
1679
1680	    MAP(XK_Find, 1);
1681	    MAP(XK_Insert, 2);	/* kich1 */
1682	    MAP(XK_Delete, 3);
1683#ifdef XK_KP_Insert
1684	    MAP(XK_KP_Insert, 2);
1685	    MAP(XK_KP_Delete, 3);
1686#endif
1687#ifdef DXK_Remove
1688	    MAP(DXK_Remove, 3);
1689#endif
1690	    MAP(XK_Select, 4);
1691
1692	    MAP(XK_Prior, 216);
1693	    MAP(XK_Next, 222);
1694	    MAP(XK_Home, 214);
1695	    MAP(XK_End, 220);
1696	    MAP(XK_Begin, 218);	/* kf41=kb2 */
1697
1698	default:
1699	    result = -1;
1700	    break;
1701	}
1702    }
1703    if (result > 0) {
1704	reply->a_type = ANSI_CSI;
1705	reply->a_nparam = 1;
1706	reply->a_param[0] = result;
1707	reply->a_final = 'z';
1708    } else if (IsCursorKey(kd->keysym)) {
1709	reply->a_type = ANSI_SS3;
1710	reply->a_final = (Char) curfinal[kd->keysym - XK_Home];
1711    }
1712#else
1713    (void) reply;
1714    (void) kd;
1715#endif /* OPT_SUN_FUNC_KEYS */
1716}
1717
1718#if OPT_NUM_LOCK
1719#define isName(c) ((c) == '_' || (c) == '-' || isalnum(CharOf(c)))
1720
1721static const char *
1722skipName(const char *s)
1723{
1724    while (*s != '\0' && isName(CharOf(*s)))
1725	++s;
1726    return s;
1727}
1728
1729/*
1730 * Found a ":" in a translation, check what is past it to see if it contains
1731 * any of the insert-text action names.
1732 */
1733static Boolean
1734keyCanInsert(const char *parse)
1735{
1736    Boolean result = False;
1737    Boolean escape = False;
1738    Boolean quoted = False;
1739
1740    static const char *const table[] =
1741    {
1742	"insert",
1743	"insert-seven-bit",
1744	"insert-eight-bit",
1745	"string",
1746    };
1747    Cardinal n;
1748
1749    while (*parse != '\0' && *parse != '\n') {
1750	int ch = CharOf(*parse++);
1751	if (escape) {
1752	    escape = False;
1753	} else if (ch == '\\') {
1754	    escape = True;
1755	} else if (ch == '"') {
1756	    quoted = (Boolean) !quoted;
1757	} else if (!quoted && isName(ch)) {
1758	    const char *next = skipName(--parse);
1759	    size_t need = (size_t) (next - parse);
1760
1761	    for (n = 0; n < XtNumber(table); ++n) {
1762		if (need == strlen(table[n])
1763		    && !strncmp(parse, table[n], need)) {
1764		    result = True;
1765		    break;
1766		}
1767	    }
1768	    parse = next;
1769	}
1770
1771    }
1772    return result;
1773}
1774
1775/*
1776 * Strip the entire action, to avoid matching it.
1777 */
1778static char *
1779stripAction(char *base, char *last)
1780{
1781    while (last != base) {
1782	if (*--last == '\n') {
1783	    break;
1784	}
1785    }
1786    return last;
1787}
1788
1789static char *
1790stripBlanks(char *base, char *last)
1791{
1792    while (last != base) {
1793	int ch = CharOf(last[-1]);
1794	if (ch != ' ' && ch != '\t')
1795	    break;
1796	--last;
1797    }
1798    return last;
1799}
1800
1801/*
1802 * Strip unneeded whitespace from a translations resource, mono-casing and
1803 * returning a malloc'd copy of the result.
1804 */
1805static char *
1806stripTranslations(const char *s, Bool onlyInsert)
1807{
1808    char *dst = 0;
1809
1810    if (s != 0) {
1811	dst = TypeMallocN(char, strlen(s) + 1);
1812
1813	if (dst != 0) {
1814	    int state = 0;
1815	    int prv = 0;
1816	    char *d = dst;
1817
1818	    TRACE(("stripping:\n%s\n", s));
1819	    while (*s != '\0') {
1820		int ch = *s++;
1821		if (ch == '\n') {
1822		    if (d != dst)
1823			*d++ = (char) ch;
1824		    state = 0;
1825		} else if (strchr(":!#", ch) != 0) {
1826		    d = stripBlanks(dst, d);
1827		    if (onlyInsert && (ch == ':') && !keyCanInsert(s)) {
1828			d = stripAction(dst, d);
1829		    }
1830		    state = -1;
1831		} else if (state >= 0) {
1832		    if (isspace(CharOf(ch))) {
1833			if (state == 0 || strchr("<>~ \t", prv))
1834			    continue;
1835		    } else if (strchr("<>~", ch)) {
1836			d = stripBlanks(dst, d);
1837		    }
1838		    *d++ = x_toupper(ch);
1839		    ++state;
1840		}
1841		prv = ch;
1842	    }
1843	    *d = '\0';
1844	    TRACE(("...result:\n%s\n", dst));
1845	}
1846    }
1847    return dst;
1848}
1849
1850/*
1851 * Make a simple check to see if a given translations keyword appears in
1852 * xterm's translations resource.  It does not attempt to parse the strings,
1853 * just makes a case-independent check and ensures that the ends of the match
1854 * are on token-boundaries.
1855 *
1856 * That this can only retrieve translations that are given as resource values;
1857 * the default translations in charproc.c for example are not retrievable by
1858 * any interface to X.
1859 *
1860 * Also:  We can retrieve only the most-specified translation resource.  For
1861 * example, if the resource file specifies both "*translations" and
1862 * "XTerm*translations", we see only the latter.
1863 */
1864static Bool
1865TranslationsUseKeyword(Widget w, char **cache, const char *keyword, Bool onlyInsert)
1866{
1867    Bool result = False;
1868    char *copy;
1869    char *test;
1870
1871    if ((test = stripTranslations(keyword, onlyInsert)) != 0) {
1872	if (*cache == 0) {
1873	    String data = 0;
1874	    getKeymapResources(w, "vt100", "VT100", XtRString, &data, sizeof(data));
1875	    if (data != 0 && (copy = stripTranslations(data, onlyInsert)) != 0) {
1876		*cache = copy;
1877	    }
1878	}
1879
1880	if (*cache != 0) {
1881	    char *p = *cache;
1882	    int state = 0;
1883	    int now = ' ';
1884
1885	    while (*p != 0) {
1886		int prv = now;
1887		now = *p++;
1888		if (now == ':'
1889		    || now == '!') {
1890		    state = -1;
1891		} else if (now == '\n') {
1892		    state = 0;
1893		} else if (state >= 0) {
1894		    if (now == test[state]) {
1895			if ((state != 0
1896			     || !isName(prv))
1897			    && ((test[++state] == 0)
1898				&& !isName(*p))) {
1899			    result = True;
1900			    break;
1901			}
1902		    } else {
1903			state = 0;
1904		    }
1905		}
1906	    }
1907	}
1908	free(test);
1909    }
1910    TRACE(("TranslationsUseKeyword(%p, %s) = %d\n",
1911	   (void *) w, keyword, result));
1912    return result;
1913}
1914
1915static Bool
1916xtermHasTranslation(XtermWidget xw, const char *keyword, Bool onlyInsert)
1917{
1918    return (TranslationsUseKeyword(SHELL_OF(xw),
1919				   &(xw->keyboard.shell_translations),
1920				   keyword,
1921				   onlyInsert)
1922	    || TranslationsUseKeyword((Widget) xw,
1923				      &(xw->keyboard.xterm_translations),
1924				      keyword,
1925				      onlyInsert));
1926}
1927
1928#if OPT_EXTRA_PASTE
1929static void
1930addTranslation(XtermWidget xw, const char *fromString, const char *toString)
1931{
1932    size_t have = (xw->keyboard.extra_translations
1933		   ? strlen(xw->keyboard.extra_translations)
1934		   : 0);
1935    size_t need = (((have != 0) ? (have + 4) : 0)
1936		   + strlen(fromString)
1937		   + strlen(toString)
1938		   + 6);
1939
1940    if (!xtermHasTranslation(xw, fromString, False)) {
1941	xw->keyboard.extra_translations
1942	    = TypeRealloc(char, need, xw->keyboard.extra_translations);
1943	if ((xw->keyboard.extra_translations) != 0) {
1944	    TRACE(("adding %s: %s\n", fromString, toString));
1945	    if (have)
1946		strcat(xw->keyboard.extra_translations, " \\n\\");
1947	    sprintf(xw->keyboard.extra_translations, "%s: %s",
1948		    fromString, toString);
1949	    TRACE(("...{%s}\n", xw->keyboard.extra_translations));
1950	}
1951    }
1952}
1953#endif
1954
1955#define SaveMask(name)	xw->work.name |= (unsigned) mask;\
1956			TRACE(("SaveMask(%#x -> %s) %#x (%#x is%s modifier)\n", \
1957				(unsigned) keysym, #name, \
1958				xw->work.name, (unsigned) mask, \
1959				ModifierName((unsigned) mask)));
1960/*
1961 * Determine which modifier mask (if any) applies to the Num_Lock keysym.
1962 *
1963 * Also, determine which modifiers are associated with the ALT keys, so we can
1964 * send that information as a parameter for special keys in Sun/PC keyboard
1965 * mode.  However, if the ALT modifier is used in translations, we do not want
1966 * to confuse things by sending the parameter.
1967 */
1968void
1969VTInitModifiers(XtermWidget xw)
1970{
1971    Display *dpy = XtDisplay(xw);
1972    XModifierKeymap *keymap = XGetModifierMapping(dpy);
1973    KeySym keysym;
1974    int min_keycode, max_keycode, keysyms_per_keycode = 0;
1975
1976    if (keymap != 0) {
1977	KeySym *theMap;
1978	int keycode_count;
1979
1980	TRACE(("VTInitModifiers\n"));
1981
1982	XDisplayKeycodes(dpy, &min_keycode, &max_keycode);
1983	keycode_count = (max_keycode - min_keycode + 1);
1984	theMap = XGetKeyboardMapping(dpy,
1985				     (KeyCode) min_keycode,
1986				     keycode_count,
1987				     &keysyms_per_keycode);
1988
1989	if (theMap != 0) {
1990	    int i, j, k, l;
1991	    unsigned long mask;
1992
1993#if OPT_EXTRA_PASTE
1994	    /*
1995	     * Assume that if we can find the paste keysym in the X keyboard
1996	     * mapping that the server allows the corresponding translations
1997	     * resource.
1998	     */
1999	    int limit = (max_keycode - min_keycode) * keysyms_per_keycode;
2000	    for (i = 0; i < limit; ++i) {
2001#ifdef XF86XK_Paste
2002		if (theMap[i] == XF86XK_Paste) {
2003		    TRACE(("keyboard has XF86XK_Paste\n"));
2004		    addTranslation(xw,
2005				   ":<KeyPress> XF86Paste",
2006				   "insert-selection(SELECT, CUT_BUFFER0)");
2007		}
2008#endif
2009#ifdef SunXK_Paste
2010		if (theMap[i] == SunXK_Paste) {
2011		    TRACE(("keyboard has SunXK_Paste\n"));
2012		    addTranslation(xw,
2013				   ":<KeyPress> SunPaste",
2014				   "insert-selection(SELECT, CUT_BUFFER0)");
2015		}
2016#endif
2017	    }
2018#endif /* OPT_EXTRA_PASTE */
2019
2020	    for (i = k = 0, mask = 1; i < 8; i++, mask <<= 1) {
2021		for (j = 0; j < keymap->max_keypermod; j++) {
2022		    KeyCode code = keymap->modifiermap[k++];
2023		    if (code == 0)
2024			continue;
2025
2026		    for (l = 0; l < keysyms_per_keycode; ++l) {
2027#ifdef HAVE_XKBKEYCODETOKEYSYM
2028			keysym = XkbKeycodeToKeysym(dpy, code, 0, l);
2029#else
2030			keysym = XKeycodeToKeysym(dpy, code, l);
2031#endif
2032			if (keysym == NoSymbol) {
2033			    /* EMPTY */ ;
2034			} else if (keysym == XK_Num_Lock) {
2035			    SaveMask(num_lock);
2036			} else if (keysym == XK_Alt_L || keysym == XK_Alt_R) {
2037			    SaveMask(alt_mods);
2038			} else if (keysym == XK_Meta_L || keysym == XK_Meta_R) {
2039			    SaveMask(meta_mods);
2040			}
2041		    }
2042		}
2043	    }
2044	    XFree(theMap);
2045	}
2046
2047	/* Don't disable any mods if "alwaysUseMods" is true. */
2048	if (!xw->misc.alwaysUseMods) {
2049
2050	    /*
2051	     * Force TranslationsUseKeyword() to reload.
2052	     */
2053	    FreeAndNull(xw->keyboard.shell_translations);
2054	    FreeAndNull(xw->keyboard.xterm_translations);
2055
2056	    /*
2057	     * If the Alt modifier is used in translations, we would rather not
2058	     * use it to modify function-keys when NumLock is active.
2059	     */
2060	    if ((xw->work.alt_mods != 0)
2061		&& xtermHasTranslation(xw, "alt", True)) {
2062		TRACE(("ALT is used as a modifier in translations (ignore mask)\n"));
2063		xw->work.alt_mods = 0;
2064	    }
2065
2066	    /*
2067	     * If the Meta modifier is used in translations, we would rather not
2068	     * use it to modify function-keys.
2069	     */
2070	    if ((xw->work.meta_mods != 0)
2071		&& xtermHasTranslation(xw, "meta", True)) {
2072		TRACE(("META is used as a modifier in translations\n"));
2073		xw->work.meta_mods = 0;
2074	    }
2075	}
2076
2077	XFreeModifiermap(keymap);
2078    }
2079}
2080#endif /* OPT_NUM_LOCK */
2081