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