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