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