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