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