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