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