xref: /vim-8.2.3635/src/term.c (revision 2bf24176)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 /*
10  *
11  * term.c: functions for controlling the terminal
12  *
13  * primitive termcap support for Amiga, MSDOS, and Win32 included
14  *
15  * NOTE: padding and variable substitution is not performed,
16  * when compiling without HAVE_TGETENT, we use tputs() and tgoto() dummies.
17  */
18 
19 /*
20  * Some systems have a prototype for tgetstr() with (char *) instead of
21  * (char **). This define removes that prototype. We include our own prototype
22  * below.
23  */
24 
25 #define tgetstr tgetstr_defined_wrong
26 #include "vim.h"
27 
28 #ifdef HAVE_TGETENT
29 # ifdef HAVE_TERMIOS_H
30 #  include <termios.h>	    /* seems to be required for some Linux */
31 # endif
32 # ifdef HAVE_TERMCAP_H
33 #  include <termcap.h>
34 # endif
35 
36 /*
37  * A few linux systems define outfuntype in termcap.h to be used as the third
38  * argument for tputs().
39  */
40 # ifdef VMS
41 #  define TPUTSFUNCAST
42 # else
43 #  ifdef HAVE_OUTFUNTYPE
44 #   define TPUTSFUNCAST (outfuntype)
45 #  else
46 #   define TPUTSFUNCAST (int (*)())
47 #  endif
48 # endif
49 #endif
50 
51 #undef tgetstr
52 
53 /*
54  * Here are the builtin termcap entries.  They are not stored as complete
55  * structures with all entries, as such a structure is too big.
56  *
57  * The entries are compact, therefore they normally are included even when
58  * HAVE_TGETENT is defined. When HAVE_TGETENT is defined, the builtin entries
59  * can be accessed with "builtin_amiga", "builtin_ansi", "builtin_debug", etc.
60  *
61  * Each termcap is a list of builtin_term structures. It always starts with
62  * KS_NAME, which separates the entries.  See parse_builtin_tcap() for all
63  * details.
64  * bt_entry is either a KS_xxx code (>= 0), or a K_xxx code.
65  *
66  * Entries marked with "guessed" may be wrong.
67  */
68 struct builtin_term
69 {
70     int		bt_entry;
71     char	*bt_string;
72 };
73 
74 /* start of keys that are not directly used by Vim but can be mapped */
75 #define BT_EXTRA_KEYS	0x101
76 
77 static struct builtin_term *find_builtin_term __ARGS((char_u *name));
78 static void parse_builtin_tcap __ARGS((char_u *s));
79 static void term_color __ARGS((char_u *s, int n));
80 static void gather_termleader __ARGS((void));
81 #ifdef FEAT_TERMRESPONSE
82 static void req_codes_from_term __ARGS((void));
83 static void req_more_codes_from_term __ARGS((void));
84 static void got_code_from_term __ARGS((char_u *code, int len));
85 static void check_for_codes_from_term __ARGS((void));
86 #endif
87 #if defined(FEAT_GUI) \
88     || (defined(FEAT_MOUSE) && (!defined(UNIX) || defined(FEAT_MOUSE_XTERM) \
89 		|| defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)))
90 static int get_bytes_from_buf __ARGS((char_u *, char_u *, int));
91 #endif
92 static void del_termcode_idx __ARGS((int idx));
93 static int term_is_builtin __ARGS((char_u *name));
94 static int term_7to8bit __ARGS((char_u *p));
95 #ifdef FEAT_TERMRESPONSE
96 static void switch_to_8bit __ARGS((void));
97 #endif
98 
99 #ifdef HAVE_TGETENT
100 static char_u *tgetent_error __ARGS((char_u *, char_u *));
101 
102 /*
103  * Here is our own prototype for tgetstr(), any prototypes from the include
104  * files have been disabled by the define at the start of this file.
105  */
106 char		*tgetstr __ARGS((char *, char **));
107 
108 # ifdef FEAT_TERMRESPONSE
109     /* Change this to "if 1" to debug what happens with termresponse. */
110 #  if 0
111 #   define DEBUG_TERMRESPONSE
112     static void log_tr(char *msg);
113 #   define LOG_TR(msg) log_tr(msg)
114 #  else
115 #   define LOG_TR(msg)
116 #  endif
117 /* Request Terminal Version status: */
118 #  define CRV_GET	1	/* send T_CRV when switched to RAW mode */
119 #  define CRV_SENT	2	/* did send T_CRV, waiting for answer */
120 #  define CRV_GOT	3	/* received T_CRV response */
121 static int crv_status = CRV_GET;
122 /* Request Cursor position report: */
123 #  define U7_GET	1	/* send T_U7 when switched to RAW mode */
124 #  define U7_SENT	2	/* did send T_U7, waiting for answer */
125 #  define U7_GOT	3	/* received T_U7 response */
126 static int u7_status = U7_GET;
127 /* Request background color report: */
128 #  define RBG_GET	1	/* send T_RBG when switched to RAW mode */
129 #  define RBG_SENT	2	/* did send T_RBG, waiting for answer */
130 #  define RBG_GOT	3	/* received T_RBG response */
131 static int rbg_status = RBG_GET;
132 # endif
133 
134 /*
135  * Don't declare these variables if termcap.h contains them.
136  * Autoconf checks if these variables should be declared extern (not all
137  * systems have them).
138  * Some versions define ospeed to be speed_t, but that is incompatible with
139  * BSD, where ospeed is short and speed_t is long.
140  */
141 # ifndef HAVE_OSPEED
142 #  ifdef OSPEED_EXTERN
143 extern short ospeed;
144 #   else
145 short ospeed;
146 #   endif
147 # endif
148 # ifndef HAVE_UP_BC_PC
149 #  ifdef UP_BC_PC_EXTERN
150 extern char *UP, *BC, PC;
151 #  else
152 char *UP, *BC, PC;
153 #  endif
154 # endif
155 
156 # define TGETSTR(s, p)	vim_tgetstr((s), (p))
157 # define TGETENT(b, t)	tgetent((char *)(b), (char *)(t))
158 static char_u *vim_tgetstr __ARGS((char *s, char_u **pp));
159 #endif /* HAVE_TGETENT */
160 
161 static int  detected_8bit = FALSE;	/* detected 8-bit terminal */
162 
163 static struct builtin_term builtin_termcaps[] =
164 {
165 
166 #if defined(FEAT_GUI)
167 /*
168  * GUI pseudo term-cap.
169  */
170     {(int)KS_NAME,	"gui"},
171     {(int)KS_CE,	IF_EB("\033|$", ESC_STR "|$")},
172     {(int)KS_AL,	IF_EB("\033|i", ESC_STR "|i")},
173 # ifdef TERMINFO
174     {(int)KS_CAL,	IF_EB("\033|%p1%dI", ESC_STR "|%p1%dI")},
175 # else
176     {(int)KS_CAL,	IF_EB("\033|%dI", ESC_STR "|%dI")},
177 # endif
178     {(int)KS_DL,	IF_EB("\033|d", ESC_STR "|d")},
179 # ifdef TERMINFO
180     {(int)KS_CDL,	IF_EB("\033|%p1%dD", ESC_STR "|%p1%dD")},
181     {(int)KS_CS,	IF_EB("\033|%p1%d;%p2%dR", ESC_STR "|%p1%d;%p2%dR")},
182 #  ifdef FEAT_VERTSPLIT
183     {(int)KS_CSV,	IF_EB("\033|%p1%d;%p2%dV", ESC_STR "|%p1%d;%p2%dV")},
184 #  endif
185 # else
186     {(int)KS_CDL,	IF_EB("\033|%dD", ESC_STR "|%dD")},
187     {(int)KS_CS,	IF_EB("\033|%d;%dR", ESC_STR "|%d;%dR")},
188 #  ifdef FEAT_VERTSPLIT
189     {(int)KS_CSV,	IF_EB("\033|%d;%dV", ESC_STR "|%d;%dV")},
190 #  endif
191 # endif
192     {(int)KS_CL,	IF_EB("\033|C", ESC_STR "|C")},
193 			/* attributes switched on with 'h', off with * 'H' */
194     {(int)KS_ME,	IF_EB("\033|31H", ESC_STR "|31H")}, /* HL_ALL */
195     {(int)KS_MR,	IF_EB("\033|1h", ESC_STR "|1h")},   /* HL_INVERSE */
196     {(int)KS_MD,	IF_EB("\033|2h", ESC_STR "|2h")},   /* HL_BOLD */
197     {(int)KS_SE,	IF_EB("\033|16H", ESC_STR "|16H")}, /* HL_STANDOUT */
198     {(int)KS_SO,	IF_EB("\033|16h", ESC_STR "|16h")}, /* HL_STANDOUT */
199     {(int)KS_UE,	IF_EB("\033|8H", ESC_STR "|8H")},   /* HL_UNDERLINE */
200     {(int)KS_US,	IF_EB("\033|8h", ESC_STR "|8h")},   /* HL_UNDERLINE */
201     {(int)KS_UCE,	IF_EB("\033|8C", ESC_STR "|8C")},   /* HL_UNDERCURL */
202     {(int)KS_UCS,	IF_EB("\033|8c", ESC_STR "|8c")},   /* HL_UNDERCURL */
203     {(int)KS_CZR,	IF_EB("\033|4H", ESC_STR "|4H")},   /* HL_ITALIC */
204     {(int)KS_CZH,	IF_EB("\033|4h", ESC_STR "|4h")},   /* HL_ITALIC */
205     {(int)KS_VB,	IF_EB("\033|f", ESC_STR "|f")},
206     {(int)KS_MS,	"y"},
207     {(int)KS_UT,	"y"},
208     {(int)KS_XN,	"y"},
209     {(int)KS_LE,	"\b"},		/* cursor-left = BS */
210     {(int)KS_ND,	"\014"},	/* cursor-right = CTRL-L */
211 # ifdef TERMINFO
212     {(int)KS_CM,	IF_EB("\033|%p1%d;%p2%dM", ESC_STR "|%p1%d;%p2%dM")},
213 # else
214     {(int)KS_CM,	IF_EB("\033|%d;%dM", ESC_STR "|%d;%dM")},
215 # endif
216 	/* there are no key sequences here, the GUI sequences are recognized
217 	 * in check_termcode() */
218 #endif
219 
220 #ifndef NO_BUILTIN_TCAPS
221 
222 # if defined(AMIGA) || defined(ALL_BUILTIN_TCAPS)
223 /*
224  * Amiga console window, default for Amiga
225  */
226     {(int)KS_NAME,	"amiga"},
227     {(int)KS_CE,	"\033[K"},
228     {(int)KS_CD,	"\033[J"},
229     {(int)KS_AL,	"\033[L"},
230 #  ifdef TERMINFO
231     {(int)KS_CAL,	"\033[%p1%dL"},
232 #  else
233     {(int)KS_CAL,	"\033[%dL"},
234 #  endif
235     {(int)KS_DL,	"\033[M"},
236 #  ifdef TERMINFO
237     {(int)KS_CDL,	"\033[%p1%dM"},
238 #  else
239     {(int)KS_CDL,	"\033[%dM"},
240 #  endif
241     {(int)KS_CL,	"\014"},
242     {(int)KS_VI,	"\033[0 p"},
243     {(int)KS_VE,	"\033[1 p"},
244     {(int)KS_ME,	"\033[0m"},
245     {(int)KS_MR,	"\033[7m"},
246     {(int)KS_MD,	"\033[1m"},
247     {(int)KS_SE,	"\033[0m"},
248     {(int)KS_SO,	"\033[33m"},
249     {(int)KS_US,	"\033[4m"},
250     {(int)KS_UE,	"\033[0m"},
251     {(int)KS_CZH,	"\033[3m"},
252     {(int)KS_CZR,	"\033[0m"},
253 #if defined(__MORPHOS__) || defined(__AROS__)
254     {(int)KS_CCO,	"8"},		/* allow 8 colors */
255 #  ifdef TERMINFO
256     {(int)KS_CAB,	"\033[4%p1%dm"},/* set background color */
257     {(int)KS_CAF,	"\033[3%p1%dm"},/* set foreground color */
258 #  else
259     {(int)KS_CAB,	"\033[4%dm"},	/* set background color */
260     {(int)KS_CAF,	"\033[3%dm"},	/* set foreground color */
261 #  endif
262     {(int)KS_OP,	"\033[m"},	/* reset colors */
263 #endif
264     {(int)KS_MS,	"y"},
265     {(int)KS_UT,	"y"},		/* guessed */
266     {(int)KS_LE,	"\b"},
267 #  ifdef TERMINFO
268     {(int)KS_CM,	"\033[%i%p1%d;%p2%dH"},
269 #  else
270     {(int)KS_CM,	"\033[%i%d;%dH"},
271 #  endif
272 #if defined(__MORPHOS__)
273     {(int)KS_SR,	"\033M"},
274 #endif
275 #  ifdef TERMINFO
276     {(int)KS_CRI,	"\033[%p1%dC"},
277 #  else
278     {(int)KS_CRI,	"\033[%dC"},
279 #  endif
280     {K_UP,		"\233A"},
281     {K_DOWN,		"\233B"},
282     {K_LEFT,		"\233D"},
283     {K_RIGHT,		"\233C"},
284     {K_S_UP,		"\233T"},
285     {K_S_DOWN,		"\233S"},
286     {K_S_LEFT,		"\233 A"},
287     {K_S_RIGHT,		"\233 @"},
288     {K_S_TAB,		"\233Z"},
289     {K_F1,		"\233\060~"},/* some compilers don't dig "\2330" */
290     {K_F2,		"\233\061~"},
291     {K_F3,		"\233\062~"},
292     {K_F4,		"\233\063~"},
293     {K_F5,		"\233\064~"},
294     {K_F6,		"\233\065~"},
295     {K_F7,		"\233\066~"},
296     {K_F8,		"\233\067~"},
297     {K_F9,		"\233\070~"},
298     {K_F10,		"\233\071~"},
299     {K_S_F1,		"\233\061\060~"},
300     {K_S_F2,		"\233\061\061~"},
301     {K_S_F3,		"\233\061\062~"},
302     {K_S_F4,		"\233\061\063~"},
303     {K_S_F5,		"\233\061\064~"},
304     {K_S_F6,		"\233\061\065~"},
305     {K_S_F7,		"\233\061\066~"},
306     {K_S_F8,		"\233\061\067~"},
307     {K_S_F9,		"\233\061\070~"},
308     {K_S_F10,		"\233\061\071~"},
309     {K_HELP,		"\233?~"},
310     {K_INS,		"\233\064\060~"},	/* 101 key keyboard */
311     {K_PAGEUP,		"\233\064\061~"},	/* 101 key keyboard */
312     {K_PAGEDOWN,	"\233\064\062~"},	/* 101 key keyboard */
313     {K_HOME,		"\233\064\064~"},	/* 101 key keyboard */
314     {K_END,		"\233\064\065~"},	/* 101 key keyboard */
315 
316     {BT_EXTRA_KEYS,	""},
317     {TERMCAP2KEY('#', '2'), "\233\065\064~"},	/* shifted home key */
318     {TERMCAP2KEY('#', '3'), "\233\065\060~"},	/* shifted insert key */
319     {TERMCAP2KEY('*', '7'), "\233\065\065~"},	/* shifted end key */
320 # endif
321 
322 # if defined(__BEOS__) || defined(ALL_BUILTIN_TCAPS)
323 /*
324  * almost standard ANSI terminal, default for bebox
325  */
326     {(int)KS_NAME,	"beos-ansi"},
327     {(int)KS_CE,	"\033[K"},
328     {(int)KS_CD,	"\033[J"},
329     {(int)KS_AL,	"\033[L"},
330 #  ifdef TERMINFO
331     {(int)KS_CAL,	"\033[%p1%dL"},
332 #  else
333     {(int)KS_CAL,	"\033[%dL"},
334 #  endif
335     {(int)KS_DL,	"\033[M"},
336 #  ifdef TERMINFO
337     {(int)KS_CDL,	"\033[%p1%dM"},
338 #  else
339     {(int)KS_CDL,	"\033[%dM"},
340 #  endif
341 #ifdef BEOS_PR_OR_BETTER
342 #  ifdef TERMINFO
343     {(int)KS_CS,	"\033[%i%p1%d;%p2%dr"},
344 #  else
345     {(int)KS_CS,	"\033[%i%d;%dr"},	/* scroll region */
346 #  endif
347 #endif
348     {(int)KS_CL,	"\033[H\033[2J"},
349 #ifdef notyet
350     {(int)KS_VI,	"[VI]"}, /* cursor invisible, VT320: CSI ? 25 l */
351     {(int)KS_VE,	"[VE]"}, /* cursor visible, VT320: CSI ? 25 h */
352 #endif
353     {(int)KS_ME,	"\033[m"},	/* normal mode */
354     {(int)KS_MR,	"\033[7m"},	/* reverse */
355     {(int)KS_MD,	"\033[1m"},	/* bold */
356     {(int)KS_SO,	"\033[31m"},	/* standout mode: red */
357     {(int)KS_SE,	"\033[m"},	/* standout end */
358     {(int)KS_CZH,	"\033[35m"},	/* italic: purple */
359     {(int)KS_CZR,	"\033[m"},	/* italic end */
360     {(int)KS_US,	"\033[4m"},	/* underscore mode */
361     {(int)KS_UE,	"\033[m"},	/* underscore end */
362     {(int)KS_CCO,	"8"},		/* allow 8 colors */
363 #  ifdef TERMINFO
364     {(int)KS_CAB,	"\033[4%p1%dm"},/* set background color */
365     {(int)KS_CAF,	"\033[3%p1%dm"},/* set foreground color */
366 #  else
367     {(int)KS_CAB,	"\033[4%dm"},	/* set background color */
368     {(int)KS_CAF,	"\033[3%dm"},	/* set foreground color */
369 #  endif
370     {(int)KS_OP,	"\033[m"},	/* reset colors */
371     {(int)KS_MS,	"y"},		/* safe to move cur in reverse mode */
372     {(int)KS_UT,	"y"},		/* guessed */
373     {(int)KS_LE,	"\b"},
374 #  ifdef TERMINFO
375     {(int)KS_CM,	"\033[%i%p1%d;%p2%dH"},
376 #  else
377     {(int)KS_CM,	"\033[%i%d;%dH"},
378 #  endif
379     {(int)KS_SR,	"\033M"},
380 #  ifdef TERMINFO
381     {(int)KS_CRI,	"\033[%p1%dC"},
382 #  else
383     {(int)KS_CRI,	"\033[%dC"},
384 #  endif
385 #if defined(BEOS_DR8)
386     {(int)KS_DB,	""},		/* hack! see screen.c */
387 #endif
388 
389     {K_UP,		"\033[A"},
390     {K_DOWN,		"\033[B"},
391     {K_LEFT,		"\033[D"},
392     {K_RIGHT,		"\033[C"},
393 # endif
394 
395 # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS) || defined(SOME_BUILTIN_TCAPS) || defined(__EMX__)
396 /*
397  * standard ANSI terminal, default for unix
398  */
399     {(int)KS_NAME,	"ansi"},
400     {(int)KS_CE,	IF_EB("\033[K", ESC_STR "[K")},
401     {(int)KS_AL,	IF_EB("\033[L", ESC_STR "[L")},
402 #  ifdef TERMINFO
403     {(int)KS_CAL,	IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")},
404 #  else
405     {(int)KS_CAL,	IF_EB("\033[%dL", ESC_STR "[%dL")},
406 #  endif
407     {(int)KS_DL,	IF_EB("\033[M", ESC_STR "[M")},
408 #  ifdef TERMINFO
409     {(int)KS_CDL,	IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")},
410 #  else
411     {(int)KS_CDL,	IF_EB("\033[%dM", ESC_STR "[%dM")},
412 #  endif
413     {(int)KS_CL,	IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")},
414     {(int)KS_ME,	IF_EB("\033[0m", ESC_STR "[0m")},
415     {(int)KS_MR,	IF_EB("\033[7m", ESC_STR "[7m")},
416     {(int)KS_MS,	"y"},
417     {(int)KS_UT,	"y"},		/* guessed */
418     {(int)KS_LE,	"\b"},
419 #  ifdef TERMINFO
420     {(int)KS_CM,	IF_EB("\033[%i%p1%d;%p2%dH", ESC_STR "[%i%p1%d;%p2%dH")},
421 #  else
422     {(int)KS_CM,	IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")},
423 #  endif
424 #  ifdef TERMINFO
425     {(int)KS_CRI,	IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")},
426 #  else
427     {(int)KS_CRI,	IF_EB("\033[%dC", ESC_STR "[%dC")},
428 #  endif
429 # endif
430 
431 # if defined(MSDOS) || defined(ALL_BUILTIN_TCAPS) || defined(__EMX__)
432 /*
433  * These codes are valid when nansi.sys or equivalent has been installed.
434  * Function keys on a PC are preceded with a NUL. These are converted into
435  * K_NUL '\316' in mch_inchar(), because we cannot handle NULs in key codes.
436  * CTRL-arrow is used instead of SHIFT-arrow.
437  */
438 #ifdef __EMX__
439     {(int)KS_NAME,	"os2ansi"},
440 #else
441     {(int)KS_NAME,	"pcansi"},
442     {(int)KS_DL,	"\033[M"},
443     {(int)KS_AL,	"\033[L"},
444 #endif
445     {(int)KS_CE,	"\033[K"},
446     {(int)KS_CL,	"\033[2J"},
447     {(int)KS_ME,	"\033[0m"},
448     {(int)KS_MR,	"\033[5m"},	/* reverse: black on lightgrey */
449     {(int)KS_MD,	"\033[1m"},	/* bold: white text */
450     {(int)KS_SE,	"\033[0m"},	/* standout end */
451     {(int)KS_SO,	"\033[31m"},	/* standout: white on blue */
452     {(int)KS_CZH,	"\033[34;43m"},	/* italic mode: blue text on yellow */
453     {(int)KS_CZR,	"\033[0m"},	/* italic mode end */
454     {(int)KS_US,	"\033[36;41m"},	/* underscore mode: cyan text on red */
455     {(int)KS_UE,	"\033[0m"},	/* underscore mode end */
456     {(int)KS_CCO,	"8"},		/* allow 8 colors */
457 #  ifdef TERMINFO
458     {(int)KS_CAB,	"\033[4%p1%dm"},/* set background color */
459     {(int)KS_CAF,	"\033[3%p1%dm"},/* set foreground color */
460 #  else
461     {(int)KS_CAB,	"\033[4%dm"},	/* set background color */
462     {(int)KS_CAF,	"\033[3%dm"},	/* set foreground color */
463 #  endif
464     {(int)KS_OP,	"\033[0m"},	/* reset colors */
465     {(int)KS_MS,	"y"},
466     {(int)KS_UT,	"y"},		/* guessed */
467     {(int)KS_LE,	"\b"},
468 #  ifdef TERMINFO
469     {(int)KS_CM,	"\033[%i%p1%d;%p2%dH"},
470 #  else
471     {(int)KS_CM,	"\033[%i%d;%dH"},
472 #  endif
473 #  ifdef TERMINFO
474     {(int)KS_CRI,	"\033[%p1%dC"},
475 #  else
476     {(int)KS_CRI,	"\033[%dC"},
477 #  endif
478     {K_UP,		"\316H"},
479     {K_DOWN,		"\316P"},
480     {K_LEFT,		"\316K"},
481     {K_RIGHT,		"\316M"},
482     {K_S_LEFT,		"\316s"},
483     {K_S_RIGHT,		"\316t"},
484     {K_F1,		"\316;"},
485     {K_F2,		"\316<"},
486     {K_F3,		"\316="},
487     {K_F4,		"\316>"},
488     {K_F5,		"\316?"},
489     {K_F6,		"\316@"},
490     {K_F7,		"\316A"},
491     {K_F8,		"\316B"},
492     {K_F9,		"\316C"},
493     {K_F10,		"\316D"},
494     {K_F11,		"\316\205"},	/* guessed */
495     {K_F12,		"\316\206"},	/* guessed */
496     {K_S_F1,		"\316T"},
497     {K_S_F2,		"\316U"},
498     {K_S_F3,		"\316V"},
499     {K_S_F4,		"\316W"},
500     {K_S_F5,		"\316X"},
501     {K_S_F6,		"\316Y"},
502     {K_S_F7,		"\316Z"},
503     {K_S_F8,		"\316["},
504     {K_S_F9,		"\316\\"},
505     {K_S_F10,		"\316]"},
506     {K_S_F11,		"\316\207"},	/* guessed */
507     {K_S_F12,		"\316\210"},	/* guessed */
508     {K_INS,		"\316R"},
509     {K_DEL,		"\316S"},
510     {K_HOME,		"\316G"},
511     {K_END,		"\316O"},
512     {K_PAGEDOWN,	"\316Q"},
513     {K_PAGEUP,		"\316I"},
514 # endif
515 
516 # if defined(MSDOS)
517 /*
518  * These codes are valid for the pc video.  The entries that start with ESC |
519  * are translated into conio calls in os_msdos.c. Default for MSDOS.
520  */
521     {(int)KS_NAME,	"pcterm"},
522     {(int)KS_CE,	"\033|K"},
523     {(int)KS_AL,	"\033|L"},
524     {(int)KS_DL,	"\033|M"},
525 #  ifdef TERMINFO
526     {(int)KS_CS,	"\033|%i%p1%d;%p2%dr"},
527 #   ifdef FEAT_VERTSPLIT
528     {(int)KS_CSV,	"\033|%i%p1%d;%p2%dV"},
529 #   endif
530 #  else
531     {(int)KS_CS,	"\033|%i%d;%dr"},
532 #   ifdef FEAT_VERTSPLIT
533     {(int)KS_CSV,	"\033|%i%d;%dV"},
534 #   endif
535 #  endif
536     {(int)KS_CL,	"\033|J"},
537     {(int)KS_ME,	"\033|0m"},	/* normal */
538     {(int)KS_MR,	"\033|112m"},	/* reverse: black on lightgrey */
539     {(int)KS_MD,	"\033|15m"},	/* bold: white text */
540     {(int)KS_SE,	"\033|0m"},	/* standout end */
541     {(int)KS_SO,	"\033|31m"},	/* standout: white on blue */
542     {(int)KS_CZH,	"\033|225m"},	/* italic mode: blue text on yellow */
543     {(int)KS_CZR,	"\033|0m"},	/* italic mode end */
544     {(int)KS_US,	"\033|67m"},	/* underscore mode: cyan text on red */
545     {(int)KS_UE,	"\033|0m"},	/* underscore mode end */
546     {(int)KS_CCO,	"16"},		/* allow 16 colors */
547 #  ifdef TERMINFO
548     {(int)KS_CAB,	"\033|%p1%db"},	/* set background color */
549     {(int)KS_CAF,	"\033|%p1%df"},	/* set foreground color */
550 #  else
551     {(int)KS_CAB,	"\033|%db"},	/* set background color */
552     {(int)KS_CAF,	"\033|%df"},	/* set foreground color */
553 #  endif
554     {(int)KS_MS,	"y"},
555     {(int)KS_UT,	"y"},
556     {(int)KS_LE,	"\b"},
557 #  ifdef TERMINFO
558     {(int)KS_CM,	"\033|%i%p1%d;%p2%dH"},
559 #  else
560     {(int)KS_CM,	"\033|%i%d;%dH"},
561 #  endif
562 #ifdef DJGPP
563     {(int)KS_VB,	"\033|B"},	/* visual bell */
564 #endif
565     {K_UP,		"\316H"},
566     {K_DOWN,		"\316P"},
567     {K_LEFT,		"\316K"},
568     {K_RIGHT,		"\316M"},
569     {K_S_LEFT,		"\316s"},
570     {K_S_RIGHT,		"\316t"},
571     {K_S_TAB,		"\316\017"},
572     {K_F1,		"\316;"},
573     {K_F2,		"\316<"},
574     {K_F3,		"\316="},
575     {K_F4,		"\316>"},
576     {K_F5,		"\316?"},
577     {K_F6,		"\316@"},
578     {K_F7,		"\316A"},
579     {K_F8,		"\316B"},
580     {K_F9,		"\316C"},
581     {K_F10,		"\316D"},
582     {K_F11,		"\316\205"},
583     {K_F12,		"\316\206"},
584     {K_S_F1,		"\316T"},
585     {K_S_F2,		"\316U"},
586     {K_S_F3,		"\316V"},
587     {K_S_F4,		"\316W"},
588     {K_S_F5,		"\316X"},
589     {K_S_F6,		"\316Y"},
590     {K_S_F7,		"\316Z"},
591     {K_S_F8,		"\316["},
592     {K_S_F9,		"\316\\"},
593     {K_S_F10,		"\316]"},
594     {K_S_F11,		"\316\207"},
595     {K_S_F12,		"\316\210"},
596     {K_INS,		"\316R"},
597     {K_DEL,		"\316S"},
598     {K_HOME,		"\316G"},
599     {K_END,		"\316O"},
600     {K_PAGEDOWN,	"\316Q"},
601     {K_PAGEUP,		"\316I"},
602     {K_KPLUS,		"\316N"},
603     {K_KMINUS,		"\316J"},
604     {K_KMULTIPLY,	"\3167"},
605     {K_K0,		"\316\332"},
606     {K_K1,		"\316\336"},
607     {K_K2,		"\316\342"},
608     {K_K3,		"\316\346"},
609     {K_K4,		"\316\352"},
610     {K_K5,		"\316\356"},
611     {K_K6,		"\316\362"},
612     {K_K7,		"\316\366"},
613     {K_K8,		"\316\372"},
614     {K_K9,		"\316\376"},
615 # endif
616 
617 # if defined(WIN3264) || defined(ALL_BUILTIN_TCAPS) || defined(__EMX__)
618 /*
619  * These codes are valid for the Win32 Console .  The entries that start with
620  * ESC | are translated into console calls in os_win32.c.  The function keys
621  * are also translated in os_win32.c.
622  */
623     {(int)KS_NAME,	"win32"},
624     {(int)KS_CE,	"\033|K"},	/* clear to end of line */
625     {(int)KS_AL,	"\033|L"},	/* add new blank line */
626 #  ifdef TERMINFO
627     {(int)KS_CAL,	"\033|%p1%dL"},	/* add number of new blank lines */
628 #  else
629     {(int)KS_CAL,	"\033|%dL"},	/* add number of new blank lines */
630 #  endif
631     {(int)KS_DL,	"\033|M"},	/* delete line */
632 #  ifdef TERMINFO
633     {(int)KS_CDL,	"\033|%p1%dM"},	/* delete number of lines */
634 #  else
635     {(int)KS_CDL,	"\033|%dM"},	/* delete number of lines */
636 #  endif
637     {(int)KS_CL,	"\033|J"},	/* clear screen */
638     {(int)KS_CD,	"\033|j"},	/* clear to end of display */
639     {(int)KS_VI,	"\033|v"},	/* cursor invisible */
640     {(int)KS_VE,	"\033|V"},	/* cursor visible */
641 
642     {(int)KS_ME,	"\033|0m"},	/* normal */
643     {(int)KS_MR,	"\033|112m"},	/* reverse: black on lightgray */
644     {(int)KS_MD,	"\033|15m"},	/* bold: white on black */
645 #if 1
646     {(int)KS_SO,	"\033|31m"},	/* standout: white on blue */
647     {(int)KS_SE,	"\033|0m"},	/* standout end */
648 #else
649     {(int)KS_SO,	"\033|F"},	/* standout: high intensity */
650     {(int)KS_SE,	"\033|f"},	/* standout end */
651 #endif
652     {(int)KS_CZH,	"\033|225m"},	/* italic: blue text on yellow */
653     {(int)KS_CZR,	"\033|0m"},	/* italic end */
654     {(int)KS_US,	"\033|67m"},	/* underscore: cyan text on red */
655     {(int)KS_UE,	"\033|0m"},	/* underscore end */
656     {(int)KS_CCO,	"16"},		/* allow 16 colors */
657 #  ifdef TERMINFO
658     {(int)KS_CAB,	"\033|%p1%db"},	/* set background color */
659     {(int)KS_CAF,	"\033|%p1%df"},	/* set foreground color */
660 #  else
661     {(int)KS_CAB,	"\033|%db"},	/* set background color */
662     {(int)KS_CAF,	"\033|%df"},	/* set foreground color */
663 #  endif
664 
665     {(int)KS_MS,	"y"},		/* save to move cur in reverse mode */
666     {(int)KS_UT,	"y"},
667     {(int)KS_XN,	"y"},
668     {(int)KS_LE,	"\b"},
669 #  ifdef TERMINFO
670     {(int)KS_CM,	"\033|%i%p1%d;%p2%dH"},/* cursor motion */
671 #  else
672     {(int)KS_CM,	"\033|%i%d;%dH"},/* cursor motion */
673 #  endif
674     {(int)KS_VB,	"\033|B"},	/* visual bell */
675     {(int)KS_TI,	"\033|S"},	/* put terminal in termcap mode */
676     {(int)KS_TE,	"\033|E"},	/* out of termcap mode */
677 #  ifdef TERMINFO
678     {(int)KS_CS,	"\033|%i%p1%d;%p2%dr"},/* scroll region */
679 #  else
680     {(int)KS_CS,	"\033|%i%d;%dr"},/* scroll region */
681 #  endif
682 
683     {K_UP,		"\316H"},
684     {K_DOWN,		"\316P"},
685     {K_LEFT,		"\316K"},
686     {K_RIGHT,		"\316M"},
687     {K_S_UP,		"\316\304"},
688     {K_S_DOWN,		"\316\317"},
689     {K_S_LEFT,		"\316\311"},
690     {K_C_LEFT,		"\316s"},
691     {K_S_RIGHT,		"\316\313"},
692     {K_C_RIGHT,		"\316t"},
693     {K_S_TAB,		"\316\017"},
694     {K_F1,		"\316;"},
695     {K_F2,		"\316<"},
696     {K_F3,		"\316="},
697     {K_F4,		"\316>"},
698     {K_F5,		"\316?"},
699     {K_F6,		"\316@"},
700     {K_F7,		"\316A"},
701     {K_F8,		"\316B"},
702     {K_F9,		"\316C"},
703     {K_F10,		"\316D"},
704     {K_F11,		"\316\205"},
705     {K_F12,		"\316\206"},
706     {K_S_F1,		"\316T"},
707     {K_S_F2,		"\316U"},
708     {K_S_F3,		"\316V"},
709     {K_S_F4,		"\316W"},
710     {K_S_F5,		"\316X"},
711     {K_S_F6,		"\316Y"},
712     {K_S_F7,		"\316Z"},
713     {K_S_F8,		"\316["},
714     {K_S_F9,		"\316\\"},
715     {K_S_F10,		"\316]"},
716     {K_S_F11,		"\316\207"},
717     {K_S_F12,		"\316\210"},
718     {K_INS,		"\316R"},
719     {K_DEL,		"\316S"},
720     {K_HOME,		"\316G"},
721     {K_S_HOME,		"\316\302"},
722     {K_C_HOME,		"\316w"},
723     {K_END,		"\316O"},
724     {K_S_END,		"\316\315"},
725     {K_C_END,		"\316u"},
726     {K_PAGEDOWN,	"\316Q"},
727     {K_PAGEUP,		"\316I"},
728     {K_KPLUS,		"\316N"},
729     {K_KMINUS,		"\316J"},
730     {K_KMULTIPLY,	"\316\067"},
731     {K_K0,		"\316\332"},
732     {K_K1,		"\316\336"},
733     {K_K2,		"\316\342"},
734     {K_K3,		"\316\346"},
735     {K_K4,		"\316\352"},
736     {K_K5,		"\316\356"},
737     {K_K6,		"\316\362"},
738     {K_K7,		"\316\366"},
739     {K_K8,		"\316\372"},
740     {K_K9,		"\316\376"},
741 # endif
742 
743 # if defined(VMS) || defined(ALL_BUILTIN_TCAPS)
744 /*
745  * VT320 is working as an ANSI terminal compatible DEC terminal.
746  * (it covers VT1x0, VT2x0 and VT3x0 up to VT320 on VMS as well)
747  * Note: K_F1...K_F5 are for internal use, should not be defined.
748  * TODO:- rewrite ESC[ codes to CSI
749  *      - keyboard languages (CSI ? 26 n)
750  */
751     {(int)KS_NAME,	"vt320"},
752     {(int)KS_CE,	IF_EB("\033[K", ESC_STR "[K")},
753     {(int)KS_AL,	IF_EB("\033[L", ESC_STR "[L")},
754 #  ifdef TERMINFO
755     {(int)KS_CAL,	IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")},
756 #  else
757     {(int)KS_CAL,	IF_EB("\033[%dL", ESC_STR "[%dL")},
758 #  endif
759     {(int)KS_DL,	IF_EB("\033[M", ESC_STR "[M")},
760 #  ifdef TERMINFO
761     {(int)KS_CDL,	IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")},
762 #  else
763     {(int)KS_CDL,	IF_EB("\033[%dM", ESC_STR "[%dM")},
764 #  endif
765     {(int)KS_CL,	IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")},
766     {(int)KS_CD,	IF_EB("\033[J", ESC_STR "[J")},
767     {(int)KS_CCO,	"8"},			/* allow 8 colors */
768     {(int)KS_ME,	IF_EB("\033[0m", ESC_STR "[0m")},
769     {(int)KS_MR,	IF_EB("\033[7m", ESC_STR "[7m")},
770     {(int)KS_MD,	IF_EB("\033[1m", ESC_STR "[1m")},  /* bold mode */
771     {(int)KS_SE,	IF_EB("\033[22m", ESC_STR "[22m")},/* normal mode */
772     {(int)KS_UE,	IF_EB("\033[24m", ESC_STR "[24m")},/* exit underscore mode */
773     {(int)KS_US,	IF_EB("\033[4m", ESC_STR "[4m")},  /* underscore mode */
774     {(int)KS_CZH,	IF_EB("\033[34;43m", ESC_STR "[34;43m")},  /* italic mode: blue text on yellow */
775     {(int)KS_CZR,	IF_EB("\033[0m", ESC_STR "[0m")},	    /* italic mode end */
776     {(int)KS_CAB,	IF_EB("\033[4%dm", ESC_STR "[4%dm")},	    /* set background color (ANSI) */
777     {(int)KS_CAF,	IF_EB("\033[3%dm", ESC_STR "[3%dm")},	    /* set foreground color (ANSI) */
778     {(int)KS_CSB,	IF_EB("\033[102;%dm", ESC_STR "[102;%dm")},	/* set screen background color */
779     {(int)KS_CSF,	IF_EB("\033[101;%dm", ESC_STR "[101;%dm")},	/* set screen foreground color */
780     {(int)KS_MS,	"y"},
781     {(int)KS_UT,	"y"},
782     {(int)KS_XN,	"y"},
783     {(int)KS_LE,	"\b"},
784 #  ifdef TERMINFO
785     {(int)KS_CM,	IF_EB("\033[%i%p1%d;%p2%dH",
786 						  ESC_STR "[%i%p1%d;%p2%dH")},
787 #  else
788     {(int)KS_CM,	IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")},
789 #  endif
790 #  ifdef TERMINFO
791     {(int)KS_CRI,	IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")},
792 #  else
793     {(int)KS_CRI,	IF_EB("\033[%dC", ESC_STR "[%dC")},
794 #  endif
795     {K_UP,		IF_EB("\033[A", ESC_STR "[A")},
796     {K_DOWN,		IF_EB("\033[B", ESC_STR "[B")},
797     {K_RIGHT,		IF_EB("\033[C", ESC_STR "[C")},
798     {K_LEFT,		IF_EB("\033[D", ESC_STR "[D")},
799     {K_F1,		IF_EB("\033[11~", ESC_STR "[11~")},
800     {K_F2,		IF_EB("\033[12~", ESC_STR "[12~")},
801     {K_F3,		IF_EB("\033[13~", ESC_STR "[13~")},
802     {K_F4,		IF_EB("\033[14~", ESC_STR "[14~")},
803     {K_F5,		IF_EB("\033[15~", ESC_STR "[15~")},
804     {K_F6,		IF_EB("\033[17~", ESC_STR "[17~")},
805     {K_F7,		IF_EB("\033[18~", ESC_STR "[18~")},
806     {K_F8,		IF_EB("\033[19~", ESC_STR "[19~")},
807     {K_F9,		IF_EB("\033[20~", ESC_STR "[20~")},
808     {K_F10,		IF_EB("\033[21~", ESC_STR "[21~")},
809     {K_F11,		IF_EB("\033[23~", ESC_STR "[23~")},
810     {K_F12,		IF_EB("\033[24~", ESC_STR "[24~")},
811     {K_F13,		IF_EB("\033[25~", ESC_STR "[25~")},
812     {K_F14,		IF_EB("\033[26~", ESC_STR "[26~")},
813     {K_F15,		IF_EB("\033[28~", ESC_STR "[28~")},	/* Help */
814     {K_F16,		IF_EB("\033[29~", ESC_STR "[29~")},	/* Select */
815     {K_F17,		IF_EB("\033[31~", ESC_STR "[31~")},
816     {K_F18,		IF_EB("\033[32~", ESC_STR "[32~")},
817     {K_F19,		IF_EB("\033[33~", ESC_STR "[33~")},
818     {K_F20,		IF_EB("\033[34~", ESC_STR "[34~")},
819     {K_INS,		IF_EB("\033[2~", ESC_STR "[2~")},
820     {K_DEL,		IF_EB("\033[3~", ESC_STR "[3~")},
821     {K_HOME,		IF_EB("\033[1~", ESC_STR "[1~")},
822     {K_END,		IF_EB("\033[4~", ESC_STR "[4~")},
823     {K_PAGEUP,		IF_EB("\033[5~", ESC_STR "[5~")},
824     {K_PAGEDOWN,	IF_EB("\033[6~", ESC_STR "[6~")},
825     {K_KPLUS,		IF_EB("\033Ok", ESC_STR "Ok")},	/* keypad plus */
826     {K_KMINUS,		IF_EB("\033Om", ESC_STR "Om")},	/* keypad minus */
827     {K_KDIVIDE,		IF_EB("\033Oo", ESC_STR "Oo")},	/* keypad / */
828     {K_KMULTIPLY,	IF_EB("\033Oj", ESC_STR "Oj")},	/* keypad * */
829     {K_KENTER,		IF_EB("\033OM", ESC_STR "OM")},	/* keypad Enter */
830     {K_BS,		"\x7f"},	/* for some reason 0177 doesn't work */
831 # endif
832 
833 # if defined(ALL_BUILTIN_TCAPS) || defined(__MINT__)
834 /*
835  * Ordinary vt52
836  */
837     {(int)KS_NAME,	"vt52"},
838     {(int)KS_CE,	IF_EB("\033K", ESC_STR "K")},
839     {(int)KS_CD,	IF_EB("\033J", ESC_STR "J")},
840 #  ifdef TERMINFO
841     {(int)KS_CM,	IF_EB("\033Y%p1%' '%+%c%p2%' '%+%c",
842 			    ESC_STR "Y%p1%' '%+%c%p2%' '%+%c")},
843 #  else
844     {(int)KS_CM,	IF_EB("\033Y%+ %+ ", ESC_STR "Y%+ %+ ")},
845 #  endif
846     {(int)KS_LE,	"\b"},
847     {(int)KS_SR,	IF_EB("\033I", ESC_STR "I")},
848     {(int)KS_AL,	IF_EB("\033L", ESC_STR "L")},
849     {(int)KS_DL,	IF_EB("\033M", ESC_STR "M")},
850     {K_UP,		IF_EB("\033A", ESC_STR "A")},
851     {K_DOWN,		IF_EB("\033B", ESC_STR "B")},
852     {K_LEFT,		IF_EB("\033D", ESC_STR "D")},
853     {K_RIGHT,		IF_EB("\033C", ESC_STR "C")},
854     {K_F1,		IF_EB("\033P", ESC_STR "P")},
855     {K_F2,		IF_EB("\033Q", ESC_STR "Q")},
856     {K_F3,		IF_EB("\033R", ESC_STR "R")},
857 #  ifdef __MINT__
858     {(int)KS_CL,	IF_EB("\033E", ESC_STR "E")},
859     {(int)KS_VE,	IF_EB("\033e", ESC_STR "e")},
860     {(int)KS_VI,	IF_EB("\033f", ESC_STR "f")},
861     {(int)KS_SO,	IF_EB("\033p", ESC_STR "p")},
862     {(int)KS_SE,	IF_EB("\033q", ESC_STR "q")},
863     {K_S_UP,		IF_EB("\033a", ESC_STR "a")},
864     {K_S_DOWN,		IF_EB("\033b", ESC_STR "b")},
865     {K_S_LEFT,		IF_EB("\033d", ESC_STR "d")},
866     {K_S_RIGHT,		IF_EB("\033c", ESC_STR "c")},
867     {K_F4,		IF_EB("\033S", ESC_STR "S")},
868     {K_F5,		IF_EB("\033T", ESC_STR "T")},
869     {K_F6,		IF_EB("\033U", ESC_STR "U")},
870     {K_F7,		IF_EB("\033V", ESC_STR "V")},
871     {K_F8,		IF_EB("\033W", ESC_STR "W")},
872     {K_F9,		IF_EB("\033X", ESC_STR "X")},
873     {K_F10,		IF_EB("\033Y", ESC_STR "Y")},
874     {K_S_F1,		IF_EB("\033p", ESC_STR "p")},
875     {K_S_F2,		IF_EB("\033q", ESC_STR "q")},
876     {K_S_F3,		IF_EB("\033r", ESC_STR "r")},
877     {K_S_F4,		IF_EB("\033s", ESC_STR "s")},
878     {K_S_F5,		IF_EB("\033t", ESC_STR "t")},
879     {K_S_F6,		IF_EB("\033u", ESC_STR "u")},
880     {K_S_F7,		IF_EB("\033v", ESC_STR "v")},
881     {K_S_F8,		IF_EB("\033w", ESC_STR "w")},
882     {K_S_F9,		IF_EB("\033x", ESC_STR "x")},
883     {K_S_F10,		IF_EB("\033y", ESC_STR "y")},
884     {K_INS,		IF_EB("\033I", ESC_STR "I")},
885     {K_HOME,		IF_EB("\033E", ESC_STR "E")},
886     {K_PAGEDOWN,	IF_EB("\033b", ESC_STR "b")},
887     {K_PAGEUP,		IF_EB("\033a", ESC_STR "a")},
888 #  else
889     {(int)KS_CL,	IF_EB("\033H\033J", ESC_STR "H" ESC_STR_nc "J")},
890     {(int)KS_MS,	"y"},
891 #  endif
892 # endif
893 
894 # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS) || defined(SOME_BUILTIN_TCAPS) || defined(__EMX__)
895     {(int)KS_NAME,	"xterm"},
896     {(int)KS_CE,	IF_EB("\033[K", ESC_STR "[K")},
897     {(int)KS_AL,	IF_EB("\033[L", ESC_STR "[L")},
898 #  ifdef TERMINFO
899     {(int)KS_CAL,	IF_EB("\033[%p1%dL", ESC_STR "[%p1%dL")},
900 #  else
901     {(int)KS_CAL,	IF_EB("\033[%dL", ESC_STR "[%dL")},
902 #  endif
903     {(int)KS_DL,	IF_EB("\033[M", ESC_STR "[M")},
904 #  ifdef TERMINFO
905     {(int)KS_CDL,	IF_EB("\033[%p1%dM", ESC_STR "[%p1%dM")},
906 #  else
907     {(int)KS_CDL,	IF_EB("\033[%dM", ESC_STR "[%dM")},
908 #  endif
909 #  ifdef TERMINFO
910     {(int)KS_CS,	IF_EB("\033[%i%p1%d;%p2%dr",
911 						  ESC_STR "[%i%p1%d;%p2%dr")},
912 #  else
913     {(int)KS_CS,	IF_EB("\033[%i%d;%dr", ESC_STR "[%i%d;%dr")},
914 #  endif
915     {(int)KS_CL,	IF_EB("\033[H\033[2J", ESC_STR "[H" ESC_STR_nc "[2J")},
916     {(int)KS_CD,	IF_EB("\033[J", ESC_STR "[J")},
917     {(int)KS_ME,	IF_EB("\033[m", ESC_STR "[m")},
918     {(int)KS_MR,	IF_EB("\033[7m", ESC_STR "[7m")},
919     {(int)KS_MD,	IF_EB("\033[1m", ESC_STR "[1m")},
920     {(int)KS_UE,	IF_EB("\033[m", ESC_STR "[m")},
921     {(int)KS_US,	IF_EB("\033[4m", ESC_STR "[4m")},
922     {(int)KS_MS,	"y"},
923     {(int)KS_UT,	"y"},
924     {(int)KS_LE,	"\b"},
925 #  ifdef TERMINFO
926     {(int)KS_CM,	IF_EB("\033[%i%p1%d;%p2%dH",
927 						  ESC_STR "[%i%p1%d;%p2%dH")},
928 #  else
929     {(int)KS_CM,	IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")},
930 #  endif
931     {(int)KS_SR,	IF_EB("\033M", ESC_STR "M")},
932 #  ifdef TERMINFO
933     {(int)KS_CRI,	IF_EB("\033[%p1%dC", ESC_STR "[%p1%dC")},
934 #  else
935     {(int)KS_CRI,	IF_EB("\033[%dC", ESC_STR "[%dC")},
936 #  endif
937     {(int)KS_KS,	IF_EB("\033[?1h\033=", ESC_STR "[?1h" ESC_STR_nc "=")},
938     {(int)KS_KE,	IF_EB("\033[?1l\033>", ESC_STR "[?1l" ESC_STR_nc ">")},
939 #  ifdef FEAT_XTERM_SAVE
940     {(int)KS_TI,	IF_EB("\0337\033[?47h", ESC_STR "7" ESC_STR_nc "[?47h")},
941     {(int)KS_TE,	IF_EB("\033[2J\033[?47l\0338",
942 				  ESC_STR "[2J" ESC_STR_nc "[?47l" ESC_STR_nc "8")},
943 #  endif
944     {(int)KS_CIS,	IF_EB("\033]1;", ESC_STR "]1;")},
945     {(int)KS_CIE,	"\007"},
946     {(int)KS_TS,	IF_EB("\033]2;", ESC_STR "]2;")},
947     {(int)KS_FS,	"\007"},
948 #  ifdef TERMINFO
949     {(int)KS_CWS,	IF_EB("\033[8;%p1%d;%p2%dt",
950 						  ESC_STR "[8;%p1%d;%p2%dt")},
951     {(int)KS_CWP,	IF_EB("\033[3;%p1%d;%p2%dt",
952 						  ESC_STR "[3;%p1%d;%p2%dt")},
953 #  else
954     {(int)KS_CWS,	IF_EB("\033[8;%d;%dt", ESC_STR "[8;%d;%dt")},
955     {(int)KS_CWP,	IF_EB("\033[3;%d;%dt", ESC_STR "[3;%d;%dt")},
956 #  endif
957     {(int)KS_CRV,	IF_EB("\033[>c", ESC_STR "[>c")},
958     {(int)KS_RBG,	IF_EB("\033]11;?\007", ESC_STR "]11;?\007")},
959     {(int)KS_U7,	IF_EB("\033[6n", ESC_STR "[6n")},
960 
961     {K_UP,		IF_EB("\033O*A", ESC_STR "O*A")},
962     {K_DOWN,		IF_EB("\033O*B", ESC_STR "O*B")},
963     {K_RIGHT,		IF_EB("\033O*C", ESC_STR "O*C")},
964     {K_LEFT,		IF_EB("\033O*D", ESC_STR "O*D")},
965     /* An extra set of cursor keys for vt100 mode */
966     {K_XUP,		IF_EB("\033[1;*A", ESC_STR "[1;*A")},
967     {K_XDOWN,		IF_EB("\033[1;*B", ESC_STR "[1;*B")},
968     {K_XRIGHT,		IF_EB("\033[1;*C", ESC_STR "[1;*C")},
969     {K_XLEFT,		IF_EB("\033[1;*D", ESC_STR "[1;*D")},
970     /* An extra set of function keys for vt100 mode */
971     {K_XF1,		IF_EB("\033O*P", ESC_STR "O*P")},
972     {K_XF2,		IF_EB("\033O*Q", ESC_STR "O*Q")},
973     {K_XF3,		IF_EB("\033O*R", ESC_STR "O*R")},
974     {K_XF4,		IF_EB("\033O*S", ESC_STR "O*S")},
975     {K_F1,		IF_EB("\033[11;*~", ESC_STR "[11;*~")},
976     {K_F2,		IF_EB("\033[12;*~", ESC_STR "[12;*~")},
977     {K_F3,		IF_EB("\033[13;*~", ESC_STR "[13;*~")},
978     {K_F4,		IF_EB("\033[14;*~", ESC_STR "[14;*~")},
979     {K_F5,		IF_EB("\033[15;*~", ESC_STR "[15;*~")},
980     {K_F6,		IF_EB("\033[17;*~", ESC_STR "[17;*~")},
981     {K_F7,		IF_EB("\033[18;*~", ESC_STR "[18;*~")},
982     {K_F8,		IF_EB("\033[19;*~", ESC_STR "[19;*~")},
983     {K_F9,		IF_EB("\033[20;*~", ESC_STR "[20;*~")},
984     {K_F10,		IF_EB("\033[21;*~", ESC_STR "[21;*~")},
985     {K_F11,		IF_EB("\033[23;*~", ESC_STR "[23;*~")},
986     {K_F12,		IF_EB("\033[24;*~", ESC_STR "[24;*~")},
987     {K_S_TAB,		IF_EB("\033[Z", ESC_STR "[Z")},
988     {K_HELP,		IF_EB("\033[28;*~", ESC_STR "[28;*~")},
989     {K_UNDO,		IF_EB("\033[26;*~", ESC_STR "[26;*~")},
990     {K_INS,		IF_EB("\033[2;*~", ESC_STR "[2;*~")},
991     {K_HOME,		IF_EB("\033[1;*H", ESC_STR "[1;*H")},
992     /* {K_S_HOME,		IF_EB("\033O2H", ESC_STR "O2H")}, */
993     /* {K_C_HOME,		IF_EB("\033O5H", ESC_STR "O5H")}, */
994     {K_KHOME,		IF_EB("\033[1;*~", ESC_STR "[1;*~")},
995     {K_XHOME,		IF_EB("\033O*H", ESC_STR "O*H")},	/* other Home */
996     {K_ZHOME,		IF_EB("\033[7;*~", ESC_STR "[7;*~")},	/* other Home */
997     {K_END,		IF_EB("\033[1;*F", ESC_STR "[1;*F")},
998     /* {K_S_END,		IF_EB("\033O2F", ESC_STR "O2F")}, */
999     /* {K_C_END,		IF_EB("\033O5F", ESC_STR "O5F")}, */
1000     {K_KEND,		IF_EB("\033[4;*~", ESC_STR "[4;*~")},
1001     {K_XEND,		IF_EB("\033O*F", ESC_STR "O*F")},	/* other End */
1002     {K_ZEND,		IF_EB("\033[8;*~", ESC_STR "[8;*~")},
1003     {K_PAGEUP,		IF_EB("\033[5;*~", ESC_STR "[5;*~")},
1004     {K_PAGEDOWN,	IF_EB("\033[6;*~", ESC_STR "[6;*~")},
1005     {K_KPLUS,		IF_EB("\033O*k", ESC_STR "O*k")},	/* keypad plus */
1006     {K_KMINUS,		IF_EB("\033O*m", ESC_STR "O*m")},	/* keypad minus */
1007     {K_KDIVIDE,		IF_EB("\033O*o", ESC_STR "O*o")},	/* keypad / */
1008     {K_KMULTIPLY,	IF_EB("\033O*j", ESC_STR "O*j")},	/* keypad * */
1009     {K_KENTER,		IF_EB("\033O*M", ESC_STR "O*M")},	/* keypad Enter */
1010     {K_KPOINT,		IF_EB("\033O*n", ESC_STR "O*n")},	/* keypad . */
1011     {K_KDEL,		IF_EB("\033[3;*~", ESC_STR "[3;*~")},	/* keypad Del */
1012 
1013     {BT_EXTRA_KEYS,   ""},
1014     {TERMCAP2KEY('k', '0'), IF_EB("\033[10;*~", ESC_STR "[10;*~")}, /* F0 */
1015     {TERMCAP2KEY('F', '3'), IF_EB("\033[25;*~", ESC_STR "[25;*~")}, /* F13 */
1016     /* F14 and F15 are missing, because they send the same codes as the undo
1017      * and help key, although they don't work on all keyboards. */
1018     {TERMCAP2KEY('F', '6'), IF_EB("\033[29;*~", ESC_STR "[29;*~")}, /* F16 */
1019     {TERMCAP2KEY('F', '7'), IF_EB("\033[31;*~", ESC_STR "[31;*~")}, /* F17 */
1020     {TERMCAP2KEY('F', '8'), IF_EB("\033[32;*~", ESC_STR "[32;*~")}, /* F18 */
1021     {TERMCAP2KEY('F', '9'), IF_EB("\033[33;*~", ESC_STR "[33;*~")}, /* F19 */
1022     {TERMCAP2KEY('F', 'A'), IF_EB("\033[34;*~", ESC_STR "[34;*~")}, /* F20 */
1023 
1024     {TERMCAP2KEY('F', 'B'), IF_EB("\033[42;*~", ESC_STR "[42;*~")}, /* F21 */
1025     {TERMCAP2KEY('F', 'C'), IF_EB("\033[43;*~", ESC_STR "[43;*~")}, /* F22 */
1026     {TERMCAP2KEY('F', 'D'), IF_EB("\033[44;*~", ESC_STR "[44;*~")}, /* F23 */
1027     {TERMCAP2KEY('F', 'E'), IF_EB("\033[45;*~", ESC_STR "[45;*~")}, /* F24 */
1028     {TERMCAP2KEY('F', 'F'), IF_EB("\033[46;*~", ESC_STR "[46;*~")}, /* F25 */
1029     {TERMCAP2KEY('F', 'G'), IF_EB("\033[47;*~", ESC_STR "[47;*~")}, /* F26 */
1030     {TERMCAP2KEY('F', 'H'), IF_EB("\033[48;*~", ESC_STR "[48;*~")}, /* F27 */
1031     {TERMCAP2KEY('F', 'I'), IF_EB("\033[49;*~", ESC_STR "[49;*~")}, /* F28 */
1032     {TERMCAP2KEY('F', 'J'), IF_EB("\033[50;*~", ESC_STR "[50;*~")}, /* F29 */
1033     {TERMCAP2KEY('F', 'K'), IF_EB("\033[51;*~", ESC_STR "[51;*~")}, /* F30 */
1034 
1035     {TERMCAP2KEY('F', 'L'), IF_EB("\033[52;*~", ESC_STR "[52;*~")}, /* F31 */
1036     {TERMCAP2KEY('F', 'M'), IF_EB("\033[53;*~", ESC_STR "[53;*~")}, /* F32 */
1037     {TERMCAP2KEY('F', 'N'), IF_EB("\033[54;*~", ESC_STR "[54;*~")}, /* F33 */
1038     {TERMCAP2KEY('F', 'O'), IF_EB("\033[55;*~", ESC_STR "[55;*~")}, /* F34 */
1039     {TERMCAP2KEY('F', 'P'), IF_EB("\033[56;*~", ESC_STR "[56;*~")}, /* F35 */
1040     {TERMCAP2KEY('F', 'Q'), IF_EB("\033[57;*~", ESC_STR "[57;*~")}, /* F36 */
1041     {TERMCAP2KEY('F', 'R'), IF_EB("\033[58;*~", ESC_STR "[58;*~")}, /* F37 */
1042 # endif
1043 
1044 # if defined(UNIX) || defined(ALL_BUILTIN_TCAPS)
1045 /*
1046  * iris-ansi for Silicon Graphics machines.
1047  */
1048     {(int)KS_NAME,	"iris-ansi"},
1049     {(int)KS_CE,	"\033[K"},
1050     {(int)KS_CD,	"\033[J"},
1051     {(int)KS_AL,	"\033[L"},
1052 #  ifdef TERMINFO
1053     {(int)KS_CAL,	"\033[%p1%dL"},
1054 #  else
1055     {(int)KS_CAL,	"\033[%dL"},
1056 #  endif
1057     {(int)KS_DL,	"\033[M"},
1058 #  ifdef TERMINFO
1059     {(int)KS_CDL,	"\033[%p1%dM"},
1060 #  else
1061     {(int)KS_CDL,	"\033[%dM"},
1062 #  endif
1063 #if 0	/* The scroll region is not working as Vim expects. */
1064 #  ifdef TERMINFO
1065     {(int)KS_CS,	"\033[%i%p1%d;%p2%dr"},
1066 #  else
1067     {(int)KS_CS,	"\033[%i%d;%dr"},
1068 #  endif
1069 #endif
1070     {(int)KS_CL,	"\033[H\033[2J"},
1071     {(int)KS_VE,	"\033[9/y\033[12/y"},	/* These aren't documented */
1072     {(int)KS_VS,	"\033[10/y\033[=1h\033[=2l"}, /* These aren't documented */
1073     {(int)KS_TI,	"\033[=6h"},
1074     {(int)KS_TE,	"\033[=6l"},
1075     {(int)KS_SE,	"\033[21;27m"},
1076     {(int)KS_SO,	"\033[1;7m"},
1077     {(int)KS_ME,	"\033[m"},
1078     {(int)KS_MR,	"\033[7m"},
1079     {(int)KS_MD,	"\033[1m"},
1080     {(int)KS_CCO,	"8"},			/* allow 8 colors */
1081     {(int)KS_CZH,	"\033[3m"},		/* italic mode on */
1082     {(int)KS_CZR,	"\033[23m"},		/* italic mode off */
1083     {(int)KS_US,	"\033[4m"},		/* underline on */
1084     {(int)KS_UE,	"\033[24m"},		/* underline off */
1085 #  ifdef TERMINFO
1086     {(int)KS_CAB,	"\033[4%p1%dm"},    /* set background color (ANSI) */
1087     {(int)KS_CAF,	"\033[3%p1%dm"},    /* set foreground color (ANSI) */
1088     {(int)KS_CSB,	"\033[102;%p1%dm"}, /* set screen background color */
1089     {(int)KS_CSF,	"\033[101;%p1%dm"}, /* set screen foreground color */
1090 #  else
1091     {(int)KS_CAB,	"\033[4%dm"},	    /* set background color (ANSI) */
1092     {(int)KS_CAF,	"\033[3%dm"},	    /* set foreground color (ANSI) */
1093     {(int)KS_CSB,	"\033[102;%dm"},    /* set screen background color */
1094     {(int)KS_CSF,	"\033[101;%dm"},    /* set screen foreground color */
1095 #  endif
1096     {(int)KS_MS,	"y"},		/* guessed */
1097     {(int)KS_UT,	"y"},		/* guessed */
1098     {(int)KS_LE,	"\b"},
1099 #  ifdef TERMINFO
1100     {(int)KS_CM,	"\033[%i%p1%d;%p2%dH"},
1101 #  else
1102     {(int)KS_CM,	"\033[%i%d;%dH"},
1103 #  endif
1104     {(int)KS_SR,	"\033M"},
1105 #  ifdef TERMINFO
1106     {(int)KS_CRI,	"\033[%p1%dC"},
1107 #  else
1108     {(int)KS_CRI,	"\033[%dC"},
1109 #  endif
1110     {(int)KS_CIS,	"\033P3.y"},
1111     {(int)KS_CIE,	"\234"},    /* ST "String Terminator" */
1112     {(int)KS_TS,	"\033P1.y"},
1113     {(int)KS_FS,	"\234"},    /* ST "String Terminator" */
1114 #  ifdef TERMINFO
1115     {(int)KS_CWS,	"\033[203;%p1%d;%p2%d/y"},
1116     {(int)KS_CWP,	"\033[205;%p1%d;%p2%d/y"},
1117 #  else
1118     {(int)KS_CWS,	"\033[203;%d;%d/y"},
1119     {(int)KS_CWP,	"\033[205;%d;%d/y"},
1120 #  endif
1121     {K_UP,		"\033[A"},
1122     {K_DOWN,		"\033[B"},
1123     {K_LEFT,		"\033[D"},
1124     {K_RIGHT,		"\033[C"},
1125     {K_S_UP,		"\033[161q"},
1126     {K_S_DOWN,		"\033[164q"},
1127     {K_S_LEFT,		"\033[158q"},
1128     {K_S_RIGHT,		"\033[167q"},
1129     {K_F1,		"\033[001q"},
1130     {K_F2,		"\033[002q"},
1131     {K_F3,		"\033[003q"},
1132     {K_F4,		"\033[004q"},
1133     {K_F5,		"\033[005q"},
1134     {K_F6,		"\033[006q"},
1135     {K_F7,		"\033[007q"},
1136     {K_F8,		"\033[008q"},
1137     {K_F9,		"\033[009q"},
1138     {K_F10,		"\033[010q"},
1139     {K_F11,		"\033[011q"},
1140     {K_F12,		"\033[012q"},
1141     {K_S_F1,		"\033[013q"},
1142     {K_S_F2,		"\033[014q"},
1143     {K_S_F3,		"\033[015q"},
1144     {K_S_F4,		"\033[016q"},
1145     {K_S_F5,		"\033[017q"},
1146     {K_S_F6,		"\033[018q"},
1147     {K_S_F7,		"\033[019q"},
1148     {K_S_F8,		"\033[020q"},
1149     {K_S_F9,		"\033[021q"},
1150     {K_S_F10,		"\033[022q"},
1151     {K_S_F11,		"\033[023q"},
1152     {K_S_F12,		"\033[024q"},
1153     {K_INS,		"\033[139q"},
1154     {K_HOME,		"\033[H"},
1155     {K_END,		"\033[146q"},
1156     {K_PAGEUP,		"\033[150q"},
1157     {K_PAGEDOWN,	"\033[154q"},
1158 # endif
1159 
1160 # if defined(DEBUG) || defined(ALL_BUILTIN_TCAPS)
1161 /*
1162  * for debugging
1163  */
1164     {(int)KS_NAME,	"debug"},
1165     {(int)KS_CE,	"[CE]"},
1166     {(int)KS_CD,	"[CD]"},
1167     {(int)KS_AL,	"[AL]"},
1168 #  ifdef TERMINFO
1169     {(int)KS_CAL,	"[CAL%p1%d]"},
1170 #  else
1171     {(int)KS_CAL,	"[CAL%d]"},
1172 #  endif
1173     {(int)KS_DL,	"[DL]"},
1174 #  ifdef TERMINFO
1175     {(int)KS_CDL,	"[CDL%p1%d]"},
1176 #  else
1177     {(int)KS_CDL,	"[CDL%d]"},
1178 #  endif
1179 #  ifdef TERMINFO
1180     {(int)KS_CS,	"[%p1%dCS%p2%d]"},
1181 #  else
1182     {(int)KS_CS,	"[%dCS%d]"},
1183 #  endif
1184 #  ifdef FEAT_VERTSPLIT
1185 #   ifdef TERMINFO
1186     {(int)KS_CSV,	"[%p1%dCSV%p2%d]"},
1187 #   else
1188     {(int)KS_CSV,	"[%dCSV%d]"},
1189 #   endif
1190 #  endif
1191 #  ifdef TERMINFO
1192     {(int)KS_CAB,	"[CAB%p1%d]"},
1193     {(int)KS_CAF,	"[CAF%p1%d]"},
1194     {(int)KS_CSB,	"[CSB%p1%d]"},
1195     {(int)KS_CSF,	"[CSF%p1%d]"},
1196 #  else
1197     {(int)KS_CAB,	"[CAB%d]"},
1198     {(int)KS_CAF,	"[CAF%d]"},
1199     {(int)KS_CSB,	"[CSB%d]"},
1200     {(int)KS_CSF,	"[CSF%d]"},
1201 #  endif
1202     {(int)KS_OP,	"[OP]"},
1203     {(int)KS_LE,	"[LE]"},
1204     {(int)KS_CL,	"[CL]"},
1205     {(int)KS_VI,	"[VI]"},
1206     {(int)KS_VE,	"[VE]"},
1207     {(int)KS_VS,	"[VS]"},
1208     {(int)KS_ME,	"[ME]"},
1209     {(int)KS_MR,	"[MR]"},
1210     {(int)KS_MB,	"[MB]"},
1211     {(int)KS_MD,	"[MD]"},
1212     {(int)KS_SE,	"[SE]"},
1213     {(int)KS_SO,	"[SO]"},
1214     {(int)KS_UE,	"[UE]"},
1215     {(int)KS_US,	"[US]"},
1216     {(int)KS_UCE,	"[UCE]"},
1217     {(int)KS_UCS,	"[UCS]"},
1218     {(int)KS_MS,	"[MS]"},
1219     {(int)KS_UT,	"[UT]"},
1220     {(int)KS_XN,	"[XN]"},
1221 #  ifdef TERMINFO
1222     {(int)KS_CM,	"[%p1%dCM%p2%d]"},
1223 #  else
1224     {(int)KS_CM,	"[%dCM%d]"},
1225 #  endif
1226     {(int)KS_SR,	"[SR]"},
1227 #  ifdef TERMINFO
1228     {(int)KS_CRI,	"[CRI%p1%d]"},
1229 #  else
1230     {(int)KS_CRI,	"[CRI%d]"},
1231 #  endif
1232     {(int)KS_VB,	"[VB]"},
1233     {(int)KS_KS,	"[KS]"},
1234     {(int)KS_KE,	"[KE]"},
1235     {(int)KS_TI,	"[TI]"},
1236     {(int)KS_TE,	"[TE]"},
1237     {(int)KS_CIS,	"[CIS]"},
1238     {(int)KS_CIE,	"[CIE]"},
1239     {(int)KS_TS,	"[TS]"},
1240     {(int)KS_FS,	"[FS]"},
1241 #  ifdef TERMINFO
1242     {(int)KS_CWS,	"[%p1%dCWS%p2%d]"},
1243     {(int)KS_CWP,	"[%p1%dCWP%p2%d]"},
1244 #  else
1245     {(int)KS_CWS,	"[%dCWS%d]"},
1246     {(int)KS_CWP,	"[%dCWP%d]"},
1247 #  endif
1248     {(int)KS_CRV,	"[CRV]"},
1249     {(int)KS_U7,	"[U7]"},
1250     {(int)KS_RBG,	"[RBG]"},
1251     {K_UP,		"[KU]"},
1252     {K_DOWN,		"[KD]"},
1253     {K_LEFT,		"[KL]"},
1254     {K_RIGHT,		"[KR]"},
1255     {K_XUP,		"[xKU]"},
1256     {K_XDOWN,		"[xKD]"},
1257     {K_XLEFT,		"[xKL]"},
1258     {K_XRIGHT,		"[xKR]"},
1259     {K_S_UP,		"[S-KU]"},
1260     {K_S_DOWN,		"[S-KD]"},
1261     {K_S_LEFT,		"[S-KL]"},
1262     {K_C_LEFT,		"[C-KL]"},
1263     {K_S_RIGHT,		"[S-KR]"},
1264     {K_C_RIGHT,		"[C-KR]"},
1265     {K_F1,		"[F1]"},
1266     {K_XF1,		"[xF1]"},
1267     {K_F2,		"[F2]"},
1268     {K_XF2,		"[xF2]"},
1269     {K_F3,		"[F3]"},
1270     {K_XF3,		"[xF3]"},
1271     {K_F4,		"[F4]"},
1272     {K_XF4,		"[xF4]"},
1273     {K_F5,		"[F5]"},
1274     {K_F6,		"[F6]"},
1275     {K_F7,		"[F7]"},
1276     {K_F8,		"[F8]"},
1277     {K_F9,		"[F9]"},
1278     {K_F10,		"[F10]"},
1279     {K_F11,		"[F11]"},
1280     {K_F12,		"[F12]"},
1281     {K_S_F1,		"[S-F1]"},
1282     {K_S_XF1,		"[S-xF1]"},
1283     {K_S_F2,		"[S-F2]"},
1284     {K_S_XF2,		"[S-xF2]"},
1285     {K_S_F3,		"[S-F3]"},
1286     {K_S_XF3,		"[S-xF3]"},
1287     {K_S_F4,		"[S-F4]"},
1288     {K_S_XF4,		"[S-xF4]"},
1289     {K_S_F5,		"[S-F5]"},
1290     {K_S_F6,		"[S-F6]"},
1291     {K_S_F7,		"[S-F7]"},
1292     {K_S_F8,		"[S-F8]"},
1293     {K_S_F9,		"[S-F9]"},
1294     {K_S_F10,		"[S-F10]"},
1295     {K_S_F11,		"[S-F11]"},
1296     {K_S_F12,		"[S-F12]"},
1297     {K_HELP,		"[HELP]"},
1298     {K_UNDO,		"[UNDO]"},
1299     {K_BS,		"[BS]"},
1300     {K_INS,		"[INS]"},
1301     {K_KINS,		"[KINS]"},
1302     {K_DEL,		"[DEL]"},
1303     {K_KDEL,		"[KDEL]"},
1304     {K_HOME,		"[HOME]"},
1305     {K_S_HOME,		"[C-HOME]"},
1306     {K_C_HOME,		"[C-HOME]"},
1307     {K_KHOME,		"[KHOME]"},
1308     {K_XHOME,		"[XHOME]"},
1309     {K_ZHOME,		"[ZHOME]"},
1310     {K_END,		"[END]"},
1311     {K_S_END,		"[C-END]"},
1312     {K_C_END,		"[C-END]"},
1313     {K_KEND,		"[KEND]"},
1314     {K_XEND,		"[XEND]"},
1315     {K_ZEND,		"[ZEND]"},
1316     {K_PAGEUP,		"[PAGEUP]"},
1317     {K_PAGEDOWN,	"[PAGEDOWN]"},
1318     {K_KPAGEUP,		"[KPAGEUP]"},
1319     {K_KPAGEDOWN,	"[KPAGEDOWN]"},
1320     {K_MOUSE,		"[MOUSE]"},
1321     {K_KPLUS,		"[KPLUS]"},
1322     {K_KMINUS,		"[KMINUS]"},
1323     {K_KDIVIDE,		"[KDIVIDE]"},
1324     {K_KMULTIPLY,	"[KMULTIPLY]"},
1325     {K_KENTER,		"[KENTER]"},
1326     {K_KPOINT,		"[KPOINT]"},
1327     {K_K0,		"[K0]"},
1328     {K_K1,		"[K1]"},
1329     {K_K2,		"[K2]"},
1330     {K_K3,		"[K3]"},
1331     {K_K4,		"[K4]"},
1332     {K_K5,		"[K5]"},
1333     {K_K6,		"[K6]"},
1334     {K_K7,		"[K7]"},
1335     {K_K8,		"[K8]"},
1336     {K_K9,		"[K9]"},
1337 # endif
1338 
1339 #endif /* NO_BUILTIN_TCAPS */
1340 
1341 /*
1342  * The most minimal terminal: only clear screen and cursor positioning
1343  * Always included.
1344  */
1345     {(int)KS_NAME,	"dumb"},
1346     {(int)KS_CL,	"\014"},
1347 #ifdef TERMINFO
1348     {(int)KS_CM,	IF_EB("\033[%i%p1%d;%p2%dH",
1349 						  ESC_STR "[%i%p1%d;%p2%dH")},
1350 #else
1351     {(int)KS_CM,	IF_EB("\033[%i%d;%dH", ESC_STR "[%i%d;%dH")},
1352 #endif
1353 
1354 /*
1355  * end marker
1356  */
1357     {(int)KS_NAME,	NULL}
1358 
1359 };	/* end of builtin_termcaps */
1360 
1361 /*
1362  * DEFAULT_TERM is used, when no terminal is specified with -T option or $TERM.
1363  */
1364 #ifdef AMIGA
1365 # define DEFAULT_TERM	(char_u *)"amiga"
1366 #endif
1367 
1368 #ifdef MSWIN
1369 # define DEFAULT_TERM	(char_u *)"win32"
1370 #endif
1371 
1372 #ifdef MSDOS
1373 # define DEFAULT_TERM	(char_u *)"pcterm"
1374 #endif
1375 
1376 #if defined(UNIX) && !defined(__MINT__)
1377 # define DEFAULT_TERM	(char_u *)"ansi"
1378 #endif
1379 
1380 #ifdef __MINT__
1381 # define DEFAULT_TERM	(char_u *)"vt52"
1382 #endif
1383 
1384 #ifdef __EMX__
1385 # define DEFAULT_TERM	(char_u *)"os2ansi"
1386 #endif
1387 
1388 #ifdef VMS
1389 # define DEFAULT_TERM	(char_u *)"vt320"
1390 #endif
1391 
1392 #ifdef __BEOS__
1393 # undef DEFAULT_TERM
1394 # define DEFAULT_TERM	(char_u *)"beos-ansi"
1395 #endif
1396 
1397 #ifndef DEFAULT_TERM
1398 # define DEFAULT_TERM	(char_u *)"dumb"
1399 #endif
1400 
1401 /*
1402  * Term_strings contains currently used terminal output strings.
1403  * It is initialized with the default values by parse_builtin_tcap().
1404  * The values can be changed by setting the option with the same name.
1405  */
1406 char_u *(term_strings[(int)KS_LAST + 1]);
1407 
1408 static int	need_gather = FALSE;	    /* need to fill termleader[] */
1409 static char_u	termleader[256 + 1];	    /* for check_termcode() */
1410 #ifdef FEAT_TERMRESPONSE
1411 static int	check_for_codes = FALSE;    /* check for key code response */
1412 #endif
1413 
1414     static struct builtin_term *
1415 find_builtin_term(term)
1416     char_u	*term;
1417 {
1418     struct builtin_term *p;
1419 
1420     p = builtin_termcaps;
1421     while (p->bt_string != NULL)
1422     {
1423 	if (p->bt_entry == (int)KS_NAME)
1424 	{
1425 #ifdef UNIX
1426 	    if (STRCMP(p->bt_string, "iris-ansi") == 0 && vim_is_iris(term))
1427 		return p;
1428 	    else if (STRCMP(p->bt_string, "xterm") == 0 && vim_is_xterm(term))
1429 		return p;
1430 	    else
1431 #endif
1432 #ifdef VMS
1433 		if (STRCMP(p->bt_string, "vt320") == 0 && vim_is_vt300(term))
1434 		    return p;
1435 		else
1436 #endif
1437 		  if (STRCMP(term, p->bt_string) == 0)
1438 		    return p;
1439 	}
1440 	++p;
1441     }
1442     return p;
1443 }
1444 
1445 /*
1446  * Parsing of the builtin termcap entries.
1447  * Caller should check if 'name' is a valid builtin term.
1448  * The terminal's name is not set, as this is already done in termcapinit().
1449  */
1450     static void
1451 parse_builtin_tcap(term)
1452     char_u  *term;
1453 {
1454     struct builtin_term	    *p;
1455     char_u		    name[2];
1456     int			    term_8bit;
1457 
1458     p = find_builtin_term(term);
1459     term_8bit = term_is_8bit(term);
1460 
1461     /* Do not parse if builtin term not found */
1462     if (p->bt_string == NULL)
1463 	return;
1464 
1465     for (++p; p->bt_entry != (int)KS_NAME && p->bt_entry != BT_EXTRA_KEYS; ++p)
1466     {
1467 	if ((int)p->bt_entry >= 0)	/* KS_xx entry */
1468 	{
1469 	    /* Only set the value if it wasn't set yet. */
1470 	    if (term_strings[p->bt_entry] == NULL
1471 				 || term_strings[p->bt_entry] == empty_option)
1472 	    {
1473 		/* 8bit terminal: use CSI instead of <Esc>[ */
1474 		if (term_8bit && term_7to8bit((char_u *)p->bt_string) != 0)
1475 		{
1476 		    char_u  *s, *t;
1477 
1478 		    s = vim_strsave((char_u *)p->bt_string);
1479 		    if (s != NULL)
1480 		    {
1481 			for (t = s; *t; ++t)
1482 			    if (term_7to8bit(t))
1483 			    {
1484 				*t = term_7to8bit(t);
1485 				STRCPY(t + 1, t + 2);
1486 			    }
1487 			term_strings[p->bt_entry] = s;
1488 			set_term_option_alloced(&term_strings[p->bt_entry]);
1489 		    }
1490 		}
1491 		else
1492 		    term_strings[p->bt_entry] = (char_u *)p->bt_string;
1493 	    }
1494 	}
1495 	else
1496 	{
1497 	    name[0] = KEY2TERMCAP0((int)p->bt_entry);
1498 	    name[1] = KEY2TERMCAP1((int)p->bt_entry);
1499 	    if (find_termcode(name) == NULL)
1500 		add_termcode(name, (char_u *)p->bt_string, term_8bit);
1501 	}
1502     }
1503 }
1504 #if defined(HAVE_TGETENT) || defined(FEAT_TERMRESPONSE)
1505 static void set_color_count __ARGS((int nr));
1506 
1507 /*
1508  * Set number of colors.
1509  * Store it as a number in t_colors.
1510  * Store it as a string in T_CCO (using nr_colors[]).
1511  */
1512     static void
1513 set_color_count(nr)
1514     int		nr;
1515 {
1516     char_u	nr_colors[20];		/* string for number of colors */
1517 
1518     t_colors = nr;
1519     if (t_colors > 1)
1520 	sprintf((char *)nr_colors, "%d", t_colors);
1521     else
1522 	*nr_colors = NUL;
1523     set_string_option_direct((char_u *)"t_Co", -1, nr_colors, OPT_FREE, 0);
1524 }
1525 #endif
1526 
1527 #ifdef HAVE_TGETENT
1528 static char *(key_names[]) =
1529 {
1530 #ifdef FEAT_TERMRESPONSE
1531     /* Do this one first, it may cause a screen redraw. */
1532     "Co",
1533 #endif
1534     "ku", "kd", "kr", "kl",
1535     "#2", "#4", "%i", "*7",
1536     "k1", "k2", "k3", "k4", "k5", "k6",
1537     "k7", "k8", "k9", "k;", "F1", "F2",
1538     "%1", "&8", "kb", "kI", "kD", "kh",
1539     "@7", "kP", "kN", "K1", "K3", "K4", "K5", "kB",
1540     NULL
1541 };
1542 #endif
1543 
1544 /*
1545  * Set terminal options for terminal "term".
1546  * Return OK if terminal 'term' was found in a termcap, FAIL otherwise.
1547  *
1548  * While doing this, until ttest(), some options may be NULL, be careful.
1549  */
1550     int
1551 set_termname(term)
1552     char_u *term;
1553 {
1554     struct builtin_term *termp;
1555 #ifdef HAVE_TGETENT
1556     int		builtin_first = p_tbi;
1557     int		try;
1558     int		termcap_cleared = FALSE;
1559 #endif
1560     int		width = 0, height = 0;
1561     char_u	*error_msg = NULL;
1562     char_u	*bs_p, *del_p;
1563 
1564     /* In silect mode (ex -s) we don't use the 'term' option. */
1565     if (silent_mode)
1566 	return OK;
1567 
1568     detected_8bit = FALSE;		/* reset 8-bit detection */
1569 
1570     if (term_is_builtin(term))
1571     {
1572 	term += 8;
1573 #ifdef HAVE_TGETENT
1574 	builtin_first = 1;
1575 #endif
1576     }
1577 
1578 /*
1579  * If HAVE_TGETENT is not defined, only the builtin termcap is used, otherwise:
1580  *   If builtin_first is TRUE:
1581  *     0. try builtin termcap
1582  *     1. try external termcap
1583  *     2. if both fail default to a builtin terminal
1584  *   If builtin_first is FALSE:
1585  *     1. try external termcap
1586  *     2. try builtin termcap, if both fail default to a builtin terminal
1587  */
1588 #ifdef HAVE_TGETENT
1589     for (try = builtin_first ? 0 : 1; try < 3; ++try)
1590     {
1591 	/*
1592 	 * Use external termcap
1593 	 */
1594 	if (try == 1)
1595 	{
1596 	    char_u	    *p;
1597 	    static char_u   tstrbuf[TBUFSZ];
1598 	    int		    i;
1599 	    char_u	    tbuf[TBUFSZ];
1600 	    char_u	    *tp;
1601 	    static struct {
1602 			    enum SpecialKey dest; /* index in term_strings[] */
1603 			    char *name;		  /* termcap name for string */
1604 			  } string_names[] =
1605 			    {	{KS_CE, "ce"}, {KS_AL, "al"}, {KS_CAL,"AL"},
1606 				{KS_DL, "dl"}, {KS_CDL,"DL"}, {KS_CS, "cs"},
1607 				{KS_CL, "cl"}, {KS_CD, "cd"},
1608 				{KS_VI, "vi"}, {KS_VE, "ve"}, {KS_MB, "mb"},
1609 				{KS_VS, "vs"}, {KS_ME, "me"}, {KS_MR, "mr"},
1610 				{KS_MD, "md"}, {KS_SE, "se"}, {KS_SO, "so"},
1611 				{KS_CZH,"ZH"}, {KS_CZR,"ZR"}, {KS_UE, "ue"},
1612 				{KS_US, "us"}, {KS_UCE, "Ce"}, {KS_UCS, "Cs"},
1613 				{KS_CM, "cm"}, {KS_SR, "sr"},
1614 				{KS_CRI,"RI"}, {KS_VB, "vb"}, {KS_KS, "ks"},
1615 				{KS_KE, "ke"}, {KS_TI, "ti"}, {KS_TE, "te"},
1616 				{KS_BC, "bc"}, {KS_CSB,"Sb"}, {KS_CSF,"Sf"},
1617 				{KS_CAB,"AB"}, {KS_CAF,"AF"}, {KS_LE, "le"},
1618 				{KS_ND, "nd"}, {KS_OP, "op"}, {KS_CRV, "RV"},
1619 				{KS_CIS, "IS"}, {KS_CIE, "IE"},
1620 				{KS_TS, "ts"}, {KS_FS, "fs"},
1621 				{KS_CWP, "WP"}, {KS_CWS, "WS"},
1622 				{KS_CSI, "SI"}, {KS_CEI, "EI"},
1623 				{KS_U7, "u7"}, {KS_RBG, "RB"},
1624 				{(enum SpecialKey)0, NULL}
1625 			    };
1626 
1627 	    /*
1628 	     * If the external termcap does not have a matching entry, try the
1629 	     * builtin ones.
1630 	     */
1631 	    if ((error_msg = tgetent_error(tbuf, term)) == NULL)
1632 	    {
1633 		tp = tstrbuf;
1634 		if (!termcap_cleared)
1635 		{
1636 		    clear_termoptions();	/* clear old options */
1637 		    termcap_cleared = TRUE;
1638 		}
1639 
1640 	    /* get output strings */
1641 		for (i = 0; string_names[i].name != NULL; ++i)
1642 		{
1643 		    if (term_str(string_names[i].dest) == NULL
1644 			    || term_str(string_names[i].dest) == empty_option)
1645 			term_str(string_names[i].dest) =
1646 					   TGETSTR(string_names[i].name, &tp);
1647 		}
1648 
1649 		/* tgetflag() returns 1 if the flag is present, 0 if not and
1650 		 * possibly -1 if the flag doesn't exist. */
1651 		if ((T_MS == NULL || T_MS == empty_option)
1652 							&& tgetflag("ms") > 0)
1653 		    T_MS = (char_u *)"y";
1654 		if ((T_XS == NULL || T_XS == empty_option)
1655 							&& tgetflag("xs") > 0)
1656 		    T_XS = (char_u *)"y";
1657 		if ((T_XN == NULL || T_XN == empty_option)
1658 							&& tgetflag("xn") > 0)
1659 		    T_XN = (char_u *)"y";
1660 		if ((T_DB == NULL || T_DB == empty_option)
1661 							&& tgetflag("db") > 0)
1662 		    T_DB = (char_u *)"y";
1663 		if ((T_DA == NULL || T_DA == empty_option)
1664 							&& tgetflag("da") > 0)
1665 		    T_DA = (char_u *)"y";
1666 		if ((T_UT == NULL || T_UT == empty_option)
1667 							&& tgetflag("ut") > 0)
1668 		    T_UT = (char_u *)"y";
1669 
1670 
1671 		/*
1672 		 * get key codes
1673 		 */
1674 		for (i = 0; key_names[i] != NULL; ++i)
1675 		{
1676 		    if (find_termcode((char_u *)key_names[i]) == NULL)
1677 		    {
1678 			p = TGETSTR(key_names[i], &tp);
1679 			/* if cursor-left == backspace, ignore it (televideo
1680 			 * 925) */
1681 			if (p != NULL
1682 				&& (*p != Ctrl_H
1683 				    || key_names[i][0] != 'k'
1684 				    || key_names[i][1] != 'l'))
1685 			    add_termcode((char_u *)key_names[i], p, FALSE);
1686 		    }
1687 		}
1688 
1689 		if (height == 0)
1690 		    height = tgetnum("li");
1691 		if (width == 0)
1692 		    width = tgetnum("co");
1693 
1694 		/*
1695 		 * Get number of colors (if not done already).
1696 		 */
1697 		if (term_str(KS_CCO) == NULL
1698 			|| term_str(KS_CCO) == empty_option)
1699 		    set_color_count(tgetnum("Co"));
1700 
1701 # ifndef hpux
1702 		BC = (char *)TGETSTR("bc", &tp);
1703 		UP = (char *)TGETSTR("up", &tp);
1704 		p = TGETSTR("pc", &tp);
1705 		if (p)
1706 		    PC = *p;
1707 # endif /* hpux */
1708 	    }
1709 	}
1710 	else	    /* try == 0 || try == 2 */
1711 #endif /* HAVE_TGETENT */
1712 	/*
1713 	 * Use builtin termcap
1714 	 */
1715 	{
1716 #ifdef HAVE_TGETENT
1717 	    /*
1718 	     * If builtin termcap was already used, there is no need to search
1719 	     * for the builtin termcap again, quit now.
1720 	     */
1721 	    if (try == 2 && builtin_first && termcap_cleared)
1722 		break;
1723 #endif
1724 	    /*
1725 	     * search for 'term' in builtin_termcaps[]
1726 	     */
1727 	    termp = find_builtin_term(term);
1728 	    if (termp->bt_string == NULL)	/* did not find it */
1729 	    {
1730 #ifdef HAVE_TGETENT
1731 		/*
1732 		 * If try == 0, first try the external termcap. If that is not
1733 		 * found we'll get back here with try == 2.
1734 		 * If termcap_cleared is set we used the external termcap,
1735 		 * don't complain about not finding the term in the builtin
1736 		 * termcap.
1737 		 */
1738 		if (try == 0)			/* try external one */
1739 		    continue;
1740 		if (termcap_cleared)		/* found in external termcap */
1741 		    break;
1742 #endif
1743 
1744 		mch_errmsg("\r\n");
1745 		if (error_msg != NULL)
1746 		{
1747 		    mch_errmsg((char *)error_msg);
1748 		    mch_errmsg("\r\n");
1749 		}
1750 		mch_errmsg("'");
1751 		mch_errmsg((char *)term);
1752 		mch_errmsg(_("' not known. Available builtin terminals are:"));
1753 		mch_errmsg("\r\n");
1754 		for (termp = &(builtin_termcaps[0]); termp->bt_string != NULL;
1755 								      ++termp)
1756 		{
1757 		    if (termp->bt_entry == (int)KS_NAME)
1758 		    {
1759 #ifdef HAVE_TGETENT
1760 			mch_errmsg("    builtin_");
1761 #else
1762 			mch_errmsg("    ");
1763 #endif
1764 			mch_errmsg(termp->bt_string);
1765 			mch_errmsg("\r\n");
1766 		    }
1767 		}
1768 		/* when user typed :set term=xxx, quit here */
1769 		if (starting != NO_SCREEN)
1770 		{
1771 		    screen_start();	/* don't know where cursor is now */
1772 		    wait_return(TRUE);
1773 		    return FAIL;
1774 		}
1775 		term = DEFAULT_TERM;
1776 		mch_errmsg(_("defaulting to '"));
1777 		mch_errmsg((char *)term);
1778 		mch_errmsg("'\r\n");
1779 		if (emsg_silent == 0)
1780 		{
1781 		    screen_start();	/* don't know where cursor is now */
1782 		    out_flush();
1783 		    ui_delay(2000L, TRUE);
1784 		}
1785 		set_string_option_direct((char_u *)"term", -1, term,
1786 								 OPT_FREE, 0);
1787 		display_errors();
1788 	    }
1789 	    out_flush();
1790 #ifdef HAVE_TGETENT
1791 	    if (!termcap_cleared)
1792 	    {
1793 #endif
1794 		clear_termoptions();	    /* clear old options */
1795 #ifdef HAVE_TGETENT
1796 		termcap_cleared = TRUE;
1797 	    }
1798 #endif
1799 	    parse_builtin_tcap(term);
1800 #ifdef FEAT_GUI
1801 	    if (term_is_gui(term))
1802 	    {
1803 		out_flush();
1804 		gui_init();
1805 		/* If starting the GUI failed, don't do any of the other
1806 		 * things for this terminal */
1807 		if (!gui.in_use)
1808 		    return FAIL;
1809 #ifdef HAVE_TGETENT
1810 		break;		/* don't try using external termcap */
1811 #endif
1812 	    }
1813 #endif /* FEAT_GUI */
1814 	}
1815 #ifdef HAVE_TGETENT
1816     }
1817 #endif
1818 
1819 /*
1820  * special: There is no info in the termcap about whether the cursor
1821  * positioning is relative to the start of the screen or to the start of the
1822  * scrolling region.  We just guess here. Only msdos pcterm is known to do it
1823  * relative.
1824  */
1825     if (STRCMP(term, "pcterm") == 0)
1826 	T_CCS = (char_u *)"yes";
1827     else
1828 	T_CCS = empty_option;
1829 
1830 #ifdef UNIX
1831 /*
1832  * Any "stty" settings override the default for t_kb from the termcap.
1833  * This is in os_unix.c, because it depends a lot on the version of unix that
1834  * is being used.
1835  * Don't do this when the GUI is active, it uses "t_kb" and "t_kD" directly.
1836  */
1837 #ifdef FEAT_GUI
1838     if (!gui.in_use)
1839 #endif
1840 	get_stty();
1841 #endif
1842 
1843 /*
1844  * If the termcap has no entry for 'bs' and/or 'del' and the ioctl() also
1845  * didn't work, use the default CTRL-H
1846  * The default for t_kD is DEL, unless t_kb is DEL.
1847  * The vim_strsave'd strings are probably lost forever, well it's only two
1848  * bytes.  Don't do this when the GUI is active, it uses "t_kb" and "t_kD"
1849  * directly.
1850  */
1851 #ifdef FEAT_GUI
1852     if (!gui.in_use)
1853 #endif
1854     {
1855 	bs_p = find_termcode((char_u *)"kb");
1856 	del_p = find_termcode((char_u *)"kD");
1857 	if (bs_p == NULL || *bs_p == NUL)
1858 	    add_termcode((char_u *)"kb", (bs_p = (char_u *)CTRL_H_STR), FALSE);
1859 	if ((del_p == NULL || *del_p == NUL) &&
1860 					    (bs_p == NULL || *bs_p != DEL))
1861 	    add_termcode((char_u *)"kD", (char_u *)DEL_STR, FALSE);
1862     }
1863 
1864 #if defined(UNIX) || defined(VMS)
1865     term_is_xterm = vim_is_xterm(term);
1866 #endif
1867 
1868 #ifdef FEAT_MOUSE
1869 # if defined(UNIX) || defined(VMS)
1870 #  ifdef FEAT_MOUSE_TTY
1871     /*
1872      * For Unix, set the 'ttymouse' option to the type of mouse to be used.
1873      * The termcode for the mouse is added as a side effect in option.c.
1874      */
1875     {
1876 	char_u	*p;
1877 
1878 	p = (char_u *)"";
1879 #  ifdef FEAT_MOUSE_XTERM
1880 	if (use_xterm_like_mouse(term))
1881 	{
1882 	    if (use_xterm_mouse())
1883 		p = NULL;	/* keep existing value, might be "xterm2" */
1884 	    else
1885 		p = (char_u *)"xterm";
1886 	}
1887 #  endif
1888 	if (p != NULL)
1889 	{
1890 	    set_option_value((char_u *)"ttym", 0L, p, 0);
1891 	    /* Reset the WAS_SET flag, 'ttymouse' can be set to "sgr" or
1892 	     * "xterm2" in check_termcode(). */
1893 	    reset_option_was_set((char_u *)"ttym");
1894 	}
1895 	if (p == NULL
1896 #   ifdef FEAT_GUI
1897 		|| gui.in_use
1898 #   endif
1899 		)
1900 	    check_mouse_termcode();	/* set mouse termcode anyway */
1901     }
1902 #  endif
1903 # else
1904     set_mouse_termcode(KS_MOUSE, (char_u *)"\233M");
1905 # endif
1906 #endif	/* FEAT_MOUSE */
1907 
1908 #ifdef FEAT_SNIFF
1909     {
1910 	char_u	name[2];
1911 
1912 	name[0] = (int)KS_EXTRA;
1913 	name[1] = (int)KE_SNIFF;
1914 	add_termcode(name, (char_u *)"\233sniff", FALSE);
1915     }
1916 #endif
1917 
1918 #ifdef USE_TERM_CONSOLE
1919     /* DEFAULT_TERM indicates that it is the machine console. */
1920     if (STRCMP(term, DEFAULT_TERM) != 0)
1921 	term_console = FALSE;
1922     else
1923     {
1924 	term_console = TRUE;
1925 # ifdef AMIGA
1926 	win_resize_on();	/* enable window resizing reports */
1927 # endif
1928     }
1929 #endif
1930 
1931 #if defined(UNIX) || defined(VMS)
1932     /*
1933      * 'ttyfast' is default on for xterm, iris-ansi and a few others.
1934      */
1935     if (vim_is_fastterm(term))
1936 	p_tf = TRUE;
1937 #endif
1938 #ifdef USE_TERM_CONSOLE
1939     /*
1940      * 'ttyfast' is default on consoles
1941      */
1942     if (term_console)
1943 	p_tf = TRUE;
1944 #endif
1945 
1946     ttest(TRUE);	/* make sure we have a valid set of terminal codes */
1947 
1948     full_screen = TRUE;		/* we can use termcap codes from now on */
1949     set_term_defaults();	/* use current values as defaults */
1950 #ifdef FEAT_TERMRESPONSE
1951     LOG_TR("setting crv_status to CRV_GET");
1952     crv_status = CRV_GET;	/* Get terminal version later */
1953 #endif
1954 
1955     /*
1956      * Initialize the terminal with the appropriate termcap codes.
1957      * Set the mouse and window title if possible.
1958      * Don't do this when starting, need to parse the .vimrc first, because it
1959      * may redefine t_TI etc.
1960      */
1961     if (starting != NO_SCREEN)
1962     {
1963 	starttermcap();		/* may change terminal mode */
1964 #ifdef FEAT_MOUSE
1965 	setmouse();		/* may start using the mouse */
1966 #endif
1967 #ifdef FEAT_TITLE
1968 	maketitle();		/* may display window title */
1969 #endif
1970     }
1971 
1972 	/* display initial screen after ttest() checking. jw. */
1973     if (width <= 0 || height <= 0)
1974     {
1975 	/* termcap failed to report size */
1976 	/* set defaults, in case ui_get_shellsize() also fails */
1977 	width = 80;
1978 #if defined(MSDOS) || defined(WIN3264)
1979 	height = 25;	    /* console is often 25 lines */
1980 #else
1981 	height = 24;	    /* most terminals are 24 lines */
1982 #endif
1983     }
1984     set_shellsize(width, height, FALSE);	/* may change Rows */
1985     if (starting != NO_SCREEN)
1986     {
1987 	if (scroll_region)
1988 	    scroll_region_reset();		/* In case Rows changed */
1989 	check_map_keycodes();	/* check mappings for terminal codes used */
1990 
1991 #ifdef FEAT_AUTOCMD
1992 	{
1993 	    buf_T	*old_curbuf;
1994 
1995 	    /*
1996 	     * Execute the TermChanged autocommands for each buffer that is
1997 	     * loaded.
1998 	     */
1999 	    old_curbuf = curbuf;
2000 	    for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next)
2001 	    {
2002 		if (curbuf->b_ml.ml_mfp != NULL)
2003 		    apply_autocmds(EVENT_TERMCHANGED, NULL, NULL, FALSE,
2004 								      curbuf);
2005 	    }
2006 	    if (buf_valid(old_curbuf))
2007 		curbuf = old_curbuf;
2008 	}
2009 #endif
2010     }
2011 
2012 #ifdef FEAT_TERMRESPONSE
2013     may_req_termresponse();
2014 #endif
2015 
2016     return OK;
2017 }
2018 
2019 #if defined(FEAT_MOUSE) || defined(PROTO)
2020 
2021 # ifdef FEAT_MOUSE_TTY
2022 #  define HMT_NORMAL	1
2023 #  define HMT_NETTERM	2
2024 #  define HMT_DEC	4
2025 #  define HMT_JSBTERM	8
2026 #  define HMT_PTERM	16
2027 #  define HMT_URXVT	32
2028 #  define HMT_SGR	64
2029 static int has_mouse_termcode = 0;
2030 # endif
2031 
2032 # if (!defined(UNIX) || defined(FEAT_MOUSE_TTY)) || defined(PROTO)
2033     void
2034 set_mouse_termcode(n, s)
2035     int		n;	/* KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE */
2036     char_u	*s;
2037 {
2038     char_u	name[2];
2039 
2040     name[0] = n;
2041     name[1] = KE_FILLER;
2042     add_termcode(name, s, FALSE);
2043 #  ifdef FEAT_MOUSE_TTY
2044 #   ifdef FEAT_MOUSE_JSB
2045     if (n == KS_JSBTERM_MOUSE)
2046 	has_mouse_termcode |= HMT_JSBTERM;
2047     else
2048 #   endif
2049 #   ifdef FEAT_MOUSE_NET
2050     if (n == KS_NETTERM_MOUSE)
2051 	has_mouse_termcode |= HMT_NETTERM;
2052     else
2053 #   endif
2054 #   ifdef FEAT_MOUSE_DEC
2055     if (n == KS_DEC_MOUSE)
2056 	has_mouse_termcode |= HMT_DEC;
2057     else
2058 #   endif
2059 #   ifdef FEAT_MOUSE_PTERM
2060     if (n == KS_PTERM_MOUSE)
2061 	has_mouse_termcode |= HMT_PTERM;
2062     else
2063 #   endif
2064 #   ifdef FEAT_MOUSE_URXVT
2065     if (n == KS_URXVT_MOUSE)
2066 	has_mouse_termcode |= HMT_URXVT;
2067     else
2068 #   endif
2069 #   ifdef FEAT_MOUSE_SGR
2070     if (n == KS_SGR_MOUSE)
2071 	has_mouse_termcode |= HMT_SGR;
2072     else
2073 #   endif
2074 	has_mouse_termcode |= HMT_NORMAL;
2075 #  endif
2076 }
2077 # endif
2078 
2079 # if ((defined(UNIX) || defined(VMS)) \
2080 	&& defined(FEAT_MOUSE_TTY)) || defined(PROTO)
2081     void
2082 del_mouse_termcode(n)
2083     int		n;	/* KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE */
2084 {
2085     char_u	name[2];
2086 
2087     name[0] = n;
2088     name[1] = KE_FILLER;
2089     del_termcode(name);
2090 #  ifdef FEAT_MOUSE_TTY
2091 #   ifdef FEAT_MOUSE_JSB
2092     if (n == KS_JSBTERM_MOUSE)
2093 	has_mouse_termcode &= ~HMT_JSBTERM;
2094     else
2095 #   endif
2096 #   ifdef FEAT_MOUSE_NET
2097     if (n == KS_NETTERM_MOUSE)
2098 	has_mouse_termcode &= ~HMT_NETTERM;
2099     else
2100 #   endif
2101 #   ifdef FEAT_MOUSE_DEC
2102     if (n == KS_DEC_MOUSE)
2103 	has_mouse_termcode &= ~HMT_DEC;
2104     else
2105 #   endif
2106 #   ifdef FEAT_MOUSE_PTERM
2107     if (n == KS_PTERM_MOUSE)
2108 	has_mouse_termcode &= ~HMT_PTERM;
2109     else
2110 #   endif
2111 #   ifdef FEAT_MOUSE_URXVT
2112     if (n == KS_URXVT_MOUSE)
2113 	has_mouse_termcode &= ~HMT_URXVT;
2114     else
2115 #   endif
2116 #   ifdef FEAT_MOUSE_SGR
2117     if (n == KS_SGR_MOUSE)
2118 	has_mouse_termcode &= ~HMT_SGR;
2119     else
2120 #   endif
2121 	has_mouse_termcode &= ~HMT_NORMAL;
2122 #  endif
2123 }
2124 # endif
2125 #endif
2126 
2127 #ifdef HAVE_TGETENT
2128 /*
2129  * Call tgetent()
2130  * Return error message if it fails, NULL if it's OK.
2131  */
2132     static char_u *
2133 tgetent_error(tbuf, term)
2134     char_u  *tbuf;
2135     char_u  *term;
2136 {
2137     int	    i;
2138 
2139     i = TGETENT(tbuf, term);
2140     if (i < 0		    /* -1 is always an error */
2141 # ifdef TGETENT_ZERO_ERR
2142 	    || i == 0	    /* sometimes zero is also an error */
2143 # endif
2144        )
2145     {
2146 	/* On FreeBSD tputs() gets a SEGV after a tgetent() which fails.  Call
2147 	 * tgetent() with the always existing "dumb" entry to avoid a crash or
2148 	 * hang. */
2149 	(void)TGETENT(tbuf, "dumb");
2150 
2151 	if (i < 0)
2152 # ifdef TGETENT_ZERO_ERR
2153 	    return (char_u *)_("E557: Cannot open termcap file");
2154 	if (i == 0)
2155 # endif
2156 #ifdef TERMINFO
2157 	    return (char_u *)_("E558: Terminal entry not found in terminfo");
2158 #else
2159 	    return (char_u *)_("E559: Terminal entry not found in termcap");
2160 #endif
2161     }
2162     return NULL;
2163 }
2164 
2165 /*
2166  * Some versions of tgetstr() have been reported to return -1 instead of NULL.
2167  * Fix that here.
2168  */
2169     static char_u *
2170 vim_tgetstr(s, pp)
2171     char	*s;
2172     char_u	**pp;
2173 {
2174     char	*p;
2175 
2176     p = tgetstr(s, (char **)pp);
2177     if (p == (char *)-1)
2178 	p = NULL;
2179     return (char_u *)p;
2180 }
2181 #endif /* HAVE_TGETENT */
2182 
2183 #if defined(HAVE_TGETENT) && (defined(UNIX) || defined(__EMX__) || defined(VMS) || defined(MACOS_X))
2184 /*
2185  * Get Columns and Rows from the termcap. Used after a window signal if the
2186  * ioctl() fails. It doesn't make sense to call tgetent each time if the "co"
2187  * and "li" entries never change. But on some systems this works.
2188  * Errors while getting the entries are ignored.
2189  */
2190     void
2191 getlinecol(cp, rp)
2192     long	*cp;	/* pointer to columns */
2193     long	*rp;	/* pointer to rows */
2194 {
2195     char_u	tbuf[TBUFSZ];
2196 
2197     if (T_NAME != NULL && *T_NAME != NUL && tgetent_error(tbuf, T_NAME) == NULL)
2198     {
2199 	if (*cp == 0)
2200 	    *cp = tgetnum("co");
2201 	if (*rp == 0)
2202 	    *rp = tgetnum("li");
2203     }
2204 }
2205 #endif /* defined(HAVE_TGETENT) && defined(UNIX) */
2206 
2207 /*
2208  * Get a string entry from the termcap and add it to the list of termcodes.
2209  * Used for <t_xx> special keys.
2210  * Give an error message for failure when not sourcing.
2211  * If force given, replace an existing entry.
2212  * Return FAIL if the entry was not found, OK if the entry was added.
2213  */
2214     int
2215 add_termcap_entry(name, force)
2216     char_u  *name;
2217     int	    force;
2218 {
2219     char_u  *term;
2220     int	    key;
2221     struct builtin_term *termp;
2222 #ifdef HAVE_TGETENT
2223     char_u  *string;
2224     int	    i;
2225     int	    builtin_first;
2226     char_u  tbuf[TBUFSZ];
2227     char_u  tstrbuf[TBUFSZ];
2228     char_u  *tp = tstrbuf;
2229     char_u  *error_msg = NULL;
2230 #endif
2231 
2232 /*
2233  * If the GUI is running or will start in a moment, we only support the keys
2234  * that the GUI can produce.
2235  */
2236 #ifdef FEAT_GUI
2237     if (gui.in_use || gui.starting)
2238 	return gui_mch_haskey(name);
2239 #endif
2240 
2241     if (!force && find_termcode(name) != NULL)	    /* it's already there */
2242 	return OK;
2243 
2244     term = T_NAME;
2245     if (term == NULL || *term == NUL)	    /* 'term' not defined yet */
2246 	return FAIL;
2247 
2248     if (term_is_builtin(term))		    /* name starts with "builtin_" */
2249     {
2250 	term += 8;
2251 #ifdef HAVE_TGETENT
2252 	builtin_first = TRUE;
2253 #endif
2254     }
2255 #ifdef HAVE_TGETENT
2256     else
2257 	builtin_first = p_tbi;
2258 #endif
2259 
2260 #ifdef HAVE_TGETENT
2261 /*
2262  * We can get the entry from the builtin termcap and from the external one.
2263  * If 'ttybuiltin' is on or the terminal name starts with "builtin_", try
2264  * builtin termcap first.
2265  * If 'ttybuiltin' is off, try external termcap first.
2266  */
2267     for (i = 0; i < 2; ++i)
2268     {
2269 	if ((!builtin_first) == i)
2270 #endif
2271 	/*
2272 	 * Search in builtin termcap
2273 	 */
2274 	{
2275 	    termp = find_builtin_term(term);
2276 	    if (termp->bt_string != NULL)	/* found it */
2277 	    {
2278 		key = TERMCAP2KEY(name[0], name[1]);
2279 		while (termp->bt_entry != (int)KS_NAME)
2280 		{
2281 		    if ((int)termp->bt_entry == key)
2282 		    {
2283 			add_termcode(name, (char_u *)termp->bt_string,
2284 							  term_is_8bit(term));
2285 			return OK;
2286 		    }
2287 		    ++termp;
2288 		}
2289 	    }
2290 	}
2291 #ifdef HAVE_TGETENT
2292 	else
2293 	/*
2294 	 * Search in external termcap
2295 	 */
2296 	{
2297 	    error_msg = tgetent_error(tbuf, term);
2298 	    if (error_msg == NULL)
2299 	    {
2300 		string = TGETSTR((char *)name, &tp);
2301 		if (string != NULL && *string != NUL)
2302 		{
2303 		    add_termcode(name, string, FALSE);
2304 		    return OK;
2305 		}
2306 	    }
2307 	}
2308     }
2309 #endif
2310 
2311     if (sourcing_name == NULL)
2312     {
2313 #ifdef HAVE_TGETENT
2314 	if (error_msg != NULL)
2315 	    EMSG(error_msg);
2316 	else
2317 #endif
2318 	    EMSG2(_("E436: No \"%s\" entry in termcap"), name);
2319     }
2320     return FAIL;
2321 }
2322 
2323     static int
2324 term_is_builtin(name)
2325     char_u  *name;
2326 {
2327     return (STRNCMP(name, "builtin_", (size_t)8) == 0);
2328 }
2329 
2330 /*
2331  * Return TRUE if terminal "name" uses CSI instead of <Esc>[.
2332  * Assume that the terminal is using 8-bit controls when the name contains
2333  * "8bit", like in "xterm-8bit".
2334  */
2335     int
2336 term_is_8bit(name)
2337     char_u  *name;
2338 {
2339     return (detected_8bit || strstr((char *)name, "8bit") != NULL);
2340 }
2341 
2342 /*
2343  * Translate terminal control chars from 7-bit to 8-bit:
2344  * <Esc>[ -> CSI
2345  * <Esc>] -> <M-C-]>
2346  * <Esc>O -> <M-C-O>
2347  */
2348     static int
2349 term_7to8bit(p)
2350     char_u  *p;
2351 {
2352     if (*p == ESC)
2353     {
2354 	if (p[1] == '[')
2355 	    return CSI;
2356 	if (p[1] == ']')
2357 	    return OSC;
2358 	if (p[1] == 'O')
2359 	    return 0x8f;
2360     }
2361     return 0;
2362 }
2363 
2364 #ifdef FEAT_GUI
2365     int
2366 term_is_gui(name)
2367     char_u  *name;
2368 {
2369     return (STRCMP(name, "builtin_gui") == 0 || STRCMP(name, "gui") == 0);
2370 }
2371 #endif
2372 
2373 #if !defined(HAVE_TGETENT) || defined(AMIGA) || defined(PROTO)
2374 
2375     char_u *
2376 tltoa(i)
2377     unsigned long i;
2378 {
2379     static char_u buf[16];
2380     char_u	*p;
2381 
2382     p = buf + 15;
2383     *p = '\0';
2384     do
2385     {
2386 	--p;
2387 	*p = (char_u) (i % 10 + '0');
2388 	i /= 10;
2389     }
2390     while (i > 0 && p > buf);
2391     return p;
2392 }
2393 #endif
2394 
2395 #ifndef HAVE_TGETENT
2396 
2397 /*
2398  * minimal tgoto() implementation.
2399  * no padding and we only parse for %i %d and %+char
2400  */
2401 static char *tgoto __ARGS((char *, int, int));
2402 
2403     static char *
2404 tgoto(cm, x, y)
2405     char *cm;
2406     int x, y;
2407 {
2408     static char buf[30];
2409     char *p, *s, *e;
2410 
2411     if (!cm)
2412 	return "OOPS";
2413     e = buf + 29;
2414     for (s = buf; s < e && *cm; cm++)
2415     {
2416 	if (*cm != '%')
2417 	{
2418 	    *s++ = *cm;
2419 	    continue;
2420 	}
2421 	switch (*++cm)
2422 	{
2423 	case 'd':
2424 	    p = (char *)tltoa((unsigned long)y);
2425 	    y = x;
2426 	    while (*p)
2427 		*s++ = *p++;
2428 	    break;
2429 	case 'i':
2430 	    x++;
2431 	    y++;
2432 	    break;
2433 	case '+':
2434 	    *s++ = (char)(*++cm + y);
2435 	    y = x;
2436 	    break;
2437 	case '%':
2438 	    *s++ = *cm;
2439 	    break;
2440 	default:
2441 	    return "OOPS";
2442 	}
2443     }
2444     *s = '\0';
2445     return buf;
2446 }
2447 
2448 #endif /* HAVE_TGETENT */
2449 
2450 /*
2451  * Set the terminal name and initialize the terminal options.
2452  * If "name" is NULL or empty, get the terminal name from the environment.
2453  * If that fails, use the default terminal name.
2454  */
2455     void
2456 termcapinit(name)
2457     char_u *name;
2458 {
2459     char_u	*term;
2460 
2461     if (name != NULL && *name == NUL)
2462 	name = NULL;	    /* empty name is equal to no name */
2463     term = name;
2464 
2465 #ifdef __BEOS__
2466     /*
2467      * TERM environment variable is normally set to 'ansi' on the Bebox;
2468      * Since the BeBox doesn't quite support full ANSI yet, we use our
2469      * own custom 'ansi-beos' termcap instead, unless the -T option has
2470      * been given on the command line.
2471      */
2472     if (term == NULL
2473 		 && strcmp((char *)mch_getenv((char_u *)"TERM"), "ansi") == 0)
2474 	term = DEFAULT_TERM;
2475 #endif
2476 #ifndef MSWIN
2477     if (term == NULL)
2478 	term = mch_getenv((char_u *)"TERM");
2479 #endif
2480     if (term == NULL || *term == NUL)
2481 	term = DEFAULT_TERM;
2482     set_string_option_direct((char_u *)"term", -1, term, OPT_FREE, 0);
2483 
2484     /* Set the default terminal name. */
2485     set_string_default("term", term);
2486     set_string_default("ttytype", term);
2487 
2488     /*
2489      * Avoid using "term" here, because the next mch_getenv() may overwrite it.
2490      */
2491     set_termname(T_NAME != NULL ? T_NAME : term);
2492 }
2493 
2494 /*
2495  * the number of calls to ui_write is reduced by using the buffer "out_buf"
2496  */
2497 #ifdef DOS16
2498 # define OUT_SIZE	255		/* only have 640K total... */
2499 #else
2500 # ifdef FEAT_GUI_W16
2501 #  define OUT_SIZE	1023		/* Save precious 1K near data */
2502 # else
2503 #  define OUT_SIZE	2047
2504 # endif
2505 #endif
2506 	    /* Add one to allow mch_write() in os_win32.c to append a NUL */
2507 static char_u		out_buf[OUT_SIZE + 1];
2508 static int		out_pos = 0;	/* number of chars in out_buf */
2509 
2510 /*
2511  * out_flush(): flush the output buffer
2512  */
2513     void
2514 out_flush()
2515 {
2516     int	    len;
2517 
2518     if (out_pos != 0)
2519     {
2520 	/* set out_pos to 0 before ui_write, to avoid recursiveness */
2521 	len = out_pos;
2522 	out_pos = 0;
2523 	ui_write(out_buf, len);
2524     }
2525 }
2526 
2527 #if defined(FEAT_MBYTE) || defined(PROTO)
2528 /*
2529  * Sometimes a byte out of a multi-byte character is written with out_char().
2530  * To avoid flushing half of the character, call this function first.
2531  */
2532     void
2533 out_flush_check()
2534 {
2535     if (enc_dbcs != 0 && out_pos >= OUT_SIZE - MB_MAXBYTES)
2536 	out_flush();
2537 }
2538 #endif
2539 
2540 #ifdef FEAT_GUI
2541 /*
2542  * out_trash(): Throw away the contents of the output buffer
2543  */
2544     void
2545 out_trash()
2546 {
2547     out_pos = 0;
2548 }
2549 #endif
2550 
2551 /*
2552  * out_char(c): put a byte into the output buffer.
2553  *		Flush it if it becomes full.
2554  * This should not be used for outputting text on the screen (use functions
2555  * like msg_puts() and screen_putchar() for that).
2556  */
2557     void
2558 out_char(c)
2559     unsigned	c;
2560 {
2561 #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(MACOS_X_UNIX)
2562     if (c == '\n')	/* turn LF into CR-LF (CRMOD doesn't seem to do this) */
2563 	out_char('\r');
2564 #endif
2565 
2566     out_buf[out_pos++] = c;
2567 
2568     /* For testing we flush each time. */
2569     if (out_pos >= OUT_SIZE || p_wd)
2570 	out_flush();
2571 }
2572 
2573 static void out_char_nf __ARGS((unsigned));
2574 
2575 /*
2576  * out_char_nf(c): like out_char(), but don't flush when p_wd is set
2577  */
2578     static void
2579 out_char_nf(c)
2580     unsigned	c;
2581 {
2582 #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(MACOS_X_UNIX)
2583     if (c == '\n')	/* turn LF into CR-LF (CRMOD doesn't seem to do this) */
2584 	out_char_nf('\r');
2585 #endif
2586 
2587     out_buf[out_pos++] = c;
2588 
2589     if (out_pos >= OUT_SIZE)
2590 	out_flush();
2591 }
2592 
2593 #if defined(FEAT_TITLE) || defined(FEAT_MOUSE_TTY) || defined(FEAT_GUI) \
2594     || defined(FEAT_TERMRESPONSE) || defined(PROTO)
2595 /*
2596  * A never-padding out_str.
2597  * use this whenever you don't want to run the string through tputs.
2598  * tputs above is harmless, but tputs from the termcap library
2599  * is likely to strip off leading digits, that it mistakes for padding
2600  * information, and "%i", "%d", etc.
2601  * This should only be used for writing terminal codes, not for outputting
2602  * normal text (use functions like msg_puts() and screen_putchar() for that).
2603  */
2604     void
2605 out_str_nf(s)
2606     char_u *s;
2607 {
2608     if (out_pos > OUT_SIZE - 20)  /* avoid terminal strings being split up */
2609 	out_flush();
2610     while (*s)
2611 	out_char_nf(*s++);
2612 
2613     /* For testing we write one string at a time. */
2614     if (p_wd)
2615 	out_flush();
2616 }
2617 #endif
2618 
2619 /*
2620  * out_str(s): Put a character string a byte at a time into the output buffer.
2621  * If HAVE_TGETENT is defined use the termcap parser. (jw)
2622  * This should only be used for writing terminal codes, not for outputting
2623  * normal text (use functions like msg_puts() and screen_putchar() for that).
2624  */
2625     void
2626 out_str(s)
2627     char_u	 *s;
2628 {
2629     if (s != NULL && *s)
2630     {
2631 #ifdef FEAT_GUI
2632 	/* Don't use tputs() when GUI is used, ncurses crashes. */
2633 	if (gui.in_use)
2634 	{
2635 	    out_str_nf(s);
2636 	    return;
2637 	}
2638 #endif
2639 	/* avoid terminal strings being split up */
2640 	if (out_pos > OUT_SIZE - 20)
2641 	    out_flush();
2642 #ifdef HAVE_TGETENT
2643 	tputs((char *)s, 1, TPUTSFUNCAST out_char_nf);
2644 #else
2645 	while (*s)
2646 	    out_char_nf(*s++);
2647 #endif
2648 
2649 	/* For testing we write one string at a time. */
2650 	if (p_wd)
2651 	    out_flush();
2652     }
2653 }
2654 
2655 /*
2656  * cursor positioning using termcap parser. (jw)
2657  */
2658     void
2659 term_windgoto(row, col)
2660     int	    row;
2661     int	    col;
2662 {
2663     OUT_STR(tgoto((char *)T_CM, col, row));
2664 }
2665 
2666     void
2667 term_cursor_right(i)
2668     int	    i;
2669 {
2670     OUT_STR(tgoto((char *)T_CRI, 0, i));
2671 }
2672 
2673     void
2674 term_append_lines(line_count)
2675     int	    line_count;
2676 {
2677     OUT_STR(tgoto((char *)T_CAL, 0, line_count));
2678 }
2679 
2680     void
2681 term_delete_lines(line_count)
2682     int	    line_count;
2683 {
2684     OUT_STR(tgoto((char *)T_CDL, 0, line_count));
2685 }
2686 
2687 #if defined(HAVE_TGETENT) || defined(PROTO)
2688     void
2689 term_set_winpos(x, y)
2690     int	    x;
2691     int	    y;
2692 {
2693     /* Can't handle a negative value here */
2694     if (x < 0)
2695 	x = 0;
2696     if (y < 0)
2697 	y = 0;
2698     OUT_STR(tgoto((char *)T_CWP, y, x));
2699 }
2700 
2701     void
2702 term_set_winsize(width, height)
2703     int	    width;
2704     int	    height;
2705 {
2706     OUT_STR(tgoto((char *)T_CWS, height, width));
2707 }
2708 #endif
2709 
2710     void
2711 term_fg_color(n)
2712     int	    n;
2713 {
2714     /* Use "AF" termcap entry if present, "Sf" entry otherwise */
2715     if (*T_CAF)
2716 	term_color(T_CAF, n);
2717     else if (*T_CSF)
2718 	term_color(T_CSF, n);
2719 }
2720 
2721     void
2722 term_bg_color(n)
2723     int	    n;
2724 {
2725     /* Use "AB" termcap entry if present, "Sb" entry otherwise */
2726     if (*T_CAB)
2727 	term_color(T_CAB, n);
2728     else if (*T_CSB)
2729 	term_color(T_CSB, n);
2730 }
2731 
2732     static void
2733 term_color(s, n)
2734     char_u	*s;
2735     int		n;
2736 {
2737     char	buf[20];
2738     int i = 2;	/* index in s[] just after <Esc>[ or CSI */
2739 
2740     /* Special handling of 16 colors, because termcap can't handle it */
2741     /* Also accept "\e[3%dm" for TERMINFO, it is sometimes used */
2742     /* Also accept CSI instead of <Esc>[ */
2743     if (n >= 8 && t_colors >= 16
2744 	      && ((s[0] == ESC && s[1] == '[') || (s[0] == CSI && (i = 1) == 1))
2745 	      && s[i] != NUL
2746 	      && (STRCMP(s + i + 1, "%p1%dm") == 0
2747 		  || STRCMP(s + i + 1, "%dm") == 0)
2748 	      && (s[i] == '3' || s[i] == '4'))
2749     {
2750 	sprintf(buf,
2751 #ifdef TERMINFO
2752 		"%s%s%%p1%%dm",
2753 #else
2754 		"%s%s%%dm",
2755 #endif
2756 		i == 2 ? IF_EB("\033[", ESC_STR "[") : "\233",
2757 		s[i] == '3' ? (n >= 16 ? "38;5;" : "9")
2758 			    : (n >= 16 ? "48;5;" : "10"));
2759 	OUT_STR(tgoto(buf, 0, n >= 16 ? n : n - 8));
2760     }
2761     else
2762 	OUT_STR(tgoto((char *)s, 0, n));
2763 }
2764 
2765 #if (defined(FEAT_TITLE) && (defined(UNIX) || defined(VMS) \
2766 	|| defined(MACOS_X))) || defined(PROTO)
2767 /*
2768  * Generic function to set window title, using t_ts and t_fs.
2769  */
2770     void
2771 term_settitle(title)
2772     char_u	*title;
2773 {
2774     /* t_ts takes one argument: column in status line */
2775     OUT_STR(tgoto((char *)T_TS, 0, 0));	/* set title start */
2776     out_str_nf(title);
2777     out_str(T_FS);			/* set title end */
2778     out_flush();
2779 }
2780 #endif
2781 
2782 /*
2783  * Make sure we have a valid set or terminal options.
2784  * Replace all entries that are NULL by empty_option
2785  */
2786     void
2787 ttest(pairs)
2788     int	pairs;
2789 {
2790     check_options();		    /* make sure no options are NULL */
2791 
2792     /*
2793      * MUST have "cm": cursor motion.
2794      */
2795     if (*T_CM == NUL)
2796 	EMSG(_("E437: terminal capability \"cm\" required"));
2797 
2798     /*
2799      * if "cs" defined, use a scroll region, it's faster.
2800      */
2801     if (*T_CS != NUL)
2802 	scroll_region = TRUE;
2803     else
2804 	scroll_region = FALSE;
2805 
2806     if (pairs)
2807     {
2808 	/*
2809 	 * optional pairs
2810 	 */
2811 	/* TP goes to normal mode for TI (invert) and TB (bold) */
2812 	if (*T_ME == NUL)
2813 	    T_ME = T_MR = T_MD = T_MB = empty_option;
2814 	if (*T_SO == NUL || *T_SE == NUL)
2815 	    T_SO = T_SE = empty_option;
2816 	if (*T_US == NUL || *T_UE == NUL)
2817 	    T_US = T_UE = empty_option;
2818 	if (*T_CZH == NUL || *T_CZR == NUL)
2819 	    T_CZH = T_CZR = empty_option;
2820 
2821 	/* T_VE is needed even though T_VI is not defined */
2822 	if (*T_VE == NUL)
2823 	    T_VI = empty_option;
2824 
2825 	/* if 'mr' or 'me' is not defined use 'so' and 'se' */
2826 	if (*T_ME == NUL)
2827 	{
2828 	    T_ME = T_SE;
2829 	    T_MR = T_SO;
2830 	    T_MD = T_SO;
2831 	}
2832 
2833 	/* if 'so' or 'se' is not defined use 'mr' and 'me' */
2834 	if (*T_SO == NUL)
2835 	{
2836 	    T_SE = T_ME;
2837 	    if (*T_MR == NUL)
2838 		T_SO = T_MD;
2839 	    else
2840 		T_SO = T_MR;
2841 	}
2842 
2843 	/* if 'ZH' or 'ZR' is not defined use 'mr' and 'me' */
2844 	if (*T_CZH == NUL)
2845 	{
2846 	    T_CZR = T_ME;
2847 	    if (*T_MR == NUL)
2848 		T_CZH = T_MD;
2849 	    else
2850 		T_CZH = T_MR;
2851 	}
2852 
2853 	/* "Sb" and "Sf" come in pairs */
2854 	if (*T_CSB == NUL || *T_CSF == NUL)
2855 	{
2856 	    T_CSB = empty_option;
2857 	    T_CSF = empty_option;
2858 	}
2859 
2860 	/* "AB" and "AF" come in pairs */
2861 	if (*T_CAB == NUL || *T_CAF == NUL)
2862 	{
2863 	    T_CAB = empty_option;
2864 	    T_CAF = empty_option;
2865 	}
2866 
2867 	/* if 'Sb' and 'AB' are not defined, reset "Co" */
2868 	if (*T_CSB == NUL && *T_CAB == NUL)
2869 	    free_one_termoption(T_CCO);
2870 
2871 	/* Set 'weirdinvert' according to value of 't_xs' */
2872 	p_wiv = (*T_XS != NUL);
2873     }
2874     need_gather = TRUE;
2875 
2876     /* Set t_colors to the value of t_Co. */
2877     t_colors = atoi((char *)T_CCO);
2878 }
2879 
2880 #if (defined(FEAT_GUI) && (defined(FEAT_MENU) || !defined(USE_ON_FLY_SCROLL))) \
2881 	|| defined(PROTO)
2882 /*
2883  * Represent the given long_u as individual bytes, with the most significant
2884  * byte first, and store them in dst.
2885  */
2886     void
2887 add_long_to_buf(val, dst)
2888     long_u  val;
2889     char_u  *dst;
2890 {
2891     int	    i;
2892     int	    shift;
2893 
2894     for (i = 1; i <= (int)sizeof(long_u); i++)
2895     {
2896 	shift = 8 * (sizeof(long_u) - i);
2897 	dst[i - 1] = (char_u) ((val >> shift) & 0xff);
2898     }
2899 }
2900 
2901 static int get_long_from_buf __ARGS((char_u *buf, long_u *val));
2902 
2903 /*
2904  * Interpret the next string of bytes in buf as a long integer, with the most
2905  * significant byte first.  Note that it is assumed that buf has been through
2906  * inchar(), so that NUL and K_SPECIAL will be represented as three bytes each.
2907  * Puts result in val, and returns the number of bytes read from buf
2908  * (between sizeof(long_u) and 2 * sizeof(long_u)), or -1 if not enough bytes
2909  * were present.
2910  */
2911     static int
2912 get_long_from_buf(buf, val)
2913     char_u  *buf;
2914     long_u  *val;
2915 {
2916     int	    len;
2917     char_u  bytes[sizeof(long_u)];
2918     int	    i;
2919     int	    shift;
2920 
2921     *val = 0;
2922     len = get_bytes_from_buf(buf, bytes, (int)sizeof(long_u));
2923     if (len != -1)
2924     {
2925 	for (i = 0; i < (int)sizeof(long_u); i++)
2926 	{
2927 	    shift = 8 * (sizeof(long_u) - 1 - i);
2928 	    *val += (long_u)bytes[i] << shift;
2929 	}
2930     }
2931     return len;
2932 }
2933 #endif
2934 
2935 #if defined(FEAT_GUI) \
2936     || (defined(FEAT_MOUSE) && (!defined(UNIX) || defined(FEAT_MOUSE_XTERM) \
2937 		|| defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)))
2938 /*
2939  * Read the next num_bytes bytes from buf, and store them in bytes.  Assume
2940  * that buf has been through inchar().	Returns the actual number of bytes used
2941  * from buf (between num_bytes and num_bytes*2), or -1 if not enough bytes were
2942  * available.
2943  */
2944     static int
2945 get_bytes_from_buf(buf, bytes, num_bytes)
2946     char_u  *buf;
2947     char_u  *bytes;
2948     int	    num_bytes;
2949 {
2950     int	    len = 0;
2951     int	    i;
2952     char_u  c;
2953 
2954     for (i = 0; i < num_bytes; i++)
2955     {
2956 	if ((c = buf[len++]) == NUL)
2957 	    return -1;
2958 	if (c == K_SPECIAL)
2959 	{
2960 	    if (buf[len] == NUL || buf[len + 1] == NUL)	    /* cannot happen? */
2961 		return -1;
2962 	    if (buf[len++] == (int)KS_ZERO)
2963 		c = NUL;
2964 	    /* else it should be KS_SPECIAL; when followed by KE_FILLER c is
2965 	     * K_SPECIAL, or followed by KE_CSI and c must be CSI. */
2966 	    if (buf[len++] == (int)KE_CSI)
2967 		c = CSI;
2968 	}
2969 	else if (c == CSI && buf[len] == KS_EXTRA
2970 					       && buf[len + 1] == (int)KE_CSI)
2971 	    /* CSI is stored as CSI KS_SPECIAL KE_CSI to avoid confusion with
2972 	     * the start of a special key, see add_to_input_buf_csi(). */
2973 	    len += 2;
2974 	bytes[i] = c;
2975     }
2976     return len;
2977 }
2978 #endif
2979 
2980 /*
2981  * Check if the new shell size is valid, correct it if it's too small or way
2982  * too big.
2983  */
2984     void
2985 check_shellsize()
2986 {
2987     if (Rows < min_rows())	/* need room for one window and command line */
2988 	Rows = min_rows();
2989     limit_screen_size();
2990 }
2991 
2992 /*
2993  * Limit Rows and Columns to avoid an overflow in Rows * Columns.
2994  */
2995     void
2996 limit_screen_size()
2997 {
2998     if (Columns < MIN_COLUMNS)
2999 	Columns = MIN_COLUMNS;
3000     else if (Columns > 10000)
3001 	Columns = 10000;
3002     if (Rows > 1000)
3003 	Rows = 1000;
3004 }
3005 
3006 /*
3007  * Invoked just before the screen structures are going to be (re)allocated.
3008  */
3009     void
3010 win_new_shellsize()
3011 {
3012     static int	old_Rows = 0;
3013     static int	old_Columns = 0;
3014 
3015     if (old_Rows != Rows || old_Columns != Columns)
3016 	ui_new_shellsize();
3017     if (old_Rows != Rows)
3018     {
3019 	/* if 'window' uses the whole screen, keep it using that */
3020 	if (p_window == old_Rows - 1 || old_Rows == 0)
3021 	    p_window = Rows - 1;
3022 	old_Rows = Rows;
3023 	shell_new_rows();	/* update window sizes */
3024     }
3025     if (old_Columns != Columns)
3026     {
3027 	old_Columns = Columns;
3028 #ifdef FEAT_VERTSPLIT
3029 	shell_new_columns();	/* update window sizes */
3030 #endif
3031     }
3032 }
3033 
3034 /*
3035  * Call this function when the Vim shell has been resized in any way.
3036  * Will obtain the current size and redraw (also when size didn't change).
3037  */
3038     void
3039 shell_resized()
3040 {
3041     set_shellsize(0, 0, FALSE);
3042 }
3043 
3044 /*
3045  * Check if the shell size changed.  Handle a resize.
3046  * When the size didn't change, nothing happens.
3047  */
3048     void
3049 shell_resized_check()
3050 {
3051     int		old_Rows = Rows;
3052     int		old_Columns = Columns;
3053 
3054     if (!exiting
3055 #ifdef FEAT_GUI
3056 	    /* Do not get the size when executing a shell command during
3057 	     * startup. */
3058 	    && !gui.starting
3059 #endif
3060 	    )
3061     {
3062 	(void)ui_get_shellsize();
3063 	check_shellsize();
3064 	if (old_Rows != Rows || old_Columns != Columns)
3065 	    shell_resized();
3066     }
3067 }
3068 
3069 /*
3070  * Set size of the Vim shell.
3071  * If 'mustset' is TRUE, we must set Rows and Columns, do not get the real
3072  * window size (this is used for the :win command).
3073  * If 'mustset' is FALSE, we may try to get the real window size and if
3074  * it fails use 'width' and 'height'.
3075  */
3076     void
3077 set_shellsize(width, height, mustset)
3078     int	    width, height;
3079     int	    mustset;
3080 {
3081     static int		busy = FALSE;
3082 
3083     /*
3084      * Avoid recursiveness, can happen when setting the window size causes
3085      * another window-changed signal.
3086      */
3087     if (busy)
3088 	return;
3089 
3090     if (width < 0 || height < 0)    /* just checking... */
3091 	return;
3092 
3093     if (State == HITRETURN || State == SETWSIZE)
3094     {
3095 	/* postpone the resizing */
3096 	State = SETWSIZE;
3097 	return;
3098     }
3099 
3100     /* curwin->w_buffer can be NULL when we are closing a window and the
3101      * buffer has already been closed and removing a scrollbar causes a resize
3102      * event. Don't resize then, it will happen after entering another buffer.
3103      */
3104     if (curwin->w_buffer == NULL)
3105 	return;
3106 
3107     ++busy;
3108 
3109 #ifdef AMIGA
3110     out_flush();	    /* must do this before mch_get_shellsize() for
3111 			       some obscure reason */
3112 #endif
3113 
3114     if (mustset || (ui_get_shellsize() == FAIL && height != 0))
3115     {
3116 	Rows = height;
3117 	Columns = width;
3118 	check_shellsize();
3119 	ui_set_shellsize(mustset);
3120     }
3121     else
3122 	check_shellsize();
3123 
3124     /* The window layout used to be adjusted here, but it now happens in
3125      * screenalloc() (also invoked from screenclear()).  That is because the
3126      * "busy" check above may skip this, but not screenalloc(). */
3127 
3128     if (State != ASKMORE && State != EXTERNCMD && State != CONFIRM)
3129 	screenclear();
3130     else
3131 	screen_start();	    /* don't know where cursor is now */
3132 
3133     if (starting != NO_SCREEN)
3134     {
3135 #ifdef FEAT_TITLE
3136 	maketitle();
3137 #endif
3138 	changed_line_abv_curs();
3139 	invalidate_botline();
3140 
3141 	/*
3142 	 * We only redraw when it's needed:
3143 	 * - While at the more prompt or executing an external command, don't
3144 	 *   redraw, but position the cursor.
3145 	 * - While editing the command line, only redraw that.
3146 	 * - in Ex mode, don't redraw anything.
3147 	 * - Otherwise, redraw right now, and position the cursor.
3148 	 * Always need to call update_screen() or screenalloc(), to make
3149 	 * sure Rows/Columns and the size of ScreenLines[] is correct!
3150 	 */
3151 	if (State == ASKMORE || State == EXTERNCMD || State == CONFIRM
3152 							     || exmode_active)
3153 	{
3154 	    screenalloc(FALSE);
3155 	    repeat_message();
3156 	}
3157 	else
3158 	{
3159 #ifdef FEAT_SCROLLBIND
3160 	    if (curwin->w_p_scb)
3161 		do_check_scrollbind(TRUE);
3162 #endif
3163 	    if (State & CMDLINE)
3164 	    {
3165 		update_screen(NOT_VALID);
3166 		redrawcmdline();
3167 	    }
3168 	    else
3169 	    {
3170 		update_topline();
3171 #if defined(FEAT_INS_EXPAND)
3172 		if (pum_visible())
3173 		{
3174 		    redraw_later(NOT_VALID);
3175 		    ins_compl_show_pum(); /* This includes the redraw. */
3176 		}
3177 		else
3178 #endif
3179 		    update_screen(NOT_VALID);
3180 		if (redrawing())
3181 		    setcursor();
3182 	    }
3183 	}
3184 	cursor_on();	    /* redrawing may have switched it off */
3185     }
3186     out_flush();
3187     --busy;
3188 }
3189 
3190 /*
3191  * Set the terminal to TMODE_RAW (for Normal mode) or TMODE_COOK (for external
3192  * commands and Ex mode).
3193  */
3194     void
3195 settmode(tmode)
3196     int	 tmode;
3197 {
3198 #ifdef FEAT_GUI
3199     /* don't set the term where gvim was started to any mode */
3200     if (gui.in_use)
3201 	return;
3202 #endif
3203 
3204     if (full_screen)
3205     {
3206 	/*
3207 	 * When returning after calling a shell we want to really set the
3208 	 * terminal to raw mode, even though we think it already is, because
3209 	 * the shell program may have reset the terminal mode.
3210 	 * When we think the terminal is normal, don't try to set it to
3211 	 * normal again, because that causes problems (logout!) on some
3212 	 * machines.
3213 	 */
3214 	if (tmode != TMODE_COOK || cur_tmode != TMODE_COOK)
3215 	{
3216 #ifdef FEAT_TERMRESPONSE
3217 # ifdef FEAT_GUI
3218 	    if (!gui.in_use && !gui.starting)
3219 # endif
3220 	    {
3221 		/* May need to check for T_CRV response and termcodes, it
3222 		 * doesn't work in Cooked mode, an external program may get
3223 		 * them. */
3224 		if (tmode != TMODE_RAW && (crv_status == CRV_SENT
3225 					 || u7_status == U7_SENT
3226 					 || rbg_status == RBG_SENT))
3227 		    (void)vpeekc_nomap();
3228 		check_for_codes_from_term();
3229 	    }
3230 #endif
3231 #ifdef FEAT_MOUSE_TTY
3232 	    if (tmode != TMODE_RAW)
3233 		mch_setmouse(FALSE);		/* switch mouse off */
3234 #endif
3235 	    out_flush();
3236 	    mch_settmode(tmode);    /* machine specific function */
3237 	    cur_tmode = tmode;
3238 #ifdef FEAT_MOUSE
3239 	    if (tmode == TMODE_RAW)
3240 		setmouse();			/* may switch mouse on */
3241 #endif
3242 	    out_flush();
3243 	}
3244 #ifdef FEAT_TERMRESPONSE
3245 	may_req_termresponse();
3246 #endif
3247     }
3248 }
3249 
3250     void
3251 starttermcap()
3252 {
3253     if (full_screen && !termcap_active)
3254     {
3255 	out_str(T_TI);			/* start termcap mode */
3256 	out_str(T_KS);			/* start "keypad transmit" mode */
3257 	out_flush();
3258 	termcap_active = TRUE;
3259 	screen_start();			/* don't know where cursor is now */
3260 #ifdef FEAT_TERMRESPONSE
3261 # ifdef FEAT_GUI
3262 	if (!gui.in_use && !gui.starting)
3263 # endif
3264 	{
3265 	    may_req_termresponse();
3266 	    /* Immediately check for a response.  If t_Co changes, we don't
3267 	     * want to redraw with wrong colors first. */
3268 	    if (crv_status == CRV_SENT)
3269 		check_for_codes_from_term();
3270 	}
3271 #endif
3272     }
3273 }
3274 
3275     void
3276 stoptermcap()
3277 {
3278     screen_stop_highlight();
3279     reset_cterm_colors();
3280     if (termcap_active)
3281     {
3282 #ifdef FEAT_TERMRESPONSE
3283 # ifdef FEAT_GUI
3284 	if (!gui.in_use && !gui.starting)
3285 # endif
3286 	{
3287 	    /* May need to discard T_CRV, T_U7 or T_RBG response. */
3288 	    if (crv_status == CRV_SENT || u7_status == U7_SENT
3289 						     || rbg_status == RBG_SENT)
3290 	    {
3291 # ifdef UNIX
3292 		/* Give the terminal a chance to respond. */
3293 		mch_delay(100L, FALSE);
3294 # endif
3295 # ifdef TCIFLUSH
3296 		/* Discard data received but not read. */
3297 		if (exiting)
3298 		    tcflush(fileno(stdin), TCIFLUSH);
3299 # endif
3300 	    }
3301 	    /* Check for termcodes first, otherwise an external program may
3302 	     * get them. */
3303 	    check_for_codes_from_term();
3304 	}
3305 #endif
3306 	out_str(T_KE);			/* stop "keypad transmit" mode */
3307 	out_flush();
3308 	termcap_active = FALSE;
3309 	cursor_on();			/* just in case it is still off */
3310 	out_str(T_TE);			/* stop termcap mode */
3311 	screen_start();			/* don't know where cursor is now */
3312 	out_flush();
3313     }
3314 }
3315 
3316 #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
3317 /*
3318  * Request version string (for xterm) when needed.
3319  * Only do this after switching to raw mode, otherwise the result will be
3320  * echoed.
3321  * Only do this after startup has finished, to avoid that the response comes
3322  * while executing "-c !cmd" or even after "-c quit".
3323  * Only do this after termcap mode has been started, otherwise the codes for
3324  * the cursor keys may be wrong.
3325  * Only do this when 'esckeys' is on, otherwise the response causes trouble in
3326  * Insert mode.
3327  * On Unix only do it when both output and input are a tty (avoid writing
3328  * request to terminal while reading from a file).
3329  * The result is caught in check_termcode().
3330  */
3331     void
3332 may_req_termresponse()
3333 {
3334     if (crv_status == CRV_GET
3335 	    && cur_tmode == TMODE_RAW
3336 	    && starting == 0
3337 	    && termcap_active
3338 	    && p_ek
3339 # ifdef UNIX
3340 	    && isatty(1)
3341 	    && isatty(read_cmd_fd)
3342 # endif
3343 	    && *T_CRV != NUL)
3344     {
3345 	LOG_TR("Sending CRV");
3346 	out_str(T_CRV);
3347 	crv_status = CRV_SENT;
3348 	/* check for the characters now, otherwise they might be eaten by
3349 	 * get_keystroke() */
3350 	out_flush();
3351 	(void)vpeekc_nomap();
3352     }
3353 }
3354 
3355 # if defined(FEAT_MBYTE) || defined(PROTO)
3356 /*
3357  * Check how the terminal treats ambiguous character width (UAX #11).
3358  * First, we move the cursor to (1, 0) and print a test ambiguous character
3359  * \u25bd (WHITE DOWN-POINTING TRIANGLE) and query current cursor position.
3360  * If the terminal treats \u25bd as single width, the position is (1, 1),
3361  * or if it is treated as double width, that will be (1, 2).
3362  * This function has the side effect that changes cursor position, so
3363  * it must be called immediately after entering termcap mode.
3364  */
3365     void
3366 may_req_ambiguous_char_width()
3367 {
3368     if (u7_status == U7_GET
3369 	    && cur_tmode == TMODE_RAW
3370 	    && termcap_active
3371 	    && p_ek
3372 #  ifdef UNIX
3373 	    && isatty(1)
3374 	    && isatty(read_cmd_fd)
3375 #  endif
3376 	    && *T_U7 != NUL
3377 	    && !option_was_set((char_u *)"ambiwidth"))
3378     {
3379 	 char_u	buf[16];
3380 
3381 	 LOG_TR("Sending U7 request");
3382 	 /* Do this in the second row.  In the first row the returned sequence
3383 	  * may be CSI 1;2R, which is the same as <S-F3>. */
3384 	 term_windgoto(1, 0);
3385 	 buf[mb_char2bytes(0x25bd, buf)] = 0;
3386 	 out_str(buf);
3387 	 out_str(T_U7);
3388 	 u7_status = U7_SENT;
3389 	 out_flush();
3390 	 term_windgoto(1, 0);
3391 	 out_str((char_u *)"  ");
3392 	 term_windgoto(0, 0);
3393 	 /* check for the characters now, otherwise they might be eaten by
3394 	  * get_keystroke() */
3395 	 out_flush();
3396 	 (void)vpeekc_nomap();
3397     }
3398 }
3399 # endif
3400 
3401 #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
3402 /*
3403  * Similar to requesting the version string: Request the terminal background
3404  * color when it is the right moment.
3405  */
3406     void
3407 may_req_bg_color()
3408 {
3409     if (rbg_status == RBG_GET
3410 	    && cur_tmode == TMODE_RAW
3411 	    && termcap_active
3412 	    && p_ek
3413 #  ifdef UNIX
3414 	    && isatty(1)
3415 	    && isatty(read_cmd_fd)
3416 #  endif
3417 	    && *T_RBG != NUL
3418 	    && !option_was_set((char_u *)"bg"))
3419     {
3420 	LOG_TR("Sending BG request");
3421 	out_str(T_RBG);
3422 	rbg_status = RBG_SENT;
3423 	/* check for the characters now, otherwise they might be eaten by
3424 	 * get_keystroke() */
3425 	out_flush();
3426 	(void)vpeekc_nomap();
3427     }
3428 }
3429 # endif
3430 
3431 # ifdef DEBUG_TERMRESPONSE
3432     static void
3433 log_tr(char *msg)
3434 {
3435     static FILE *fd_tr = NULL;
3436     static proftime_T start;
3437     proftime_T now;
3438 
3439     if (fd_tr == NULL)
3440     {
3441 	fd_tr = fopen("termresponse.log", "w");
3442 	profile_start(&start);
3443     }
3444     now = start;
3445     profile_end(&now);
3446     fprintf(fd_tr, "%s: %s %s\n",
3447 	    profile_msg(&now),
3448 	    must_redraw == NOT_VALID ? "NV"
3449 					 : must_redraw == CLEAR ? "CL" : "  ",
3450 	    msg);
3451 }
3452 # endif
3453 #endif
3454 
3455 /*
3456  * Return TRUE when saving and restoring the screen.
3457  */
3458     int
3459 swapping_screen()
3460 {
3461     return (full_screen && *T_TI != NUL);
3462 }
3463 
3464 #ifdef FEAT_MOUSE
3465 /*
3466  * setmouse() - switch mouse on/off depending on current mode and 'mouse'
3467  */
3468     void
3469 setmouse()
3470 {
3471 # ifdef FEAT_MOUSE_TTY
3472     int	    checkfor;
3473 # endif
3474 
3475 # ifdef FEAT_MOUSESHAPE
3476     update_mouseshape(-1);
3477 # endif
3478 
3479 # ifdef FEAT_MOUSE_TTY /* Should be outside proc, but may break MOUSESHAPE */
3480 #  ifdef FEAT_GUI
3481     /* In the GUI the mouse is always enabled. */
3482     if (gui.in_use)
3483 	return;
3484 #  endif
3485     /* be quick when mouse is off */
3486     if (*p_mouse == NUL || has_mouse_termcode == 0)
3487 	return;
3488 
3489     /* don't switch mouse on when not in raw mode (Ex mode) */
3490     if (cur_tmode != TMODE_RAW)
3491     {
3492 	mch_setmouse(FALSE);
3493 	return;
3494     }
3495 
3496     if (VIsual_active)
3497 	checkfor = MOUSE_VISUAL;
3498     else if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
3499 	checkfor = MOUSE_RETURN;
3500     else if (State & INSERT)
3501 	checkfor = MOUSE_INSERT;
3502     else if (State & CMDLINE)
3503 	checkfor = MOUSE_COMMAND;
3504     else if (State == CONFIRM || State == EXTERNCMD)
3505 	checkfor = ' '; /* don't use mouse for ":confirm" or ":!cmd" */
3506     else
3507 	checkfor = MOUSE_NORMAL;    /* assume normal mode */
3508 
3509     if (mouse_has(checkfor))
3510 	mch_setmouse(TRUE);
3511     else
3512 	mch_setmouse(FALSE);
3513 # endif
3514 }
3515 
3516 /*
3517  * Return TRUE if
3518  * - "c" is in 'mouse', or
3519  * - 'a' is in 'mouse' and "c" is in MOUSE_A, or
3520  * - the current buffer is a help file and 'h' is in 'mouse' and we are in a
3521  *   normal editing mode (not at hit-return message).
3522  */
3523     int
3524 mouse_has(c)
3525     int	    c;
3526 {
3527     char_u	*p;
3528 
3529     for (p = p_mouse; *p; ++p)
3530 	switch (*p)
3531 	{
3532 	    case 'a': if (vim_strchr((char_u *)MOUSE_A, c) != NULL)
3533 			  return TRUE;
3534 		      break;
3535 	    case MOUSE_HELP: if (c != MOUSE_RETURN && curbuf->b_help)
3536 				 return TRUE;
3537 			     break;
3538 	    default: if (c == *p) return TRUE; break;
3539 	}
3540     return FALSE;
3541 }
3542 
3543 /*
3544  * Return TRUE when 'mousemodel' is set to "popup" or "popup_setpos".
3545  */
3546     int
3547 mouse_model_popup()
3548 {
3549     return (p_mousem[0] == 'p');
3550 }
3551 #endif
3552 
3553 /*
3554  * By outputting the 'cursor very visible' termcap code, for some windowed
3555  * terminals this makes the screen scrolled to the correct position.
3556  * Used when starting Vim or returning from a shell.
3557  */
3558     void
3559 scroll_start()
3560 {
3561     if (*T_VS != NUL)
3562     {
3563 	out_str(T_VS);
3564 	out_str(T_VE);
3565 	screen_start();			/* don't know where cursor is now */
3566     }
3567 }
3568 
3569 static int cursor_is_off = FALSE;
3570 
3571 /*
3572  * Enable the cursor.
3573  */
3574     void
3575 cursor_on()
3576 {
3577     if (cursor_is_off)
3578     {
3579 	out_str(T_VE);
3580 	cursor_is_off = FALSE;
3581     }
3582 }
3583 
3584 /*
3585  * Disable the cursor.
3586  */
3587     void
3588 cursor_off()
3589 {
3590     if (full_screen)
3591     {
3592 	if (!cursor_is_off)
3593 	    out_str(T_VI);	    /* disable cursor */
3594 	cursor_is_off = TRUE;
3595     }
3596 }
3597 
3598 #if defined(CURSOR_SHAPE) || defined(PROTO)
3599 /*
3600  * Set cursor shape to match Insert or Replace mode.
3601  */
3602     void
3603 term_cursor_shape()
3604 {
3605     static int showing_mode = NORMAL;
3606     char_u *p;
3607 
3608     /* Only do something when redrawing the screen and we can restore the
3609      * mode. */
3610     if (!full_screen || *T_CEI == NUL)
3611 	return;
3612 
3613     if ((State & REPLACE) == REPLACE)
3614     {
3615 	if (showing_mode != REPLACE)
3616 	{
3617 	    if (*T_CSR != NUL)
3618 		p = T_CSR;	/* Replace mode cursor */
3619 	    else
3620 		p = T_CSI;	/* fall back to Insert mode cursor */
3621 	    if (*p != NUL)
3622 	    {
3623 		out_str(p);
3624 		showing_mode = REPLACE;
3625 	    }
3626 	}
3627     }
3628     else if (State & INSERT)
3629     {
3630 	if (showing_mode != INSERT && *T_CSI != NUL)
3631 	{
3632 	    out_str(T_CSI);	    /* Insert mode cursor */
3633 	    showing_mode = INSERT;
3634 	}
3635     }
3636     else if (showing_mode != NORMAL)
3637     {
3638 	out_str(T_CEI);		    /* non-Insert mode cursor */
3639 	showing_mode = NORMAL;
3640     }
3641 }
3642 #endif
3643 
3644 /*
3645  * Set scrolling region for window 'wp'.
3646  * The region starts 'off' lines from the start of the window.
3647  * Also set the vertical scroll region for a vertically split window.  Always
3648  * the full width of the window, excluding the vertical separator.
3649  */
3650     void
3651 scroll_region_set(wp, off)
3652     win_T	*wp;
3653     int		off;
3654 {
3655     OUT_STR(tgoto((char *)T_CS, W_WINROW(wp) + wp->w_height - 1,
3656 							 W_WINROW(wp) + off));
3657 #ifdef FEAT_VERTSPLIT
3658     if (*T_CSV != NUL && wp->w_width != Columns)
3659 	OUT_STR(tgoto((char *)T_CSV, W_WINCOL(wp) + wp->w_width - 1,
3660 							       W_WINCOL(wp)));
3661 #endif
3662     screen_start();		    /* don't know where cursor is now */
3663 }
3664 
3665 /*
3666  * Reset scrolling region to the whole screen.
3667  */
3668     void
3669 scroll_region_reset()
3670 {
3671     OUT_STR(tgoto((char *)T_CS, (int)Rows - 1, 0));
3672 #ifdef FEAT_VERTSPLIT
3673     if (*T_CSV != NUL)
3674 	OUT_STR(tgoto((char *)T_CSV, (int)Columns - 1, 0));
3675 #endif
3676     screen_start();		    /* don't know where cursor is now */
3677 }
3678 
3679 
3680 /*
3681  * List of terminal codes that are currently recognized.
3682  */
3683 
3684 static struct termcode
3685 {
3686     char_u  name[2];	    /* termcap name of entry */
3687     char_u  *code;	    /* terminal code (in allocated memory) */
3688     int	    len;	    /* STRLEN(code) */
3689     int	    modlen;	    /* length of part before ";*~". */
3690 } *termcodes = NULL;
3691 
3692 static int  tc_max_len = 0; /* number of entries that termcodes[] can hold */
3693 static int  tc_len = 0;	    /* current number of entries in termcodes[] */
3694 
3695 static int termcode_star __ARGS((char_u *code, int len));
3696 
3697     void
3698 clear_termcodes()
3699 {
3700     while (tc_len > 0)
3701 	vim_free(termcodes[--tc_len].code);
3702     vim_free(termcodes);
3703     termcodes = NULL;
3704     tc_max_len = 0;
3705 
3706 #ifdef HAVE_TGETENT
3707     BC = (char *)empty_option;
3708     UP = (char *)empty_option;
3709     PC = NUL;			/* set pad character to NUL */
3710     ospeed = 0;
3711 #endif
3712 
3713     need_gather = TRUE;		/* need to fill termleader[] */
3714 }
3715 
3716 #define ATC_FROM_TERM 55
3717 
3718 /*
3719  * Add a new entry to the list of terminal codes.
3720  * The list is kept alphabetical for ":set termcap"
3721  * "flags" is TRUE when replacing 7-bit by 8-bit controls is desired.
3722  * "flags" can also be ATC_FROM_TERM for got_code_from_term().
3723  */
3724     void
3725 add_termcode(name, string, flags)
3726     char_u	*name;
3727     char_u	*string;
3728     int		flags;
3729 {
3730     struct termcode *new_tc;
3731     int		    i, j;
3732     char_u	    *s;
3733     int		    len;
3734 
3735     if (string == NULL || *string == NUL)
3736     {
3737 	del_termcode(name);
3738 	return;
3739     }
3740 
3741 #if defined(WIN3264) && !defined(FEAT_GUI)
3742     s = vim_strnsave(string, (int)STRLEN(string) + 1);
3743 #else
3744     s = vim_strsave(string);
3745 #endif
3746     if (s == NULL)
3747 	return;
3748 
3749     /* Change leading <Esc>[ to CSI, change <Esc>O to <M-O>. */
3750     if (flags != 0 && flags != ATC_FROM_TERM && term_7to8bit(string) != 0)
3751     {
3752 	STRMOVE(s, s + 1);
3753 	s[0] = term_7to8bit(string);
3754     }
3755 
3756 #if defined(WIN3264) && !defined(FEAT_GUI)
3757     if (s[0] == K_NUL)
3758     {
3759 	STRMOVE(s + 1, s);
3760 	s[1] = 3;
3761     }
3762 #endif
3763 
3764     len = (int)STRLEN(s);
3765 
3766     need_gather = TRUE;		/* need to fill termleader[] */
3767 
3768     /*
3769      * need to make space for more entries
3770      */
3771     if (tc_len == tc_max_len)
3772     {
3773 	tc_max_len += 20;
3774 	new_tc = (struct termcode *)alloc(
3775 			    (unsigned)(tc_max_len * sizeof(struct termcode)));
3776 	if (new_tc == NULL)
3777 	{
3778 	    tc_max_len -= 20;
3779 	    return;
3780 	}
3781 	for (i = 0; i < tc_len; ++i)
3782 	    new_tc[i] = termcodes[i];
3783 	vim_free(termcodes);
3784 	termcodes = new_tc;
3785     }
3786 
3787     /*
3788      * Look for existing entry with the same name, it is replaced.
3789      * Look for an existing entry that is alphabetical higher, the new entry
3790      * is inserted in front of it.
3791      */
3792     for (i = 0; i < tc_len; ++i)
3793     {
3794 	if (termcodes[i].name[0] < name[0])
3795 	    continue;
3796 	if (termcodes[i].name[0] == name[0])
3797 	{
3798 	    if (termcodes[i].name[1] < name[1])
3799 		continue;
3800 	    /*
3801 	     * Exact match: May replace old code.
3802 	     */
3803 	    if (termcodes[i].name[1] == name[1])
3804 	    {
3805 		if (flags == ATC_FROM_TERM && (j = termcode_star(
3806 				    termcodes[i].code, termcodes[i].len)) > 0)
3807 		{
3808 		    /* Don't replace ESC[123;*X or ESC O*X with another when
3809 		     * invoked from got_code_from_term(). */
3810 		    if (len == termcodes[i].len - j
3811 			    && STRNCMP(s, termcodes[i].code, len - 1) == 0
3812 			    && s[len - 1]
3813 				   == termcodes[i].code[termcodes[i].len - 1])
3814 		    {
3815 			/* They are equal but for the ";*": don't add it. */
3816 			vim_free(s);
3817 			return;
3818 		    }
3819 		}
3820 		else
3821 		{
3822 		    /* Replace old code. */
3823 		    vim_free(termcodes[i].code);
3824 		    --tc_len;
3825 		    break;
3826 		}
3827 	    }
3828 	}
3829 	/*
3830 	 * Found alphabetical larger entry, move rest to insert new entry
3831 	 */
3832 	for (j = tc_len; j > i; --j)
3833 	    termcodes[j] = termcodes[j - 1];
3834 	break;
3835     }
3836 
3837     termcodes[i].name[0] = name[0];
3838     termcodes[i].name[1] = name[1];
3839     termcodes[i].code = s;
3840     termcodes[i].len = len;
3841 
3842     /* For xterm we recognize special codes like "ESC[42;*X" and "ESC O*X" that
3843      * accept modifiers. */
3844     termcodes[i].modlen = 0;
3845     j = termcode_star(s, len);
3846     if (j > 0)
3847 	termcodes[i].modlen = len - 1 - j;
3848     ++tc_len;
3849 }
3850 
3851 /*
3852  * Check termcode "code[len]" for ending in ;*X, <Esc>O*X or <M-O>*X.
3853  * The "X" can be any character.
3854  * Return 0 if not found, 2 for ;*X and 1 for O*X and <M-O>*X.
3855  */
3856     static int
3857 termcode_star(code, len)
3858     char_u	*code;
3859     int		len;
3860 {
3861     /* Shortest is <M-O>*X.  With ; shortest is <CSI>1;*X */
3862     if (len >= 3 && code[len - 2] == '*')
3863     {
3864 	if (len >= 5 && code[len - 3] == ';')
3865 	    return 2;
3866 	if ((len >= 4 && code[len - 3] == 'O') || code[len - 3] == 'O' + 128)
3867 	    return 1;
3868     }
3869     return 0;
3870 }
3871 
3872     char_u  *
3873 find_termcode(name)
3874     char_u  *name;
3875 {
3876     int	    i;
3877 
3878     for (i = 0; i < tc_len; ++i)
3879 	if (termcodes[i].name[0] == name[0] && termcodes[i].name[1] == name[1])
3880 	    return termcodes[i].code;
3881     return NULL;
3882 }
3883 
3884 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3885     char_u *
3886 get_termcode(i)
3887     int	    i;
3888 {
3889     if (i >= tc_len)
3890 	return NULL;
3891     return &termcodes[i].name[0];
3892 }
3893 #endif
3894 
3895     void
3896 del_termcode(name)
3897     char_u  *name;
3898 {
3899     int	    i;
3900 
3901     if (termcodes == NULL)	/* nothing there yet */
3902 	return;
3903 
3904     need_gather = TRUE;		/* need to fill termleader[] */
3905 
3906     for (i = 0; i < tc_len; ++i)
3907 	if (termcodes[i].name[0] == name[0] && termcodes[i].name[1] == name[1])
3908 	{
3909 	    del_termcode_idx(i);
3910 	    return;
3911 	}
3912     /* not found. Give error message? */
3913 }
3914 
3915     static void
3916 del_termcode_idx(idx)
3917     int		idx;
3918 {
3919     int		i;
3920 
3921     vim_free(termcodes[idx].code);
3922     --tc_len;
3923     for (i = idx; i < tc_len; ++i)
3924 	termcodes[i] = termcodes[i + 1];
3925 }
3926 
3927 #ifdef FEAT_TERMRESPONSE
3928 /*
3929  * Called when detected that the terminal sends 8-bit codes.
3930  * Convert all 7-bit codes to their 8-bit equivalent.
3931  */
3932     static void
3933 switch_to_8bit()
3934 {
3935     int		i;
3936     int		c;
3937 
3938     /* Only need to do something when not already using 8-bit codes. */
3939     if (!term_is_8bit(T_NAME))
3940     {
3941 	for (i = 0; i < tc_len; ++i)
3942 	{
3943 	    c = term_7to8bit(termcodes[i].code);
3944 	    if (c != 0)
3945 	    {
3946 		STRMOVE(termcodes[i].code + 1, termcodes[i].code + 2);
3947 		termcodes[i].code[0] = c;
3948 	    }
3949 	}
3950 	need_gather = TRUE;		/* need to fill termleader[] */
3951     }
3952     detected_8bit = TRUE;
3953     LOG_TR("Switching to 8 bit");
3954 }
3955 #endif
3956 
3957 #ifdef CHECK_DOUBLE_CLICK
3958 static linenr_T orig_topline = 0;
3959 # ifdef FEAT_DIFF
3960 static int orig_topfill = 0;
3961 # endif
3962 #endif
3963 #if (defined(FEAT_WINDOWS) && defined(CHECK_DOUBLE_CLICK)) || defined(PROTO)
3964 /*
3965  * Checking for double clicks ourselves.
3966  * "orig_topline" is used to avoid detecting a double-click when the window
3967  * contents scrolled (e.g., when 'scrolloff' is non-zero).
3968  */
3969 /*
3970  * Set orig_topline.  Used when jumping to another window, so that a double
3971  * click still works.
3972  */
3973     void
3974 set_mouse_topline(wp)
3975     win_T	*wp;
3976 {
3977     orig_topline = wp->w_topline;
3978 # ifdef FEAT_DIFF
3979     orig_topfill = wp->w_topfill;
3980 # endif
3981 }
3982 #endif
3983 
3984 /*
3985  * Check if typebuf.tb_buf[] contains a terminal key code.
3986  * Check from typebuf.tb_buf[typebuf.tb_off] to typebuf.tb_buf[typebuf.tb_off
3987  * + max_offset].
3988  * Return 0 for no match, -1 for partial match, > 0 for full match.
3989  * Return KEYLEN_REMOVED when a key code was deleted.
3990  * With a match, the match is removed, the replacement code is inserted in
3991  * typebuf.tb_buf[] and the number of characters in typebuf.tb_buf[] is
3992  * returned.
3993  * When "buf" is not NULL, buf[bufsize] is used instead of typebuf.tb_buf[].
3994  * "buflen" is then the length of the string in buf[] and is updated for
3995  * inserts and deletes.
3996  */
3997     int
3998 check_termcode(max_offset, buf, bufsize, buflen)
3999     int		max_offset;
4000     char_u	*buf;
4001     int		bufsize;
4002     int		*buflen;
4003 {
4004     char_u	*tp;
4005     char_u	*p;
4006     int		slen = 0;	/* init for GCC */
4007     int		modslen;
4008     int		len;
4009     int		retval = 0;
4010     int		offset;
4011     char_u	key_name[2];
4012     int		modifiers;
4013     int		key;
4014     int		new_slen;
4015     int		extra;
4016     char_u	string[MAX_KEY_CODE_LEN + 1];
4017     int		i, j;
4018     int		idx = 0;
4019 #ifdef FEAT_MOUSE
4020 # if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \
4021     || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)
4022     char_u	bytes[6];
4023     int		num_bytes;
4024 # endif
4025     int		mouse_code = 0;	    /* init for GCC */
4026     int		is_click, is_drag;
4027     int		wheel_code = 0;
4028     int		current_button;
4029     static int	held_button = MOUSE_RELEASE;
4030     static int	orig_num_clicks = 1;
4031     static int	orig_mouse_code = 0x0;
4032 # ifdef CHECK_DOUBLE_CLICK
4033     static int	orig_mouse_col = 0;
4034     static int	orig_mouse_row = 0;
4035     static struct timeval  orig_mouse_time = {0, 0};
4036 					/* time of previous mouse click */
4037     struct timeval  mouse_time;		/* time of current mouse click */
4038     long	timediff;		/* elapsed time in msec */
4039 # endif
4040 #endif
4041     int		cpo_koffset;
4042 #ifdef FEAT_MOUSE_GPM
4043     extern int	gpm_flag; /* gpm library variable */
4044 #endif
4045 
4046     cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);
4047 
4048     /*
4049      * Speed up the checks for terminal codes by gathering all first bytes
4050      * used in termleader[].  Often this is just a single <Esc>.
4051      */
4052     if (need_gather)
4053 	gather_termleader();
4054 
4055     /*
4056      * Check at several positions in typebuf.tb_buf[], to catch something like
4057      * "x<Up>" that can be mapped. Stop at max_offset, because characters
4058      * after that cannot be used for mapping, and with @r commands
4059      * typebuf.tb_buf[] can become very long.
4060      * This is used often, KEEP IT FAST!
4061      */
4062     for (offset = 0; offset < max_offset; ++offset)
4063     {
4064 	if (buf == NULL)
4065 	{
4066 	    if (offset >= typebuf.tb_len)
4067 		break;
4068 	    tp = typebuf.tb_buf + typebuf.tb_off + offset;
4069 	    len = typebuf.tb_len - offset;	/* length of the input */
4070 	}
4071 	else
4072 	{
4073 	    if (offset >= *buflen)
4074 		break;
4075 	    tp = buf + offset;
4076 	    len = *buflen - offset;
4077 	}
4078 
4079 	/*
4080 	 * Don't check characters after K_SPECIAL, those are already
4081 	 * translated terminal chars (avoid translating ~@^Hx).
4082 	 */
4083 	if (*tp == K_SPECIAL)
4084 	{
4085 	    offset += 2;	/* there are always 2 extra characters */
4086 	    continue;
4087 	}
4088 
4089 	/*
4090 	 * Skip this position if the character does not appear as the first
4091 	 * character in term_strings. This speeds up a lot, since most
4092 	 * termcodes start with the same character (ESC or CSI).
4093 	 */
4094 	i = *tp;
4095 	for (p = termleader; *p && *p != i; ++p)
4096 	    ;
4097 	if (*p == NUL)
4098 	    continue;
4099 
4100 	/*
4101 	 * Skip this position if p_ek is not set and tp[0] is an ESC and we
4102 	 * are in Insert mode.
4103 	 */
4104 	if (*tp == ESC && !p_ek && (State & INSERT))
4105 	    continue;
4106 
4107 	key_name[0] = NUL;	/* no key name found yet */
4108 	key_name[1] = NUL;	/* no key name found yet */
4109 	modifiers = 0;		/* no modifiers yet */
4110 
4111 #ifdef FEAT_GUI
4112 	if (gui.in_use)
4113 	{
4114 	    /*
4115 	     * GUI special key codes are all of the form [CSI xx].
4116 	     */
4117 	    if (*tp == CSI)	    /* Special key from GUI */
4118 	    {
4119 		if (len < 3)
4120 		    return -1;	    /* Shouldn't happen */
4121 		slen = 3;
4122 		key_name[0] = tp[1];
4123 		key_name[1] = tp[2];
4124 	    }
4125 	}
4126 	else
4127 #endif /* FEAT_GUI */
4128 	{
4129 	    for (idx = 0; idx < tc_len; ++idx)
4130 	    {
4131 		/*
4132 		 * Ignore the entry if we are not at the start of
4133 		 * typebuf.tb_buf[]
4134 		 * and there are not enough characters to make a match.
4135 		 * But only when the 'K' flag is in 'cpoptions'.
4136 		 */
4137 		slen = termcodes[idx].len;
4138 		if (cpo_koffset && offset && len < slen)
4139 		    continue;
4140 		if (STRNCMP(termcodes[idx].code, tp,
4141 				     (size_t)(slen > len ? len : slen)) == 0)
4142 		{
4143 		    if (len < slen)		/* got a partial sequence */
4144 			return -1;		/* need to get more chars */
4145 
4146 		    /*
4147 		     * When found a keypad key, check if there is another key
4148 		     * that matches and use that one.  This makes <Home> to be
4149 		     * found instead of <kHome> when they produce the same
4150 		     * key code.
4151 		     */
4152 		    if (termcodes[idx].name[0] == 'K'
4153 				       && VIM_ISDIGIT(termcodes[idx].name[1]))
4154 		    {
4155 			for (j = idx + 1; j < tc_len; ++j)
4156 			    if (termcodes[j].len == slen &&
4157 				    STRNCMP(termcodes[idx].code,
4158 					    termcodes[j].code, slen) == 0)
4159 			    {
4160 				idx = j;
4161 				break;
4162 			    }
4163 		    }
4164 
4165 		    key_name[0] = termcodes[idx].name[0];
4166 		    key_name[1] = termcodes[idx].name[1];
4167 		    break;
4168 		}
4169 
4170 		/*
4171 		 * Check for code with modifier, like xterm uses:
4172 		 * <Esc>[123;*X  (modslen == slen - 3)
4173 		 * Also <Esc>O*X and <M-O>*X (modslen == slen - 2).
4174 		 * When there is a modifier the * matches a number.
4175 		 * When there is no modifier the ;* or * is omitted.
4176 		 */
4177 		if (termcodes[idx].modlen > 0)
4178 		{
4179 		    modslen = termcodes[idx].modlen;
4180 		    if (cpo_koffset && offset && len < modslen)
4181 			continue;
4182 		    if (STRNCMP(termcodes[idx].code, tp,
4183 				(size_t)(modslen > len ? len : modslen)) == 0)
4184 		    {
4185 			int	    n;
4186 
4187 			if (len <= modslen)	/* got a partial sequence */
4188 			    return -1;		/* need to get more chars */
4189 
4190 			if (tp[modslen] == termcodes[idx].code[slen - 1])
4191 			    slen = modslen + 1;	/* no modifiers */
4192 			else if (tp[modslen] != ';' && modslen == slen - 3)
4193 			    continue;	/* no match */
4194 			else
4195 			{
4196 			    /* Skip over the digits, the final char must
4197 			     * follow. */
4198 			    for (j = slen - 2; j < len && isdigit(tp[j]); ++j)
4199 				;
4200 			    ++j;
4201 			    if (len < j)	/* got a partial sequence */
4202 				return -1;	/* need to get more chars */
4203 			    if (tp[j - 1] != termcodes[idx].code[slen - 1])
4204 				continue;	/* no match */
4205 
4206 			    /* Match!  Convert modifier bits. */
4207 			    n = atoi((char *)tp + slen - 2) - 1;
4208 			    if (n & 1)
4209 				modifiers |= MOD_MASK_SHIFT;
4210 			    if (n & 2)
4211 				modifiers |= MOD_MASK_ALT;
4212 			    if (n & 4)
4213 				modifiers |= MOD_MASK_CTRL;
4214 			    if (n & 8)
4215 				modifiers |= MOD_MASK_META;
4216 
4217 			    slen = j;
4218 			}
4219 			key_name[0] = termcodes[idx].name[0];
4220 			key_name[1] = termcodes[idx].name[1];
4221 			break;
4222 		    }
4223 		}
4224 	    }
4225 	}
4226 
4227 #ifdef FEAT_TERMRESPONSE
4228 	if (key_name[0] == NUL
4229 	    /* Mouse codes of DEC, pterm, and URXVT start with <ESC>[.  When
4230 	     * detecting the start of these mouse codes they might as well be
4231 	     * another key code or terminal response. */
4232 # ifdef FEAT_MOUSE_DEC
4233 	    || key_name[0] == KS_DEC_MOUSE
4234 # endif
4235 # ifdef FEAT_MOUSE_PTERM
4236 	    || key_name[0] == KS_PTERM_MOUSE
4237 # endif
4238 # ifdef FEAT_MOUSE_URXVT
4239 	    || key_name[0] == KS_URXVT_MOUSE
4240 # endif
4241 	   )
4242 	{
4243 	    /* Check for some responses from the terminal starting with
4244 	     * "<Esc>[" or CSI:
4245 	     *
4246 	     * - Xterm version string: <Esc>[>{x};{vers};{y}c
4247 	     *   Also eat other possible responses to t_RV, rxvt returns
4248 	     *   "<Esc>[?1;2c". Also accept CSI instead of <Esc>[.
4249 	     *   mrxvt has been reported to have "+" in the version. Assume
4250 	     *   the escape sequence ends with a letter or one of "{|}~".
4251 	     *
4252 	     * - Cursor position report: <Esc>[{row};{col}R
4253 	     *   The final byte must be 'R'. It is used for checking the
4254 	     *   ambiguous-width character state.
4255 	     */
4256 	    char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;
4257 
4258 	    if ((*T_CRV != NUL || *T_U7 != NUL)
4259 			&& ((tp[0] == ESC && len >= 3 && tp[1] == '[')
4260 			    || (tp[0] == CSI && len >= 2))
4261 			&& (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))
4262 	    {
4263 #ifdef FEAT_MBYTE
4264 		int col;
4265 		int row_char = NUL;
4266 #endif
4267 		j = 0;
4268 		extra = 0;
4269 		for (i = 2 + (tp[0] != CSI); i < len
4270 				&& !(tp[i] >= '{' && tp[i] <= '~')
4271 				&& !ASCII_ISALPHA(tp[i]); ++i)
4272 		    if (tp[i] == ';' && ++j == 1)
4273 		    {
4274 			extra = i + 1;
4275 #ifdef FEAT_MBYTE
4276 			row_char = tp[i - 1];
4277 #endif
4278 		    }
4279 		if (i == len)
4280 		{
4281 		    LOG_TR("Not enough characters for CRV");
4282 		    return -1;
4283 		}
4284 #ifdef FEAT_MBYTE
4285 		if (extra > 0)
4286 		    col = atoi((char *)tp + extra);
4287 		else
4288 		    col = 0;
4289 
4290 		/* Eat it when it has 2 arguments and ends in 'R'. Also when
4291 		 * u7_status is not "sent", it may be from a previous Vim that
4292 		 * just exited.  But not for <S-F3>, it sends something
4293 		 * similar, check for row and column to make sense. */
4294 		if (j == 1 && tp[i] == 'R')
4295 		{
4296 		    if (row_char == '2' && col >= 2)
4297 		    {
4298 			char *aw = NULL;
4299 
4300 			LOG_TR("Received U7 status");
4301 			u7_status = U7_GOT;
4302 # ifdef FEAT_AUTOCMD
4303 			did_cursorhold = TRUE;
4304 # endif
4305 			if (col == 2)
4306 			    aw = "single";
4307 			else if (col == 3)
4308 			    aw = "double";
4309 			if (aw != NULL && STRCMP(aw, p_ambw) != 0)
4310 			{
4311 			    /* Setting the option causes a screen redraw. Do
4312 			     * that right away if possible, keeping any
4313 			     * messages. */
4314 			    set_option_value((char_u *)"ambw", 0L,
4315 					     (char_u *)aw, 0);
4316 # ifdef DEBUG_TERMRESPONSE
4317 			    {
4318 				char buf[100];
4319 				int  r = redraw_asap(CLEAR);
4320 
4321 				sprintf(buf,
4322 					"set 'ambiwidth', redraw_asap(): %d",
4323 					r);
4324 				log_tr(buf);
4325 			    }
4326 # else
4327 			    redraw_asap(CLEAR);
4328 # endif
4329 			}
4330 		    }
4331 		    key_name[0] = (int)KS_EXTRA;
4332 		    key_name[1] = (int)KE_IGNORE;
4333 		    slen = i + 1;
4334 		}
4335 		else
4336 #endif
4337 		/* eat it when at least one digit and ending in 'c' */
4338 		if (*T_CRV != NUL && i > 2 + (tp[0] != CSI) && tp[i] == 'c')
4339 		{
4340 		    LOG_TR("Received CRV");
4341 		    crv_status = CRV_GOT;
4342 # ifdef FEAT_AUTOCMD
4343 		    did_cursorhold = TRUE;
4344 # endif
4345 
4346 		    /* If this code starts with CSI, you can bet that the
4347 		     * terminal uses 8-bit codes. */
4348 		    if (tp[0] == CSI)
4349 			switch_to_8bit();
4350 
4351 		    /* rxvt sends its version number: "20703" is 2.7.3.
4352 		     * Ignore it for when the user has set 'term' to xterm,
4353 		     * even though it's an rxvt. */
4354 		    if (extra > 0)
4355 			extra = atoi((char *)tp + extra);
4356 		    if (extra > 20000)
4357 			extra = 0;
4358 
4359 		    if (tp[1 + (tp[0] != CSI)] == '>' && j == 2)
4360 		    {
4361 			/* Only set 'ttymouse' automatically if it was not set
4362 			 * by the user already. */
4363 			if (!option_was_set((char_u *)"ttym"))
4364 			{
4365 # ifdef TTYM_SGR
4366 			    if (extra >= 277)
4367 				set_option_value((char_u *)"ttym", 0L,
4368 							  (char_u *)"sgr", 0);
4369 			    else
4370 # endif
4371 			    /* if xterm version >= 95 use mouse dragging */
4372 			    if (extra >= 95)
4373 				set_option_value((char_u *)"ttym", 0L,
4374 						       (char_u *)"xterm2", 0);
4375 			}
4376 
4377 			/* if xterm version >= 141 try to get termcap codes */
4378 			if (extra >= 141)
4379 			{
4380 			    LOG_TR("Enable checking for XT codes");
4381 			    check_for_codes = TRUE;
4382 			    need_gather = TRUE;
4383 			    req_codes_from_term();
4384 			}
4385 		    }
4386 # ifdef FEAT_EVAL
4387 		    set_vim_var_string(VV_TERMRESPONSE, tp, i + 1);
4388 # endif
4389 # ifdef FEAT_AUTOCMD
4390 		    apply_autocmds(EVENT_TERMRESPONSE,
4391 						   NULL, NULL, FALSE, curbuf);
4392 # endif
4393 		    key_name[0] = (int)KS_EXTRA;
4394 		    key_name[1] = (int)KE_IGNORE;
4395 		    slen = i + 1;
4396 		}
4397 	    }
4398 
4399 	    /* Check for background color response from the terminal:
4400 	     *
4401 	     *       {lead}11;rgb:{rrrr}/{gggg}/{bbbb}{tail}
4402 	     *
4403 	     * {lead} can be <Esc>] or OSC
4404 	     * {tail} can be '\007', <Esc>\ or STERM.
4405 	     *
4406 	     * Consume any code that starts with "{lead}11;", it's also
4407 	     * possible that "rgba" is following.
4408 	     */
4409 	    else if (*T_RBG != NUL
4410 			&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')
4411 			    || tp[0] == OSC))
4412 	    {
4413 		j = 1 + (tp[0] == ESC);
4414 		if (len >= j + 3 && (argp[0] != '1'
4415 					 || argp[1] != '1' || argp[2] != ';'))
4416 		  i = 0; /* no match */
4417 		else
4418 		  for (i = j; i < len; ++i)
4419 		    if (tp[i] == '\007' || (tp[0] == OSC ? tp[i] == STERM
4420 			: (tp[i] == ESC && i + 1 < len && tp[i + 1] == '\\')))
4421 		    {
4422 			if (i - j >= 21 && STRNCMP(tp + j + 3, "rgb:", 4) == 0
4423 			    && tp[j + 11] == '/' && tp[j + 16] == '/'
4424 			    && !option_was_set((char_u *)"bg"))
4425 			{/* TODO: don't set option when already the right value */
4426 			    LOG_TR("Received RBG");
4427 			    rbg_status = RBG_GOT;
4428 			    set_option_value((char_u *)"bg", 0L, (char_u *)(
4429 				    (3 * '6' < tp[j+7] + tp[j+12] + tp[j+17])
4430 				    ? "light" : "dark"), 0);
4431 			    reset_option_was_set((char_u *)"bg");
4432 			    redraw_asap(CLEAR);
4433 			}
4434 
4435 			/* got finished code: consume it */
4436 			key_name[0] = (int)KS_EXTRA;
4437 			key_name[1] = (int)KE_IGNORE;
4438 			slen = i + 1 + (tp[i] == ESC);
4439 			break;
4440 		    }
4441 		if (i == len)
4442 		{
4443 		    LOG_TR("not enough characters for RB");
4444 		    return -1;
4445 		}
4446 	    }
4447 
4448 	    /* Check for key code response from xterm:
4449 	     *
4450 	     * {lead}{flag}+r<hex bytes><{tail}
4451 	     *
4452 	     * {lead} can be <Esc>P or DCS
4453 	     * {flag} can be '0' or '1'
4454 	     * {tail} can be Esc>\ or STERM
4455 	     *
4456 	     * Consume any code that starts with "{lead}.+r".
4457 	     */
4458 	    else if (check_for_codes
4459 		    && ((tp[0] == ESC && len >= 2 && tp[1] == 'P')
4460 			|| tp[0] == DCS))
4461 	    {
4462 		j = 1 + (tp[0] == ESC);
4463 		if (len >= j + 3 && (argp[1] != '+' || argp[2] != 'r'))
4464 		  i = 0; /* no match */
4465 		else
4466 		  for (i = j; i < len; ++i)
4467 		    if ((tp[i] == ESC && i + 1 < len && tp[i + 1] == '\\')
4468 			    || tp[i] == STERM)
4469 		    {
4470 			if (i - j >= 3)
4471 			    got_code_from_term(tp + j, i);
4472 			key_name[0] = (int)KS_EXTRA;
4473 			key_name[1] = (int)KE_IGNORE;
4474 			slen = i + 1 + (tp[i] == ESC);
4475 			break;
4476 		    }
4477 
4478 		if (i == len)
4479 		{
4480 		    /* These codes arrive many together, each code can be
4481 		     * truncated at any point. */
4482 		    LOG_TR("not enough characters for XT");
4483 		    return -1;
4484 		}
4485 	    }
4486 	}
4487 #endif
4488 
4489 	if (key_name[0] == NUL)
4490 	    continue;	    /* No match at this position, try next one */
4491 
4492 	/* We only get here when we have a complete termcode match */
4493 
4494 #ifdef FEAT_MOUSE
4495 # ifdef FEAT_GUI
4496 	/*
4497 	 * Only in the GUI: Fetch the pointer coordinates of the scroll event
4498 	 * so that we know which window to scroll later.
4499 	 */
4500 	if (gui.in_use
4501 		&& key_name[0] == (int)KS_EXTRA
4502 		&& (key_name[1] == (int)KE_X1MOUSE
4503 		    || key_name[1] == (int)KE_X2MOUSE
4504 		    || key_name[1] == (int)KE_MOUSELEFT
4505 		    || key_name[1] == (int)KE_MOUSERIGHT
4506 		    || key_name[1] == (int)KE_MOUSEDOWN
4507 		    || key_name[1] == (int)KE_MOUSEUP))
4508 	{
4509 	    num_bytes = get_bytes_from_buf(tp + slen, bytes, 4);
4510 	    if (num_bytes == -1)	/* not enough coordinates */
4511 		return -1;
4512 	    mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;
4513 	    mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;
4514 	    slen += num_bytes;
4515 	}
4516 	else
4517 # endif
4518 	/*
4519 	 * If it is a mouse click, get the coordinates.
4520 	 */
4521 	if (key_name[0] == KS_MOUSE
4522 # ifdef FEAT_MOUSE_JSB
4523 		|| key_name[0] == KS_JSBTERM_MOUSE
4524 # endif
4525 # ifdef FEAT_MOUSE_NET
4526 		|| key_name[0] == KS_NETTERM_MOUSE
4527 # endif
4528 # ifdef FEAT_MOUSE_DEC
4529 		|| key_name[0] == KS_DEC_MOUSE
4530 # endif
4531 # ifdef FEAT_MOUSE_PTERM
4532 		|| key_name[0] == KS_PTERM_MOUSE
4533 # endif
4534 # ifdef FEAT_MOUSE_URXVT
4535 		|| key_name[0] == KS_URXVT_MOUSE
4536 # endif
4537 # ifdef FEAT_MOUSE_SGR
4538 		|| key_name[0] == KS_SGR_MOUSE
4539 # endif
4540 		)
4541 	{
4542 	    is_click = is_drag = FALSE;
4543 
4544 # if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \
4545 	    || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)
4546 	    if (key_name[0] == (int)KS_MOUSE)
4547 	    {
4548 		/*
4549 		 * For xterm and MSDOS we get "<t_mouse>scr", where
4550 		 *  s == encoded button state:
4551 		 *	   0x20 = left button down
4552 		 *	   0x21 = middle button down
4553 		 *	   0x22 = right button down
4554 		 *	   0x23 = any button release
4555 		 *	   0x60 = button 4 down (scroll wheel down)
4556 		 *	   0x61 = button 5 down (scroll wheel up)
4557 		 *	add 0x04 for SHIFT
4558 		 *	add 0x08 for ALT
4559 		 *	add 0x10 for CTRL
4560 		 *	add 0x20 for mouse drag (0x40 is drag with left button)
4561 		 *  c == column + ' ' + 1 == column + 33
4562 		 *  r == row + ' ' + 1 == row + 33
4563 		 *
4564 		 * The coordinates are passed on through global variables.
4565 		 * Ugly, but this avoids trouble with mouse clicks at an
4566 		 * unexpected moment and allows for mapping them.
4567 		 */
4568 		for (;;)
4569 		{
4570 #ifdef FEAT_GUI
4571 		    if (gui.in_use)
4572 		    {
4573 			/* GUI uses more bits for columns > 223 */
4574 			num_bytes = get_bytes_from_buf(tp + slen, bytes, 5);
4575 			if (num_bytes == -1)	/* not enough coordinates */
4576 			    return -1;
4577 			mouse_code = bytes[0];
4578 			mouse_col = 128 * (bytes[1] - ' ' - 1)
4579 							 + bytes[2] - ' ' - 1;
4580 			mouse_row = 128 * (bytes[3] - ' ' - 1)
4581 							 + bytes[4] - ' ' - 1;
4582 		    }
4583 		    else
4584 #endif
4585 		    {
4586 			num_bytes = get_bytes_from_buf(tp + slen, bytes, 3);
4587 			if (num_bytes == -1)	/* not enough coordinates */
4588 			    return -1;
4589 			mouse_code = bytes[0];
4590 			mouse_col = bytes[1] - ' ' - 1;
4591 			mouse_row = bytes[2] - ' ' - 1;
4592 		    }
4593 		    slen += num_bytes;
4594 
4595 		    /* If the following bytes is also a mouse code and it has
4596 		     * the same code, dump this one and get the next.  This
4597 		     * makes dragging a whole lot faster. */
4598 #ifdef FEAT_GUI
4599 		    if (gui.in_use)
4600 			j = 3;
4601 		    else
4602 #endif
4603 			j = termcodes[idx].len;
4604 		    if (STRNCMP(tp, tp + slen, (size_t)j) == 0
4605 			    && tp[slen + j] == mouse_code
4606 			    && tp[slen + j + 1] != NUL
4607 			    && tp[slen + j + 2] != NUL
4608 #ifdef FEAT_GUI
4609 			    && (!gui.in_use
4610 				|| (tp[slen + j + 3] != NUL
4611 					&& tp[slen + j + 4] != NUL))
4612 #endif
4613 			    )
4614 			slen += j;
4615 		    else
4616 			break;
4617 		}
4618 	    }
4619 
4620 # if defined(FEAT_MOUSE_URXVT) || defined(FEAT_MOUSE_SGR)
4621 	    if (key_name[0] == KS_URXVT_MOUSE
4622 		|| key_name[0] == KS_SGR_MOUSE)
4623 	    {
4624 		for (;;)
4625 		{
4626 		    /* URXVT 1015 mouse reporting mode:
4627 		     * Almost identical to xterm mouse mode, except the values
4628 		     * are decimal instead of bytes.
4629 		     *
4630 		     * \033[%d;%d;%dM
4631 		     *		  ^-- row
4632 		     *	       ^----- column
4633 		     *	    ^-------- code
4634 		     *
4635 		     * SGR 1006 mouse reporting mode:
4636 		     * Almost identical to xterm mouse mode, except the values
4637 		     * are decimal instead of bytes.
4638 		     *
4639 		     * \033[<%d;%d;%dM
4640 		     *		   ^-- row
4641 		     *	        ^----- column
4642 		     *	     ^-------- code
4643 		     *
4644 		     * \033[<%d;%d;%dm        : mouse release event
4645 		     *		   ^-- row
4646 		     *	        ^----- column
4647 		     *	     ^-------- code
4648 		     */
4649 		    p = tp + slen;
4650 
4651 		    mouse_code = getdigits(&p);
4652 		    if (*p++ != ';')
4653 			return -1;
4654 
4655 		    /* when mouse reporting is SGR, add 32 to mouse code */
4656 		    if (key_name[0] == KS_SGR_MOUSE)
4657 			mouse_code += 32;
4658 
4659 		    mouse_col = getdigits(&p) - 1;
4660 		    if (*p++ != ';')
4661 			return -1;
4662 
4663 		    mouse_row = getdigits(&p) - 1;
4664 		    if (key_name[0] == KS_SGR_MOUSE && *p == 'm')
4665 			mouse_code |= MOUSE_RELEASE;
4666 		    else if (*p != 'M')
4667 			return -1;
4668 		    p++;
4669 
4670 		    slen += (int)(p - (tp + slen));
4671 
4672 		    /* skip this one if next one has same code (like xterm
4673 		     * case) */
4674 		    j = termcodes[idx].len;
4675 		    if (STRNCMP(tp, tp + slen, (size_t)j) == 0)
4676 		    {
4677 			int slen2;
4678 			int cmd_complete = 0;
4679 
4680 			/* check if the command is complete by looking for the
4681 			 * 'M' */
4682 			for (slen2 = slen; slen2 < len; slen2++)
4683 			{
4684 			    if (tp[slen2] == 'M'
4685 				    || (key_name[0] == KS_SGR_MOUSE
4686 							 && tp[slen2] == 'm'))
4687 			    {
4688 				cmd_complete = 1;
4689 				break;
4690 			    }
4691 			}
4692 			p += j;
4693 			if (cmd_complete && getdigits(&p) == mouse_code)
4694 			{
4695 			    slen += j; /* skip the \033[ */
4696 			    continue;
4697 			}
4698 		    }
4699 		    break;
4700 		}
4701 	    }
4702 # endif
4703 
4704 	if (key_name[0] == (int)KS_MOUSE
4705 #ifdef FEAT_MOUSE_URXVT
4706 	    || key_name[0] == (int)KS_URXVT_MOUSE
4707 #endif
4708 #ifdef FEAT_MOUSE_SGR
4709 	    || key_name[0] == KS_SGR_MOUSE
4710 #endif
4711 	    )
4712 	{
4713 #  if !defined(MSWIN) && !defined(MSDOS)
4714 		/*
4715 		 * Handle mouse events.
4716 		 * Recognize the xterm mouse wheel, but not in the GUI, the
4717 		 * Linux console with GPM and the MS-DOS or Win32 console
4718 		 * (multi-clicks use >= 0x60).
4719 		 */
4720 		if (mouse_code >= MOUSEWHEEL_LOW
4721 #   ifdef FEAT_GUI
4722 			&& !gui.in_use
4723 #   endif
4724 #   ifdef FEAT_MOUSE_GPM
4725 			&& gpm_flag == 0
4726 #   endif
4727 			)
4728 		{
4729 		    /* Keep the mouse_code before it's changed, so that we
4730 		     * remember that it was a mouse wheel click. */
4731 		    wheel_code = mouse_code;
4732 		}
4733 #   ifdef FEAT_MOUSE_XTERM
4734 		else if (held_button == MOUSE_RELEASE
4735 #    ifdef FEAT_GUI
4736 			&& !gui.in_use
4737 #    endif
4738 			&& (mouse_code == 0x23 || mouse_code == 0x24))
4739 		{
4740 		    /* Apparently used by rxvt scroll wheel. */
4741 		    wheel_code = mouse_code - 0x23 + MOUSEWHEEL_LOW;
4742 		}
4743 #   endif
4744 
4745 #   if defined(UNIX) && defined(FEAT_MOUSE_TTY)
4746 		else if (use_xterm_mouse() > 1)
4747 		{
4748 		    if (mouse_code & MOUSE_DRAG_XTERM)
4749 			mouse_code |= MOUSE_DRAG;
4750 		}
4751 #   endif
4752 #   ifdef FEAT_XCLIPBOARD
4753 		else if (!(mouse_code & MOUSE_DRAG & ~MOUSE_CLICK_MASK))
4754 		{
4755 		    if ((mouse_code & MOUSE_RELEASE) == MOUSE_RELEASE)
4756 			stop_xterm_trace();
4757 		    else
4758 			start_xterm_trace(mouse_code);
4759 		}
4760 #   endif
4761 #  endif
4762 	    }
4763 # endif /* !UNIX || FEAT_MOUSE_XTERM */
4764 # ifdef FEAT_MOUSE_NET
4765 	    if (key_name[0] == (int)KS_NETTERM_MOUSE)
4766 	    {
4767 		int mc, mr;
4768 
4769 		/* expect a rather limited sequence like: balancing {
4770 		 * \033}6,45\r
4771 		 * '6' is the row, 45 is the column
4772 		 */
4773 		p = tp + slen;
4774 		mr = getdigits(&p);
4775 		if (*p++ != ',')
4776 		    return -1;
4777 		mc = getdigits(&p);
4778 		if (*p++ != '\r')
4779 		    return -1;
4780 
4781 		mouse_col = mc - 1;
4782 		mouse_row = mr - 1;
4783 		mouse_code = MOUSE_LEFT;
4784 		slen += (int)(p - (tp + slen));
4785 	    }
4786 # endif	/* FEAT_MOUSE_NET */
4787 # ifdef FEAT_MOUSE_JSB
4788 	    if (key_name[0] == (int)KS_JSBTERM_MOUSE)
4789 	    {
4790 		int mult, val, iter, button, status;
4791 
4792 		/* JSBTERM Input Model
4793 		 * \033[0~zw uniq escape sequence
4794 		 * (L-x)  Left button pressed - not pressed x not reporting
4795 		 * (M-x)  Middle button pressed - not pressed x not reporting
4796 		 * (R-x)  Right button pressed - not pressed x not reporting
4797 		 * (SDmdu)  Single , Double click, m mouse move d button down
4798 		 *						   u button up
4799 		 *  ###   X cursor position padded to 3 digits
4800 		 *  ###   Y cursor position padded to 3 digits
4801 		 * (s-x)  SHIFT key pressed - not pressed x not reporting
4802 		 * (c-x)  CTRL key pressed - not pressed x not reporting
4803 		 * \033\\ terminating sequence
4804 		 */
4805 
4806 		p = tp + slen;
4807 		button = mouse_code = 0;
4808 		switch (*p++)
4809 		{
4810 		    case 'L': button = 1; break;
4811 		    case '-': break;
4812 		    case 'x': break; /* ignore sequence */
4813 		    default:  return -1; /* Unknown Result */
4814 		}
4815 		switch (*p++)
4816 		{
4817 		    case 'M': button |= 2; break;
4818 		    case '-': break;
4819 		    case 'x': break; /* ignore sequence */
4820 		    default:  return -1; /* Unknown Result */
4821 		}
4822 		switch (*p++)
4823 		{
4824 		    case 'R': button |= 4; break;
4825 		    case '-': break;
4826 		    case 'x': break; /* ignore sequence */
4827 		    default:  return -1; /* Unknown Result */
4828 		}
4829 		status = *p++;
4830 		for (val = 0, mult = 100, iter = 0; iter < 3; iter++,
4831 							      mult /= 10, p++)
4832 		    if (*p >= '0' && *p <= '9')
4833 			val += (*p - '0') * mult;
4834 		    else
4835 			return -1;
4836 		mouse_col = val;
4837 		for (val = 0, mult = 100, iter = 0; iter < 3; iter++,
4838 							      mult /= 10, p++)
4839 		    if (*p >= '0' && *p <= '9')
4840 			val += (*p - '0') * mult;
4841 		    else
4842 			return -1;
4843 		mouse_row = val;
4844 		switch (*p++)
4845 		{
4846 		    case 's': button |= 8; break;  /* SHIFT key Pressed */
4847 		    case '-': break;  /* Not Pressed */
4848 		    case 'x': break;  /* Not Reporting */
4849 		    default:  return -1; /* Unknown Result */
4850 		}
4851 		switch (*p++)
4852 		{
4853 		    case 'c': button |= 16; break;  /* CTRL key Pressed */
4854 		    case '-': break;  /* Not Pressed */
4855 		    case 'x': break;  /* Not Reporting */
4856 		    default:  return -1; /* Unknown Result */
4857 		}
4858 		if (*p++ != '\033')
4859 		    return -1;
4860 		if (*p++ != '\\')
4861 		    return -1;
4862 		switch (status)
4863 		{
4864 		    case 'D': /* Double Click */
4865 		    case 'S': /* Single Click */
4866 			if (button & 1) mouse_code |= MOUSE_LEFT;
4867 			if (button & 2) mouse_code |= MOUSE_MIDDLE;
4868 			if (button & 4) mouse_code |= MOUSE_RIGHT;
4869 			if (button & 8) mouse_code |= MOUSE_SHIFT;
4870 			if (button & 16) mouse_code |= MOUSE_CTRL;
4871 			break;
4872 		    case 'm': /* Mouse move */
4873 			if (button & 1) mouse_code |= MOUSE_LEFT;
4874 			if (button & 2) mouse_code |= MOUSE_MIDDLE;
4875 			if (button & 4) mouse_code |= MOUSE_RIGHT;
4876 			if (button & 8) mouse_code |= MOUSE_SHIFT;
4877 			if (button & 16) mouse_code |= MOUSE_CTRL;
4878 			if ((button & 7) != 0)
4879 			{
4880 			    held_button = mouse_code;
4881 			    mouse_code |= MOUSE_DRAG;
4882 			}
4883 			is_drag = TRUE;
4884 			showmode();
4885 			break;
4886 		    case 'd': /* Button Down */
4887 			if (button & 1) mouse_code |= MOUSE_LEFT;
4888 			if (button & 2) mouse_code |= MOUSE_MIDDLE;
4889 			if (button & 4) mouse_code |= MOUSE_RIGHT;
4890 			if (button & 8) mouse_code |= MOUSE_SHIFT;
4891 			if (button & 16) mouse_code |= MOUSE_CTRL;
4892 			break;
4893 		    case 'u': /* Button Up */
4894 			if (button & 1)
4895 			    mouse_code |= MOUSE_LEFT | MOUSE_RELEASE;
4896 			if (button & 2)
4897 			    mouse_code |= MOUSE_MIDDLE | MOUSE_RELEASE;
4898 			if (button & 4)
4899 			    mouse_code |= MOUSE_RIGHT | MOUSE_RELEASE;
4900 			if (button & 8)
4901 			    mouse_code |= MOUSE_SHIFT;
4902 			if (button & 16)
4903 			    mouse_code |= MOUSE_CTRL;
4904 			break;
4905 		    default: return -1; /* Unknown Result */
4906 		}
4907 
4908 		slen += (p - (tp + slen));
4909 	    }
4910 # endif /* FEAT_MOUSE_JSB */
4911 # ifdef FEAT_MOUSE_DEC
4912 	    if (key_name[0] == (int)KS_DEC_MOUSE)
4913 	    {
4914 	       /* The DEC Locator Input Model
4915 		* Netterm delivers the code sequence:
4916 		*  \033[2;4;24;80&w  (left button down)
4917 		*  \033[3;0;24;80&w  (left button up)
4918 		*  \033[6;1;24;80&w  (right button down)
4919 		*  \033[7;0;24;80&w  (right button up)
4920 		* CSI Pe ; Pb ; Pr ; Pc ; Pp & w
4921 		* Pe is the event code
4922 		* Pb is the button code
4923 		* Pr is the row coordinate
4924 		* Pc is the column coordinate
4925 		* Pp is the third coordinate (page number)
4926 		* Pe, the event code indicates what event caused this report
4927 		*    The following event codes are defined:
4928 		*    0 - request, the terminal received an explicit request
4929 		*	 for a locator report, but the locator is unavailable
4930 		*    1 - request, the terminal received an explicit request
4931 		*	 for a locator report
4932 		*    2 - left button down
4933 		*    3 - left button up
4934 		*    4 - middle button down
4935 		*    5 - middle button up
4936 		*    6 - right button down
4937 		*    7 - right button up
4938 		*    8 - fourth button down
4939 		*    9 - fourth button up
4940 		*    10 - locator outside filter rectangle
4941 		* Pb, the button code, ASCII decimal 0-15 indicating which
4942 		*   buttons are down if any. The state of the four buttons
4943 		*   on the locator correspond to the low four bits of the
4944 		*   decimal value,
4945 		*   "1" means button depressed
4946 		*   0 - no buttons down,
4947 		*   1 - right,
4948 		*   2 - middle,
4949 		*   4 - left,
4950 		*   8 - fourth
4951 		* Pr is the row coordinate of the locator position in the page,
4952 		*   encoded as an ASCII decimal value.
4953 		*   If Pr is omitted, the locator position is undefined
4954 		*   (outside the terminal window for example).
4955 		* Pc is the column coordinate of the locator position in the
4956 		*   page, encoded as an ASCII decimal value.
4957 		*   If Pc is omitted, the locator position is undefined
4958 		*   (outside the terminal window for example).
4959 		* Pp is the page coordinate of the locator position
4960 		*   encoded as an ASCII decimal value.
4961 		*   The page coordinate may be omitted if the locator is on
4962 		*   page one (the default).  We ignore it anyway.
4963 		*/
4964 		int Pe, Pb, Pr, Pc;
4965 
4966 		p = tp + slen;
4967 
4968 		/* get event status */
4969 		Pe = getdigits(&p);
4970 		if (*p++ != ';')
4971 		    return -1;
4972 
4973 		/* get button status */
4974 		Pb = getdigits(&p);
4975 		if (*p++ != ';')
4976 		    return -1;
4977 
4978 		/* get row status */
4979 		Pr = getdigits(&p);
4980 		if (*p++ != ';')
4981 		    return -1;
4982 
4983 		/* get column status */
4984 		Pc = getdigits(&p);
4985 
4986 		/* the page parameter is optional */
4987 		if (*p == ';')
4988 		{
4989 		    p++;
4990 		    (void)getdigits(&p);
4991 		}
4992 		if (*p++ != '&')
4993 		    return -1;
4994 		if (*p++ != 'w')
4995 		    return -1;
4996 
4997 		mouse_code = 0;
4998 		switch (Pe)
4999 		{
5000 		case  0: return -1; /* position request while unavailable */
5001 		case  1: /* a response to a locator position request includes
5002 			    the status of all buttons */
5003 			 Pb &= 7;   /* mask off and ignore fourth button */
5004 			 if (Pb & 4)
5005 			     mouse_code  = MOUSE_LEFT;
5006 			 if (Pb & 2)
5007 			     mouse_code  = MOUSE_MIDDLE;
5008 			 if (Pb & 1)
5009 			     mouse_code  = MOUSE_RIGHT;
5010 			 if (Pb)
5011 			 {
5012 			     held_button = mouse_code;
5013 			     mouse_code |= MOUSE_DRAG;
5014 			     WantQueryMouse = TRUE;
5015 			 }
5016 			 is_drag = TRUE;
5017 			 showmode();
5018 			 break;
5019 		case  2: mouse_code = MOUSE_LEFT;
5020 			 WantQueryMouse = TRUE;
5021 			 break;
5022 		case  3: mouse_code = MOUSE_RELEASE | MOUSE_LEFT;
5023 			 break;
5024 		case  4: mouse_code = MOUSE_MIDDLE;
5025 			 WantQueryMouse = TRUE;
5026 			 break;
5027 		case  5: mouse_code = MOUSE_RELEASE | MOUSE_MIDDLE;
5028 			 break;
5029 		case  6: mouse_code = MOUSE_RIGHT;
5030 			 WantQueryMouse = TRUE;
5031 			 break;
5032 		case  7: mouse_code = MOUSE_RELEASE | MOUSE_RIGHT;
5033 			 break;
5034 		case  8: return -1; /* fourth button down */
5035 		case  9: return -1; /* fourth button up */
5036 		case 10: return -1; /* mouse outside of filter rectangle */
5037 		default: return -1; /* should never occur */
5038 		}
5039 
5040 		mouse_col = Pc - 1;
5041 		mouse_row = Pr - 1;
5042 
5043 		slen += (int)(p - (tp + slen));
5044 	    }
5045 # endif /* FEAT_MOUSE_DEC */
5046 # ifdef FEAT_MOUSE_PTERM
5047 	    if (key_name[0] == (int)KS_PTERM_MOUSE)
5048 	    {
5049 		int button, num_clicks, action;
5050 
5051 		p = tp + slen;
5052 
5053 		action = getdigits(&p);
5054 		if (*p++ != ';')
5055 		    return -1;
5056 
5057 		mouse_row = getdigits(&p);
5058 		if (*p++ != ';')
5059 		    return -1;
5060 		mouse_col = getdigits(&p);
5061 		if (*p++ != ';')
5062 		    return -1;
5063 
5064 		button = getdigits(&p);
5065 		mouse_code = 0;
5066 
5067 		switch( button )
5068 		{
5069 		    case 4: mouse_code = MOUSE_LEFT; break;
5070 		    case 1: mouse_code = MOUSE_RIGHT; break;
5071 		    case 2: mouse_code = MOUSE_MIDDLE; break;
5072 		    default: return -1;
5073 		}
5074 
5075 		switch( action )
5076 		{
5077 		    case 31: /* Initial press */
5078 			if (*p++ != ';')
5079 			    return -1;
5080 
5081 			num_clicks = getdigits(&p); /* Not used */
5082 			break;
5083 
5084 		    case 32: /* Release */
5085 			mouse_code |= MOUSE_RELEASE;
5086 			break;
5087 
5088 		    case 33: /* Drag */
5089 			held_button = mouse_code;
5090 			mouse_code |= MOUSE_DRAG;
5091 			break;
5092 
5093 		    default:
5094 			return -1;
5095 		}
5096 
5097 		if (*p++ != 't')
5098 		    return -1;
5099 
5100 		slen += (p - (tp + slen));
5101 	    }
5102 # endif /* FEAT_MOUSE_PTERM */
5103 
5104 	    /* Interpret the mouse code */
5105 	    current_button = (mouse_code & MOUSE_CLICK_MASK);
5106 	    if (current_button == MOUSE_RELEASE
5107 # ifdef FEAT_MOUSE_XTERM
5108 		    && wheel_code == 0
5109 # endif
5110 		    )
5111 	    {
5112 		/*
5113 		 * If we get a mouse drag or release event when
5114 		 * there is no mouse button held down (held_button ==
5115 		 * MOUSE_RELEASE), produce a K_IGNORE below.
5116 		 * (can happen when you hold down two buttons
5117 		 * and then let them go, or click in the menu bar, but not
5118 		 * on a menu, and drag into the text).
5119 		 */
5120 		if ((mouse_code & MOUSE_DRAG) == MOUSE_DRAG)
5121 		    is_drag = TRUE;
5122 		current_button = held_button;
5123 	    }
5124 	    else if (wheel_code == 0)
5125 	    {
5126 # ifdef CHECK_DOUBLE_CLICK
5127 #  ifdef FEAT_MOUSE_GPM
5128 #   ifdef FEAT_GUI
5129 		/*
5130 		 * Only for Unix, when GUI or gpm is not active, we handle
5131 		 * multi-clicks here.
5132 		 */
5133 		if (gpm_flag == 0 && !gui.in_use)
5134 #   else
5135 		if (gpm_flag == 0)
5136 #   endif
5137 #  else
5138 #   ifdef FEAT_GUI
5139 		if (!gui.in_use)
5140 #   endif
5141 #  endif
5142 		{
5143 		    /*
5144 		     * Compute the time elapsed since the previous mouse click.
5145 		     */
5146 		    gettimeofday(&mouse_time, NULL);
5147 		    timediff = (mouse_time.tv_usec
5148 					    - orig_mouse_time.tv_usec) / 1000;
5149 		    if (timediff < 0)
5150 			--orig_mouse_time.tv_sec;
5151 		    timediff += (mouse_time.tv_sec
5152 					     - orig_mouse_time.tv_sec) * 1000;
5153 		    orig_mouse_time = mouse_time;
5154 		    if (mouse_code == orig_mouse_code
5155 			    && timediff < p_mouset
5156 			    && orig_num_clicks != 4
5157 			    && orig_mouse_col == mouse_col
5158 			    && orig_mouse_row == mouse_row
5159 			    && ((orig_topline == curwin->w_topline
5160 #ifdef FEAT_DIFF
5161 				    && orig_topfill == curwin->w_topfill
5162 #endif
5163 				)
5164 #ifdef FEAT_WINDOWS
5165 				/* Double click in tab pages line also works
5166 				 * when window contents changes. */
5167 				|| (mouse_row == 0 && firstwin->w_winrow > 0)
5168 #endif
5169 			       )
5170 			    )
5171 			++orig_num_clicks;
5172 		    else
5173 			orig_num_clicks = 1;
5174 		    orig_mouse_col = mouse_col;
5175 		    orig_mouse_row = mouse_row;
5176 		    orig_topline = curwin->w_topline;
5177 #ifdef FEAT_DIFF
5178 		    orig_topfill = curwin->w_topfill;
5179 #endif
5180 		}
5181 #  if defined(FEAT_GUI) || defined(FEAT_MOUSE_GPM)
5182 		else
5183 		    orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);
5184 #  endif
5185 # else
5186 		orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);
5187 # endif
5188 		is_click = TRUE;
5189 		orig_mouse_code = mouse_code;
5190 	    }
5191 	    if (!is_drag)
5192 		held_button = mouse_code & MOUSE_CLICK_MASK;
5193 
5194 	    /*
5195 	     * Translate the actual mouse event into a pseudo mouse event.
5196 	     * First work out what modifiers are to be used.
5197 	     */
5198 	    if (orig_mouse_code & MOUSE_SHIFT)
5199 		modifiers |= MOD_MASK_SHIFT;
5200 	    if (orig_mouse_code & MOUSE_CTRL)
5201 		modifiers |= MOD_MASK_CTRL;
5202 	    if (orig_mouse_code & MOUSE_ALT)
5203 		modifiers |= MOD_MASK_ALT;
5204 	    if (orig_num_clicks == 2)
5205 		modifiers |= MOD_MASK_2CLICK;
5206 	    else if (orig_num_clicks == 3)
5207 		modifiers |= MOD_MASK_3CLICK;
5208 	    else if (orig_num_clicks == 4)
5209 		modifiers |= MOD_MASK_4CLICK;
5210 
5211 	    /* Work out our pseudo mouse event */
5212 	    key_name[0] = (int)KS_EXTRA;
5213 	    if (wheel_code != 0)
5214 	    {
5215 		if (wheel_code & MOUSE_CTRL)
5216 		    modifiers |= MOD_MASK_CTRL;
5217 		if (wheel_code & MOUSE_ALT)
5218 		    modifiers |= MOD_MASK_ALT;
5219 		key_name[1] = (wheel_code & 1)
5220 					? (int)KE_MOUSEUP : (int)KE_MOUSEDOWN;
5221 	    }
5222 	    else
5223 		key_name[1] = get_pseudo_mouse_code(current_button,
5224 							   is_click, is_drag);
5225 
5226 	    /* Make sure the mouse position is valid.  Some terminals may
5227 	     * return weird values. */
5228 	    if (mouse_col >= Columns)
5229 		mouse_col = Columns - 1;
5230 	    if (mouse_row >= Rows)
5231 		mouse_row = Rows - 1;
5232 	}
5233 #endif /* FEAT_MOUSE */
5234 
5235 #ifdef FEAT_GUI
5236 	/*
5237 	 * If using the GUI, then we get menu and scrollbar events.
5238 	 *
5239 	 * A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by
5240 	 * four bytes which are to be taken as a pointer to the vimmenu_T
5241 	 * structure.
5242 	 *
5243 	 * A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr"
5244 	 * is one byte with the tab index.
5245 	 *
5246 	 * A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed
5247 	 * by one byte representing the scrollbar number, and then four bytes
5248 	 * representing a long_u which is the new value of the scrollbar.
5249 	 *
5250 	 * A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
5251 	 * KE_FILLER followed by four bytes representing a long_u which is the
5252 	 * new value of the scrollbar.
5253 	 */
5254 # ifdef FEAT_MENU
5255 	else if (key_name[0] == (int)KS_MENU)
5256 	{
5257 	    long_u	val;
5258 
5259 	    num_bytes = get_long_from_buf(tp + slen, &val);
5260 	    if (num_bytes == -1)
5261 		return -1;
5262 	    current_menu = (vimmenu_T *)val;
5263 	    slen += num_bytes;
5264 
5265 	    /* The menu may have been deleted right after it was used, check
5266 	     * for that. */
5267 	    if (check_menu_pointer(root_menu, current_menu) == FAIL)
5268 	    {
5269 		key_name[0] = KS_EXTRA;
5270 		key_name[1] = (int)KE_IGNORE;
5271 	    }
5272 	}
5273 # endif
5274 # ifdef FEAT_GUI_TABLINE
5275 	else if (key_name[0] == (int)KS_TABLINE)
5276 	{
5277 	    /* Selecting tabline tab or using its menu. */
5278 	    num_bytes = get_bytes_from_buf(tp + slen, bytes, 1);
5279 	    if (num_bytes == -1)
5280 		return -1;
5281 	    current_tab = (int)bytes[0];
5282 	    if (current_tab == 255)	/* -1 in a byte gives 255 */
5283 		current_tab = -1;
5284 	    slen += num_bytes;
5285 	}
5286 	else if (key_name[0] == (int)KS_TABMENU)
5287 	{
5288 	    /* Selecting tabline tab or using its menu. */
5289 	    num_bytes = get_bytes_from_buf(tp + slen, bytes, 2);
5290 	    if (num_bytes == -1)
5291 		return -1;
5292 	    current_tab = (int)bytes[0];
5293 	    current_tabmenu = (int)bytes[1];
5294 	    slen += num_bytes;
5295 	}
5296 # endif
5297 # ifndef USE_ON_FLY_SCROLL
5298 	else if (key_name[0] == (int)KS_VER_SCROLLBAR)
5299 	{
5300 	    long_u	val;
5301 
5302 	    /* Get the last scrollbar event in the queue of the same type */
5303 	    j = 0;
5304 	    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR
5305 						     && tp[j + 2] != NUL; ++i)
5306 	    {
5307 		j += 3;
5308 		num_bytes = get_bytes_from_buf(tp + j, bytes, 1);
5309 		if (num_bytes == -1)
5310 		    break;
5311 		if (i == 0)
5312 		    current_scrollbar = (int)bytes[0];
5313 		else if (current_scrollbar != (int)bytes[0])
5314 		    break;
5315 		j += num_bytes;
5316 		num_bytes = get_long_from_buf(tp + j, &val);
5317 		if (num_bytes == -1)
5318 		    break;
5319 		scrollbar_value = val;
5320 		j += num_bytes;
5321 		slen = j;
5322 	    }
5323 	    if (i == 0)		/* not enough characters to make one */
5324 		return -1;
5325 	}
5326 	else if (key_name[0] == (int)KS_HOR_SCROLLBAR)
5327 	{
5328 	    long_u	val;
5329 
5330 	    /* Get the last horiz. scrollbar event in the queue */
5331 	    j = 0;
5332 	    for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR
5333 						     && tp[j + 2] != NUL; ++i)
5334 	    {
5335 		j += 3;
5336 		num_bytes = get_long_from_buf(tp + j, &val);
5337 		if (num_bytes == -1)
5338 		    break;
5339 		scrollbar_value = val;
5340 		j += num_bytes;
5341 		slen = j;
5342 	    }
5343 	    if (i == 0)		/* not enough characters to make one */
5344 		return -1;
5345 	}
5346 # endif /* !USE_ON_FLY_SCROLL */
5347 #endif /* FEAT_GUI */
5348 
5349 	/*
5350 	 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
5351 	 */
5352 	key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));
5353 
5354 	/*
5355 	 * Add any modifier codes to our string.
5356 	 */
5357 	new_slen = 0;		/* Length of what will replace the termcode */
5358 	if (modifiers != 0)
5359 	{
5360 	    /* Some keys have the modifier included.  Need to handle that here
5361 	     * to make mappings work. */
5362 	    key = simplify_key(key, &modifiers);
5363 	    if (modifiers != 0)
5364 	    {
5365 		string[new_slen++] = K_SPECIAL;
5366 		string[new_slen++] = (int)KS_MODIFIER;
5367 		string[new_slen++] = modifiers;
5368 	    }
5369 	}
5370 
5371 	/* Finally, add the special key code to our string */
5372 	key_name[0] = KEY2TERMCAP0(key);
5373 	key_name[1] = KEY2TERMCAP1(key);
5374 	if (key_name[0] == KS_KEY)
5375 	{
5376 	    /* from ":set <M-b>=xx" */
5377 #ifdef FEAT_MBYTE
5378 	    if (has_mbyte)
5379 		new_slen += (*mb_char2bytes)(key_name[1], string + new_slen);
5380 	    else
5381 #endif
5382 		string[new_slen++] = key_name[1];
5383 	}
5384 	else if (new_slen == 0 && key_name[0] == KS_EXTRA
5385 						  && key_name[1] == KE_IGNORE)
5386 	{
5387 	    /* Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED
5388 	     * to indicate what happened. */
5389 	    retval = KEYLEN_REMOVED;
5390 	}
5391 	else
5392 	{
5393 	    string[new_slen++] = K_SPECIAL;
5394 	    string[new_slen++] = key_name[0];
5395 	    string[new_slen++] = key_name[1];
5396 	}
5397 	string[new_slen] = NUL;
5398 	extra = new_slen - slen;
5399 	if (buf == NULL)
5400 	{
5401 	    if (extra < 0)
5402 		/* remove matched chars, taking care of noremap */
5403 		del_typebuf(-extra, offset);
5404 	    else if (extra > 0)
5405 		/* insert the extra space we need */
5406 		ins_typebuf(string + slen, REMAP_YES, offset, FALSE, FALSE);
5407 
5408 	    /*
5409 	     * Careful: del_typebuf() and ins_typebuf() may have reallocated
5410 	     * typebuf.tb_buf[]!
5411 	     */
5412 	    mch_memmove(typebuf.tb_buf + typebuf.tb_off + offset, string,
5413 							    (size_t)new_slen);
5414 	}
5415 	else
5416 	{
5417 	    if (extra < 0)
5418 		/* remove matched characters */
5419 		mch_memmove(buf + offset, buf + offset - extra,
5420 					   (size_t)(*buflen + offset + extra));
5421 	    else if (extra > 0)
5422 	    {
5423 		/* Insert the extra space we need.  If there is insufficient
5424 		 * space return -1. */
5425 		if (*buflen + extra + new_slen >= bufsize)
5426 		    return -1;
5427 		mch_memmove(buf + offset + extra, buf + offset,
5428 						   (size_t)(*buflen - offset));
5429 	    }
5430 	    mch_memmove(buf + offset, string, (size_t)new_slen);
5431 	    *buflen = *buflen + extra + new_slen;
5432 	}
5433 	return retval == 0 ? (len + extra + offset) : retval;
5434     }
5435 
5436 #ifdef FEAT_TERMRESPONSE
5437     LOG_TR("normal character");
5438 #endif
5439 
5440     return 0;			    /* no match found */
5441 }
5442 
5443 /*
5444  * Replace any terminal code strings in from[] with the equivalent internal
5445  * vim representation.	This is used for the "from" and "to" part of a
5446  * mapping, and the "to" part of a menu command.
5447  * Any strings like "<C-UP>" are also replaced, unless 'cpoptions' contains
5448  * '<'.
5449  * K_SPECIAL by itself is replaced by K_SPECIAL KS_SPECIAL KE_FILLER.
5450  *
5451  * The replacement is done in result[] and finally copied into allocated
5452  * memory. If this all works well *bufp is set to the allocated memory and a
5453  * pointer to it is returned. If something fails *bufp is set to NULL and from
5454  * is returned.
5455  *
5456  * CTRL-V characters are removed.  When "from_part" is TRUE, a trailing CTRL-V
5457  * is included, otherwise it is removed (for ":map xx ^V", maps xx to
5458  * nothing).  When 'cpoptions' does not contain 'B', a backslash can be used
5459  * instead of a CTRL-V.
5460  */
5461     char_u *
5462 replace_termcodes(from, bufp, from_part, do_lt, special)
5463     char_u	*from;
5464     char_u	**bufp;
5465     int		from_part;
5466     int		do_lt;		/* also translate <lt> */
5467     int		special;	/* always accept <key> notation */
5468 {
5469     int		i;
5470     int		slen;
5471     int		key;
5472     int		dlen = 0;
5473     char_u	*src;
5474     int		do_backslash;	/* backslash is a special character */
5475     int		do_special;	/* recognize <> key codes */
5476     int		do_key_code;	/* recognize raw key codes */
5477     char_u	*result;	/* buffer for resulting string */
5478 
5479     do_backslash = (vim_strchr(p_cpo, CPO_BSLASH) == NULL);
5480     do_special = (vim_strchr(p_cpo, CPO_SPECI) == NULL) || special;
5481     do_key_code = (vim_strchr(p_cpo, CPO_KEYCODE) == NULL);
5482 
5483     /*
5484      * Allocate space for the translation.  Worst case a single character is
5485      * replaced by 6 bytes (shifted special key), plus a NUL at the end.
5486      */
5487     result = alloc((unsigned)STRLEN(from) * 6 + 1);
5488     if (result == NULL)		/* out of memory */
5489     {
5490 	*bufp = NULL;
5491 	return from;
5492     }
5493 
5494     src = from;
5495 
5496     /*
5497      * Check for #n at start only: function key n
5498      */
5499     if (from_part && src[0] == '#' && VIM_ISDIGIT(src[1]))  /* function key */
5500     {
5501 	result[dlen++] = K_SPECIAL;
5502 	result[dlen++] = 'k';
5503 	if (src[1] == '0')
5504 	    result[dlen++] = ';';	/* #0 is F10 is "k;" */
5505 	else
5506 	    result[dlen++] = src[1];	/* #3 is F3 is "k3" */
5507 	src += 2;
5508     }
5509 
5510     /*
5511      * Copy each byte from *from to result[dlen]
5512      */
5513     while (*src != NUL)
5514     {
5515 	/*
5516 	 * If 'cpoptions' does not contain '<', check for special key codes,
5517 	 * like "<C-S-LeftMouse>"
5518 	 */
5519 	if (do_special && (do_lt || STRNCMP(src, "<lt>", 4) != 0))
5520 	{
5521 #ifdef FEAT_EVAL
5522 	    /*
5523 	     * Replace <SID> by K_SNR <script-nr> _.
5524 	     * (room: 5 * 6 = 30 bytes; needed: 3 + <nr> + 1 <= 14)
5525 	     */
5526 	    if (STRNICMP(src, "<SID>", 5) == 0)
5527 	    {
5528 		if (current_SID <= 0)
5529 		    EMSG(_(e_usingsid));
5530 		else
5531 		{
5532 		    src += 5;
5533 		    result[dlen++] = K_SPECIAL;
5534 		    result[dlen++] = (int)KS_EXTRA;
5535 		    result[dlen++] = (int)KE_SNR;
5536 		    sprintf((char *)result + dlen, "%ld", (long)current_SID);
5537 		    dlen += (int)STRLEN(result + dlen);
5538 		    result[dlen++] = '_';
5539 		    continue;
5540 		}
5541 	    }
5542 #endif
5543 
5544 	    slen = trans_special(&src, result + dlen, TRUE);
5545 	    if (slen)
5546 	    {
5547 		dlen += slen;
5548 		continue;
5549 	    }
5550 	}
5551 
5552 	/*
5553 	 * If 'cpoptions' does not contain 'k', see if it's an actual key-code.
5554 	 * Note that this is also checked after replacing the <> form.
5555 	 * Single character codes are NOT replaced (e.g. ^H or DEL), because
5556 	 * it could be a character in the file.
5557 	 */
5558 	if (do_key_code)
5559 	{
5560 	    i = find_term_bykeys(src);
5561 	    if (i >= 0)
5562 	    {
5563 		result[dlen++] = K_SPECIAL;
5564 		result[dlen++] = termcodes[i].name[0];
5565 		result[dlen++] = termcodes[i].name[1];
5566 		src += termcodes[i].len;
5567 		/* If terminal code matched, continue after it. */
5568 		continue;
5569 	    }
5570 	}
5571 
5572 #ifdef FEAT_EVAL
5573 	if (do_special)
5574 	{
5575 	    char_u	*p, *s, len;
5576 
5577 	    /*
5578 	     * Replace <Leader> by the value of "mapleader".
5579 	     * Replace <LocalLeader> by the value of "maplocalleader".
5580 	     * If "mapleader" or "maplocalleader" isn't set use a backslash.
5581 	     */
5582 	    if (STRNICMP(src, "<Leader>", 8) == 0)
5583 	    {
5584 		len = 8;
5585 		p = get_var_value((char_u *)"g:mapleader");
5586 	    }
5587 	    else if (STRNICMP(src, "<LocalLeader>", 13) == 0)
5588 	    {
5589 		len = 13;
5590 		p = get_var_value((char_u *)"g:maplocalleader");
5591 	    }
5592 	    else
5593 	    {
5594 		len = 0;
5595 		p = NULL;
5596 	    }
5597 	    if (len != 0)
5598 	    {
5599 		/* Allow up to 8 * 6 characters for "mapleader". */
5600 		if (p == NULL || *p == NUL || STRLEN(p) > 8 * 6)
5601 		    s = (char_u *)"\\";
5602 		else
5603 		    s = p;
5604 		while (*s != NUL)
5605 		    result[dlen++] = *s++;
5606 		src += len;
5607 		continue;
5608 	    }
5609 	}
5610 #endif
5611 
5612 	/*
5613 	 * Remove CTRL-V and ignore the next character.
5614 	 * For "from" side the CTRL-V at the end is included, for the "to"
5615 	 * part it is removed.
5616 	 * If 'cpoptions' does not contain 'B', also accept a backslash.
5617 	 */
5618 	key = *src;
5619 	if (key == Ctrl_V || (do_backslash && key == '\\'))
5620 	{
5621 	    ++src;				/* skip CTRL-V or backslash */
5622 	    if (*src == NUL)
5623 	    {
5624 		if (from_part)
5625 		    result[dlen++] = key;
5626 		break;
5627 	    }
5628 	}
5629 
5630 #ifdef FEAT_MBYTE
5631 	/* skip multibyte char correctly */
5632 	for (i = (*mb_ptr2len)(src); i > 0; --i)
5633 #endif
5634 	{
5635 	    /*
5636 	     * If the character is K_SPECIAL, replace it with K_SPECIAL
5637 	     * KS_SPECIAL KE_FILLER.
5638 	     * If compiled with the GUI replace CSI with K_CSI.
5639 	     */
5640 	    if (*src == K_SPECIAL)
5641 	    {
5642 		result[dlen++] = K_SPECIAL;
5643 		result[dlen++] = KS_SPECIAL;
5644 		result[dlen++] = KE_FILLER;
5645 	    }
5646 # ifdef FEAT_GUI
5647 	    else if (*src == CSI)
5648 	    {
5649 		result[dlen++] = K_SPECIAL;
5650 		result[dlen++] = KS_EXTRA;
5651 		result[dlen++] = (int)KE_CSI;
5652 	    }
5653 # endif
5654 	    else
5655 		result[dlen++] = *src;
5656 	    ++src;
5657 	}
5658     }
5659     result[dlen] = NUL;
5660 
5661     /*
5662      * Copy the new string to allocated memory.
5663      * If this fails, just return from.
5664      */
5665     if ((*bufp = vim_strsave(result)) != NULL)
5666 	from = *bufp;
5667     vim_free(result);
5668     return from;
5669 }
5670 
5671 /*
5672  * Find a termcode with keys 'src' (must be NUL terminated).
5673  * Return the index in termcodes[], or -1 if not found.
5674  */
5675     int
5676 find_term_bykeys(src)
5677     char_u	*src;
5678 {
5679     int		i;
5680     int		slen = (int)STRLEN(src);
5681 
5682     for (i = 0; i < tc_len; ++i)
5683     {
5684 	if (slen == termcodes[i].len
5685 			&& STRNCMP(termcodes[i].code, src, (size_t)slen) == 0)
5686 	    return i;
5687     }
5688     return -1;
5689 }
5690 
5691 /*
5692  * Gather the first characters in the terminal key codes into a string.
5693  * Used to speed up check_termcode().
5694  */
5695     static void
5696 gather_termleader()
5697 {
5698     int	    i;
5699     int	    len = 0;
5700 
5701 #ifdef FEAT_GUI
5702     if (gui.in_use)
5703 	termleader[len++] = CSI;    /* the GUI codes are not in termcodes[] */
5704 #endif
5705 #ifdef FEAT_TERMRESPONSE
5706     if (check_for_codes)
5707 	termleader[len++] = DCS;    /* the termcode response starts with DCS
5708 				       in 8-bit mode */
5709 #endif
5710     termleader[len] = NUL;
5711 
5712     for (i = 0; i < tc_len; ++i)
5713 	if (vim_strchr(termleader, termcodes[i].code[0]) == NULL)
5714 	{
5715 	    termleader[len++] = termcodes[i].code[0];
5716 	    termleader[len] = NUL;
5717 	}
5718 
5719     need_gather = FALSE;
5720 }
5721 
5722 /*
5723  * Show all termcodes (for ":set termcap")
5724  * This code looks a lot like showoptions(), but is different.
5725  */
5726     void
5727 show_termcodes()
5728 {
5729     int		col;
5730     int		*items;
5731     int		item_count;
5732     int		run;
5733     int		row, rows;
5734     int		cols;
5735     int		i;
5736     int		len;
5737 
5738 #define INC3 27	    /* try to make three columns */
5739 #define INC2 40	    /* try to make two columns */
5740 #define GAP 2	    /* spaces between columns */
5741 
5742     if (tc_len == 0)	    /* no terminal codes (must be GUI) */
5743 	return;
5744     items = (int *)alloc((unsigned)(sizeof(int) * tc_len));
5745     if (items == NULL)
5746 	return;
5747 
5748     /* Highlight title */
5749     MSG_PUTS_TITLE(_("\n--- Terminal keys ---"));
5750 
5751     /*
5752      * do the loop two times:
5753      * 1. display the short items (non-strings and short strings)
5754      * 2. display the medium items (medium length strings)
5755      * 3. display the long items (remaining strings)
5756      */
5757     for (run = 1; run <= 3 && !got_int; ++run)
5758     {
5759 	/*
5760 	 * collect the items in items[]
5761 	 */
5762 	item_count = 0;
5763 	for (i = 0; i < tc_len; i++)
5764 	{
5765 	    len = show_one_termcode(termcodes[i].name,
5766 						    termcodes[i].code, FALSE);
5767 	    if (len <= INC3 - GAP ? run == 1
5768 			: len <= INC2 - GAP ? run == 2
5769 			: run == 3)
5770 		items[item_count++] = i;
5771 	}
5772 
5773 	/*
5774 	 * display the items
5775 	 */
5776 	if (run <= 2)
5777 	{
5778 	    cols = (Columns + GAP) / (run == 1 ? INC3 : INC2);
5779 	    if (cols == 0)
5780 		cols = 1;
5781 	    rows = (item_count + cols - 1) / cols;
5782 	}
5783 	else	/* run == 3 */
5784 	    rows = item_count;
5785 	for (row = 0; row < rows && !got_int; ++row)
5786 	{
5787 	    msg_putchar('\n');			/* go to next line */
5788 	    if (got_int)			/* 'q' typed in more */
5789 		break;
5790 	    col = 0;
5791 	    for (i = row; i < item_count; i += rows)
5792 	    {
5793 		msg_col = col;			/* make columns */
5794 		show_one_termcode(termcodes[items[i]].name,
5795 					      termcodes[items[i]].code, TRUE);
5796 		if (run == 2)
5797 		    col += INC2;
5798 		else
5799 		    col += INC3;
5800 	    }
5801 	    out_flush();
5802 	    ui_breakcheck();
5803 	}
5804     }
5805     vim_free(items);
5806 }
5807 
5808 /*
5809  * Show one termcode entry.
5810  * Output goes into IObuff[]
5811  */
5812     int
5813 show_one_termcode(name, code, printit)
5814     char_u  *name;
5815     char_u  *code;
5816     int	    printit;
5817 {
5818     char_u	*p;
5819     int		len;
5820 
5821     if (name[0] > '~')
5822     {
5823 	IObuff[0] = ' ';
5824 	IObuff[1] = ' ';
5825 	IObuff[2] = ' ';
5826 	IObuff[3] = ' ';
5827     }
5828     else
5829     {
5830 	IObuff[0] = 't';
5831 	IObuff[1] = '_';
5832 	IObuff[2] = name[0];
5833 	IObuff[3] = name[1];
5834     }
5835     IObuff[4] = ' ';
5836 
5837     p = get_special_key_name(TERMCAP2KEY(name[0], name[1]), 0);
5838     if (p[1] != 't')
5839 	STRCPY(IObuff + 5, p);
5840     else
5841 	IObuff[5] = NUL;
5842     len = (int)STRLEN(IObuff);
5843     do
5844 	IObuff[len++] = ' ';
5845     while (len < 17);
5846     IObuff[len] = NUL;
5847     if (code == NULL)
5848 	len += 4;
5849     else
5850 	len += vim_strsize(code);
5851 
5852     if (printit)
5853     {
5854 	msg_puts(IObuff);
5855 	if (code == NULL)
5856 	    msg_puts((char_u *)"NULL");
5857 	else
5858 	    msg_outtrans(code);
5859     }
5860     return len;
5861 }
5862 
5863 #if defined(FEAT_TERMRESPONSE) || defined(PROTO)
5864 /*
5865  * For Xterm >= 140 compiled with OPT_TCAP_QUERY: Obtain the actually used
5866  * termcap codes from the terminal itself.
5867  * We get them one by one to avoid a very long response string.
5868  */
5869 static int xt_index_in = 0;
5870 static int xt_index_out = 0;
5871 
5872     static void
5873 req_codes_from_term()
5874 {
5875     xt_index_out = 0;
5876     xt_index_in = 0;
5877     req_more_codes_from_term();
5878 }
5879 
5880     static void
5881 req_more_codes_from_term()
5882 {
5883     char	buf[11];
5884     int		old_idx = xt_index_out;
5885 
5886     /* Don't do anything when going to exit. */
5887     if (exiting)
5888 	return;
5889 
5890     /* Send up to 10 more requests out than we received.  Avoid sending too
5891      * many, there can be a buffer overflow somewhere. */
5892     while (xt_index_out < xt_index_in + 10 && key_names[xt_index_out] != NULL)
5893     {
5894 # ifdef DEBUG_TERMRESPONSE
5895 	char dbuf[100];
5896 
5897 	sprintf(dbuf, "Requesting XT %d: %s",
5898 				       xt_index_out, key_names[xt_index_out]);
5899 	log_tr(dbuf);
5900 # endif
5901 	sprintf(buf, "\033P+q%02x%02x\033\\",
5902 		      key_names[xt_index_out][0], key_names[xt_index_out][1]);
5903 	out_str_nf((char_u *)buf);
5904 	++xt_index_out;
5905     }
5906 
5907     /* Send the codes out right away. */
5908     if (xt_index_out != old_idx)
5909 	out_flush();
5910 }
5911 
5912 /*
5913  * Decode key code response from xterm: '<Esc>P1+r<name>=<string><Esc>\'.
5914  * A "0" instead of the "1" indicates a code that isn't supported.
5915  * Both <name> and <string> are encoded in hex.
5916  * "code" points to the "0" or "1".
5917  */
5918     static void
5919 got_code_from_term(code, len)
5920     char_u	*code;
5921     int		len;
5922 {
5923 #define XT_LEN 100
5924     char_u	name[3];
5925     char_u	str[XT_LEN];
5926     int		i;
5927     int		j = 0;
5928     int		c;
5929 
5930     /* A '1' means the code is supported, a '0' means it isn't.
5931      * When half the length is > XT_LEN we can't use it.
5932      * Our names are currently all 2 characters. */
5933     if (code[0] == '1' && code[7] == '=' && len / 2 < XT_LEN)
5934     {
5935 	/* Get the name from the response and find it in the table. */
5936 	name[0] = hexhex2nr(code + 3);
5937 	name[1] = hexhex2nr(code + 5);
5938 	name[2] = NUL;
5939 	for (i = 0; key_names[i] != NULL; ++i)
5940 	{
5941 	    if (STRCMP(key_names[i], name) == 0)
5942 	    {
5943 		xt_index_in = i;
5944 		break;
5945 	    }
5946 	}
5947 # ifdef DEBUG_TERMRESPONSE
5948 	{
5949 	    char buf[100];
5950 
5951 	    sprintf(buf, "Received XT %d: %s", xt_index_in, (char *)name);
5952 	    log_tr(buf);
5953 	}
5954 # endif
5955 	if (key_names[i] != NULL)
5956 	{
5957 	    for (i = 8; (c = hexhex2nr(code + i)) >= 0; i += 2)
5958 		str[j++] = c;
5959 	    str[j] = NUL;
5960 	    if (name[0] == 'C' && name[1] == 'o')
5961 	    {
5962 		/* Color count is not a key code. */
5963 		i = atoi((char *)str);
5964 		if (i != t_colors)
5965 		{
5966 		    /* Nr of colors changed, initialize highlighting and
5967 		     * redraw everything.  This causes a redraw, which usually
5968 		     * clears the message.  Try keeping the message if it
5969 		     * might work. */
5970 		    set_keep_msg_from_hist();
5971 		    set_color_count(i);
5972 		    init_highlight(TRUE, FALSE);
5973 #ifdef DEBUG_TERMRESPONSE
5974 		    {
5975 			char buf[100];
5976 			int  r = redraw_asap(CLEAR);
5977 
5978 			sprintf(buf, "Received t_Co, redraw_asap(): %d", r);
5979 			log_tr(buf);
5980 		    }
5981 #else
5982 		    redraw_asap(CLEAR);
5983 #endif
5984 		}
5985 	    }
5986 	    else
5987 	    {
5988 		/* First delete any existing entry with the same code. */
5989 		i = find_term_bykeys(str);
5990 		if (i >= 0)
5991 		    del_termcode_idx(i);
5992 		add_termcode(name, str, ATC_FROM_TERM);
5993 	    }
5994 	}
5995     }
5996 
5997     /* May request more codes now that we received one. */
5998     ++xt_index_in;
5999     req_more_codes_from_term();
6000 }
6001 
6002 /*
6003  * Check if there are any unanswered requests and deal with them.
6004  * This is called before starting an external program or getting direct
6005  * keyboard input.  We don't want responses to be send to that program or
6006  * handled as typed text.
6007  */
6008     static void
6009 check_for_codes_from_term()
6010 {
6011     int		c;
6012 
6013     /* If no codes requested or all are answered, no need to wait. */
6014     if (xt_index_out == 0 || xt_index_out == xt_index_in)
6015 	return;
6016 
6017     /* Vgetc() will check for and handle any response.
6018      * Keep calling vpeekc() until we don't get any responses. */
6019     ++no_mapping;
6020     ++allow_keys;
6021     for (;;)
6022     {
6023 	c = vpeekc();
6024 	if (c == NUL)	    /* nothing available */
6025 	    break;
6026 
6027 	/* If a response is recognized it's replaced with K_IGNORE, must read
6028 	 * it from the input stream.  If there is no K_IGNORE we can't do
6029 	 * anything, break here (there might be some responses further on, but
6030 	 * we don't want to throw away any typed chars). */
6031 	if (c != K_SPECIAL && c != K_IGNORE)
6032 	    break;
6033 	c = vgetc();
6034 	if (c != K_IGNORE)
6035 	{
6036 	    vungetc(c);
6037 	    break;
6038 	}
6039     }
6040     --no_mapping;
6041     --allow_keys;
6042 }
6043 #endif
6044 
6045 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
6046 /*
6047  * Translate an internal mapping/abbreviation representation into the
6048  * corresponding external one recognized by :map/:abbrev commands;
6049  * respects the current B/k/< settings of 'cpoption'.
6050  *
6051  * This function is called when expanding mappings/abbreviations on the
6052  * command-line, and for building the "Ambiguous mapping..." error message.
6053  *
6054  * It uses a growarray to build the translation string since the
6055  * latter can be wider than the original description. The caller has to
6056  * free the string afterwards.
6057  *
6058  * Returns NULL when there is a problem.
6059  */
6060     char_u *
6061 translate_mapping(str, expmap)
6062     char_u	*str;
6063     int		expmap;  /* TRUE when expanding mappings on command-line */
6064 {
6065     garray_T	ga;
6066     int		c;
6067     int		modifiers;
6068     int		cpo_bslash;
6069     int		cpo_special;
6070     int		cpo_keycode;
6071 
6072     ga_init(&ga);
6073     ga.ga_itemsize = 1;
6074     ga.ga_growsize = 40;
6075 
6076     cpo_bslash = (vim_strchr(p_cpo, CPO_BSLASH) != NULL);
6077     cpo_special = (vim_strchr(p_cpo, CPO_SPECI) != NULL);
6078     cpo_keycode = (vim_strchr(p_cpo, CPO_KEYCODE) == NULL);
6079 
6080     for (; *str; ++str)
6081     {
6082 	c = *str;
6083 	if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
6084 	{
6085 	    modifiers = 0;
6086 	    if (str[1] == KS_MODIFIER)
6087 	    {
6088 		str++;
6089 		modifiers = *++str;
6090 		c = *++str;
6091 	    }
6092 	    if (cpo_special && cpo_keycode && c == K_SPECIAL && !modifiers)
6093 	    {
6094 		int	i;
6095 
6096 		/* try to find special key in termcodes */
6097 		for (i = 0; i < tc_len; ++i)
6098 		    if (termcodes[i].name[0] == str[1]
6099 					    && termcodes[i].name[1] == str[2])
6100 			break;
6101 		if (i < tc_len)
6102 		{
6103 		    ga_concat(&ga, termcodes[i].code);
6104 		    str += 2;
6105 		    continue; /* for (str) */
6106 		}
6107 	    }
6108 	    if (c == K_SPECIAL && str[1] != NUL && str[2] != NUL)
6109 	    {
6110 		if (expmap && cpo_special)
6111 		{
6112 		    ga_clear(&ga);
6113 		    return NULL;
6114 		}
6115 		c = TO_SPECIAL(str[1], str[2]);
6116 		if (c == K_ZERO)	/* display <Nul> as ^@ */
6117 		    c = NUL;
6118 		str += 2;
6119 	    }
6120 	    if (IS_SPECIAL(c) || modifiers)	/* special key */
6121 	    {
6122 		if (expmap && cpo_special)
6123 		{
6124 		    ga_clear(&ga);
6125 		    return NULL;
6126 		}
6127 		ga_concat(&ga, get_special_key_name(c, modifiers));
6128 		continue; /* for (str) */
6129 	    }
6130 	}
6131 	if (c == ' ' || c == '\t' || c == Ctrl_J || c == Ctrl_V
6132 	    || (c == '<' && !cpo_special) || (c == '\\' && !cpo_bslash))
6133 	    ga_append(&ga, cpo_bslash ? Ctrl_V : '\\');
6134 	if (c)
6135 	    ga_append(&ga, c);
6136     }
6137     ga_append(&ga, NUL);
6138     return (char_u *)(ga.ga_data);
6139 }
6140 #endif
6141 
6142 #if (defined(WIN3264) && !defined(FEAT_GUI)) || defined(PROTO)
6143 static char ksme_str[20];
6144 static char ksmr_str[20];
6145 static char ksmd_str[20];
6146 
6147 /*
6148  * For Win32 console: update termcap codes for existing console attributes.
6149  */
6150     void
6151 update_tcap(attr)
6152     int attr;
6153 {
6154     struct builtin_term *p;
6155 
6156     p = find_builtin_term(DEFAULT_TERM);
6157     sprintf(ksme_str, IF_EB("\033|%dm", ESC_STR "|%dm"), attr);
6158     sprintf(ksmd_str, IF_EB("\033|%dm", ESC_STR "|%dm"),
6159 				     attr | 0x08);  /* FOREGROUND_INTENSITY */
6160     sprintf(ksmr_str, IF_EB("\033|%dm", ESC_STR "|%dm"),
6161 				 ((attr & 0x0F) << 4) | ((attr & 0xF0) >> 4));
6162 
6163     while (p->bt_string != NULL)
6164     {
6165       if (p->bt_entry == (int)KS_ME)
6166 	  p->bt_string = &ksme_str[0];
6167       else if (p->bt_entry == (int)KS_MR)
6168 	  p->bt_string = &ksmr_str[0];
6169       else if (p->bt_entry == (int)KS_MD)
6170 	  p->bt_string = &ksmd_str[0];
6171       ++p;
6172     }
6173 }
6174 #endif
6175