blob: 2c31974739b86bbc9b4662ee4fb495dc7110e4ed [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* 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 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
39 *
40 * TODO:
Bram Moolenaar46359e12017-11-29 22:33:38 +010041 * - When using 'termguicolors' still use the 16 ANSI colors as-is. Helps for
42 * a job that uses 16 colors while Vim is using > 256.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020043 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
44 * Higashi, 2017 Sep 19)
45 * - Shift-Tab does not work.
Bram Moolenaar3a497e12017-09-30 20:40:27 +020046 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020047 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
48 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020049 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010050 * - When closing gvim with an active terminal buffer, the dialog suggests
51 * saving the buffer. Should say something else. (Manas Thakur, #2215)
52 * Also: #2223
Bram Moolenaarba6febd2017-10-30 21:56:23 +010053 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020054 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaarff546792017-11-21 14:47:57 +010055 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010057 * - After executing a shell command the status line isn't redraw.
Bram Moolenaarba6febd2017-10-30 21:56:23 +010058 * - What to store in a session file? Shell at the prompt would be OK to
59 * restore, but others may not. Open the window and let the user start the
60 * command?
Bram Moolenaar46359e12017-11-29 22:33:38 +010061 * - implement term_setsize()
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020062 * - add test for giving error for invalid 'termsize' value.
63 * - support minimal size when 'termsize' is "rows*cols".
64 * - support minimal size when 'termsize' is empty?
65 * - GUI: when using tabs, focus in terminal, click on tab does not work.
66 * - GUI: when 'confirm' is set and trying to exit Vim, dialog offers to save
67 * changes to "!shell".
68 * (justrajdeep, 2017 Aug 22)
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020069 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020070 * - For the GUI fill termios with default values, perhaps like pangoterm:
71 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
72 * - if the job in the terminal does not support the mouse, we can use the
73 * mouse in the Terminal window for copy/paste.
74 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
75 * conversions.
76 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
77 * the window and position it higher up when it gets filled, so it looks like
78 * the text scrolls up.
79 * - Copy text in the vterm to the Vim buffer once in a while, so that
80 * completion works.
81 * - add an optional limit for the scrollback size. When reaching it remove
82 * 10% at the start.
83 */
84
85#include "vim.h"
86
87#if defined(FEAT_TERMINAL) || defined(PROTO)
88
89#ifndef MIN
90# define MIN(x,y) ((x) < (y) ? (x) : (y))
91#endif
92#ifndef MAX
93# define MAX(x,y) ((x) > (y) ? (x) : (y))
94#endif
95
96#include "libvterm/include/vterm.h"
97
98/* This is VTermScreenCell without the characters, thus much smaller. */
99typedef struct {
100 VTermScreenCellAttrs attrs;
101 char width;
102 VTermColor fg, bg;
103} cellattr_T;
104
105typedef struct sb_line_S {
106 int sb_cols; /* can differ per line */
107 cellattr_T *sb_cells; /* allocated */
108 cellattr_T sb_fill_attr; /* for short line */
109} sb_line_T;
110
111/* typedef term_T in structs.h */
112struct terminal_S {
113 term_T *tl_next;
114
115 VTerm *tl_vterm;
116 job_T *tl_job;
117 buf_T *tl_buffer;
118
119 /* Set when setting the size of a vterm, reset after redrawing. */
120 int tl_vterm_size_changed;
121
122 /* used when tl_job is NULL and only a pty was created */
123 int tl_tty_fd;
124 char_u *tl_tty_in;
125 char_u *tl_tty_out;
126
127 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
128 int tl_channel_closed;
129 int tl_finish; /* 'c' for ++close, 'o' for ++open */
130 char_u *tl_opencmd;
131 char_u *tl_eof_chars;
132
133#ifdef WIN3264
134 void *tl_winpty_config;
135 void *tl_winpty;
136#endif
137
138 /* last known vterm size */
139 int tl_rows;
140 int tl_cols;
141 /* vterm size does not follow window size */
142 int tl_rows_fixed;
143 int tl_cols_fixed;
144
145 char_u *tl_title; /* NULL or allocated */
146 char_u *tl_status_text; /* NULL or allocated */
147
148 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200149 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200150 int tl_dirty_row_end; /* row below last one to update */
151
152 garray_T tl_scrollback;
153 int tl_scrollback_scrolled;
154 cellattr_T tl_default_color;
155
156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
176#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
177#define KEY_BUF_LEN 200
178
179/*
180 * Functions with separate implementation for MS-Windows and Unix-like systems.
181 */
182static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
183static int create_pty_only(term_T *term, jobopt_T *opt);
184static void term_report_winsize(term_T *term, int rows, int cols);
185static void term_free_vterm(term_T *term);
186
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100187/* The character that we know (or assume) that the terminal expects for the
188 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
191
192/**************************************
193 * 1. Generic code for all systems.
194 */
195
196/*
197 * Determine the terminal size from 'termsize' and the current window.
198 * Assumes term->tl_rows and term->tl_cols are zero.
199 */
200 static void
201set_term_and_win_size(term_T *term)
202{
203 if (*curwin->w_p_tms != NUL)
204 {
205 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
206
207 term->tl_rows = atoi((char *)curwin->w_p_tms);
208 term->tl_cols = atoi((char *)p);
209 }
210 if (term->tl_rows == 0)
211 term->tl_rows = curwin->w_height;
212 else
213 {
214 win_setheight_win(term->tl_rows, curwin);
215 term->tl_rows_fixed = TRUE;
216 }
217 if (term->tl_cols == 0)
218 term->tl_cols = curwin->w_width;
219 else
220 {
221 win_setwidth_win(term->tl_cols, curwin);
222 term->tl_cols_fixed = TRUE;
223 }
224}
225
226/*
227 * Initialize job options for a terminal job.
228 * Caller may overrule some of them.
229 */
230 static void
231init_job_options(jobopt_T *opt)
232{
233 clear_job_options(opt);
234
235 opt->jo_mode = MODE_RAW;
236 opt->jo_out_mode = MODE_RAW;
237 opt->jo_err_mode = MODE_RAW;
238 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
239}
240
241/*
242 * Set job options mandatory for a terminal job.
243 */
244 static void
245setup_job_options(jobopt_T *opt, int rows, int cols)
246{
247 if (!(opt->jo_set & JO_OUT_IO))
248 {
249 /* Connect stdout to the terminal. */
250 opt->jo_io[PART_OUT] = JIO_BUFFER;
251 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
252 opt->jo_modifiable[PART_OUT] = 0;
253 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
254 }
255
256 if (!(opt->jo_set & JO_ERR_IO))
257 {
258 /* Connect stderr to the terminal. */
259 opt->jo_io[PART_ERR] = JIO_BUFFER;
260 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
261 opt->jo_modifiable[PART_ERR] = 0;
262 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
263 }
264
265 opt->jo_pty = TRUE;
266 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
267 opt->jo_term_rows = rows;
268 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
269 opt->jo_term_cols = cols;
270}
271
272/*
273 * Start a terminal window and return its buffer.
274 * Returns NULL when failed.
275 */
276 static buf_T *
277term_start(typval_T *argvar, jobopt_T *opt, int forceit)
278{
279 exarg_T split_ea;
280 win_T *old_curwin = curwin;
281 term_T *term;
282 buf_T *old_curbuf = NULL;
283 int res;
284 buf_T *newbuf;
285
286 if (check_restricted() || check_secure())
287 return NULL;
288
289 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
290 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
291 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
292 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
293 {
294 EMSG(_(e_invarg));
295 return NULL;
296 }
297
298 term = (term_T *)alloc_clear(sizeof(term_T));
299 if (term == NULL)
300 return NULL;
301 term->tl_dirty_row_end = MAX_ROW;
302 term->tl_cursor_visible = TRUE;
303 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
304 term->tl_finish = opt->jo_term_finish;
305 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
306
307 vim_memset(&split_ea, 0, sizeof(split_ea));
308 if (opt->jo_curwin)
309 {
310 /* Create a new buffer in the current window. */
311 if (!can_abandon(curbuf, forceit))
312 {
313 no_write_message();
314 vim_free(term);
315 return NULL;
316 }
317 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
318 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
319 {
320 vim_free(term);
321 return NULL;
322 }
323 }
324 else if (opt->jo_hidden)
325 {
326 buf_T *buf;
327
328 /* Create a new buffer without a window. Make it the current buffer for
329 * a moment to be able to do the initialisations. */
330 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
331 BLN_NEW | BLN_LISTED);
332 if (buf == NULL || ml_open(buf) == FAIL)
333 {
334 vim_free(term);
335 return NULL;
336 }
337 old_curbuf = curbuf;
338 --curbuf->b_nwindows;
339 curbuf = buf;
340 curwin->w_buffer = buf;
341 ++curbuf->b_nwindows;
342 }
343 else
344 {
345 /* Open a new window or tab. */
346 split_ea.cmdidx = CMD_new;
347 split_ea.cmd = (char_u *)"new";
348 split_ea.arg = (char_u *)"";
349 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
350 {
351 split_ea.line2 = opt->jo_term_rows;
352 split_ea.addr_count = 1;
353 }
354 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
355 {
356 split_ea.line2 = opt->jo_term_cols;
357 split_ea.addr_count = 1;
358 }
359
360 ex_splitview(&split_ea);
361 if (curwin == old_curwin)
362 {
363 /* split failed */
364 vim_free(term);
365 return NULL;
366 }
367 }
368 term->tl_buffer = curbuf;
369 curbuf->b_term = term;
370
371 if (!opt->jo_hidden)
372 {
373 /* only one size was taken care of with :new, do the other one */
374 if (opt->jo_term_rows > 0 && (cmdmod.split & WSP_VERT))
375 win_setheight(opt->jo_term_rows);
376 if (opt->jo_term_cols > 0 && !(cmdmod.split & WSP_VERT))
377 win_setwidth(opt->jo_term_cols);
378 }
379
380 /* Link the new terminal in the list of active terminals. */
381 term->tl_next = first_term;
382 first_term = term;
383
384 if (opt->jo_term_name != NULL)
385 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
386 else
387 {
388 int i;
389 size_t len;
390 char_u *cmd, *p;
391
392 if (argvar->v_type == VAR_STRING)
393 {
394 cmd = argvar->vval.v_string;
395 if (cmd == NULL)
396 cmd = (char_u *)"";
397 else if (STRCMP(cmd, "NONE") == 0)
398 cmd = (char_u *)"pty";
399 }
400 else if (argvar->v_type != VAR_LIST
401 || argvar->vval.v_list == NULL
402 || argvar->vval.v_list->lv_len < 1
403 || (cmd = get_tv_string_chk(
404 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
405 cmd = (char_u*)"";
406
407 len = STRLEN(cmd) + 10;
408 p = alloc((int)len);
409
410 for (i = 0; p != NULL; ++i)
411 {
412 /* Prepend a ! to the command name to avoid the buffer name equals
413 * the executable, otherwise ":w!" would overwrite it. */
414 if (i == 0)
415 vim_snprintf((char *)p, len, "!%s", cmd);
416 else
417 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
418 if (buflist_findname(p) == NULL)
419 {
420 vim_free(curbuf->b_ffname);
421 curbuf->b_ffname = p;
422 break;
423 }
424 }
425 }
426 curbuf->b_fname = curbuf->b_ffname;
427
428 if (opt->jo_term_opencmd != NULL)
429 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
430
431 if (opt->jo_eof_chars != NULL)
432 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
433
434 set_string_option_direct((char_u *)"buftype", -1,
435 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
436
437 /* Mark the buffer as not modifiable. It can only be made modifiable after
438 * the job finished. */
439 curbuf->b_p_ma = FALSE;
440
441 set_term_and_win_size(term);
442 setup_job_options(opt, term->tl_rows, term->tl_cols);
443
444 /* System dependent: setup the vterm and maybe start the job in it. */
445 if (argvar->v_type == VAR_STRING
446 && argvar->vval.v_string != NULL
447 && STRCMP(argvar->vval.v_string, "NONE") == 0)
448 res = create_pty_only(term, opt);
449 else
450 res = term_and_job_init(term, argvar, opt);
451
452 newbuf = curbuf;
453 if (res == OK)
454 {
455 /* Get and remember the size we ended up with. Update the pty. */
456 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
457 term_report_winsize(term, term->tl_rows, term->tl_cols);
458
459 /* Make sure we don't get stuck on sending keys to the job, it leads to
460 * a deadlock if the job is waiting for Vim to read. */
461 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
462
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200463#ifdef FEAT_AUTOCMD
464 ++curbuf->b_locked;
465 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
466 --curbuf->b_locked;
467#endif
468
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 if (old_curbuf != NULL)
470 {
471 --curbuf->b_nwindows;
472 curbuf = old_curbuf;
473 curwin->w_buffer = curbuf;
474 ++curbuf->b_nwindows;
475 }
476 }
477 else
478 {
479 buf_T *buf = curbuf;
480
481 free_terminal(curbuf);
482 if (old_curbuf != NULL)
483 {
484 --curbuf->b_nwindows;
485 curbuf = old_curbuf;
486 curwin->w_buffer = curbuf;
487 ++curbuf->b_nwindows;
488 }
489
490 /* Wiping out the buffer will also close the window and call
491 * free_terminal(). */
492 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
493 return NULL;
494 }
495 return newbuf;
496}
497
498/*
499 * ":terminal": open a terminal window and execute a job in it.
500 */
501 void
502ex_terminal(exarg_T *eap)
503{
504 typval_T argvar[2];
505 jobopt_T opt;
506 char_u *cmd;
507 char_u *tofree = NULL;
508
509 init_job_options(&opt);
510
511 cmd = eap->arg;
512 while (*cmd && *cmd == '+' && *(cmd + 1) == '+')
513 {
514 char_u *p, *ep;
515
516 cmd += 2;
517 p = skiptowhite(cmd);
518 ep = vim_strchr(cmd, '=');
519 if (ep != NULL && ep < p)
520 p = ep;
521
522 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
523 opt.jo_term_finish = 'c';
524 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
525 opt.jo_term_finish = 'o';
526 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
527 opt.jo_curwin = 1;
528 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
529 opt.jo_hidden = 1;
530 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
531 && ep != NULL && isdigit(ep[1]))
532 {
533 opt.jo_set2 |= JO2_TERM_ROWS;
534 opt.jo_term_rows = atoi((char *)ep + 1);
535 p = skiptowhite(cmd);
536 }
537 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
538 && ep != NULL && isdigit(ep[1]))
539 {
540 opt.jo_set2 |= JO2_TERM_COLS;
541 opt.jo_term_cols = atoi((char *)ep + 1);
542 p = skiptowhite(cmd);
543 }
544 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
545 && ep != NULL)
546 {
547 char_u *buf = NULL;
548 char_u *keys;
549
550 p = skiptowhite(cmd);
551 *p = NUL;
552 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
553 opt.jo_set2 |= JO2_EOF_CHARS;
554 opt.jo_eof_chars = vim_strsave(keys);
555 vim_free(buf);
556 *p = ' ';
557 }
558 else
559 {
560 if (*p)
561 *p = NUL;
562 EMSG2(_("E181: Invalid attribute: %s"), cmd);
563 return;
564 }
565 cmd = skipwhite(p);
566 }
567 if (*cmd == NUL)
568 /* Make a copy of 'shell', an autocommand may change the option. */
569 tofree = cmd = vim_strsave(p_sh);
570
571 if (eap->addr_count > 0)
572 {
573 /* Write lines from current buffer to the job. */
574 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
575 opt.jo_io[PART_IN] = JIO_BUFFER;
576 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
577 opt.jo_in_top = eap->line1;
578 opt.jo_in_bot = eap->line2;
579 }
580
581 argvar[0].v_type = VAR_STRING;
582 argvar[0].vval.v_string = cmd;
583 argvar[1].v_type = VAR_UNKNOWN;
584 term_start(argvar, &opt, eap->forceit);
585 vim_free(tofree);
586 vim_free(opt.jo_eof_chars);
587}
588
589/*
590 * Free the scrollback buffer for "term".
591 */
592 static void
593free_scrollback(term_T *term)
594{
595 int i;
596
597 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
598 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
599 ga_clear(&term->tl_scrollback);
600}
601
602/*
603 * Free a terminal and everything it refers to.
604 * Kills the job if there is one.
605 * Called when wiping out a buffer.
606 */
607 void
608free_terminal(buf_T *buf)
609{
610 term_T *term = buf->b_term;
611 term_T *tp;
612
613 if (term == NULL)
614 return;
615 if (first_term == term)
616 first_term = term->tl_next;
617 else
618 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
619 if (tp->tl_next == term)
620 {
621 tp->tl_next = term->tl_next;
622 break;
623 }
624
625 if (term->tl_job != NULL)
626 {
627 if (term->tl_job->jv_status != JOB_ENDED
628 && term->tl_job->jv_status != JOB_FINISHED
629 && term->tl_job->jv_status != JOB_FAILED)
630 job_stop(term->tl_job, NULL, "kill");
631 job_unref(term->tl_job);
632 }
633
634 free_scrollback(term);
635
636 term_free_vterm(term);
637 vim_free(term->tl_title);
638 vim_free(term->tl_status_text);
639 vim_free(term->tl_opencmd);
640 vim_free(term->tl_eof_chars);
641 vim_free(term->tl_cursor_color);
642 vim_free(term);
643 buf->b_term = NULL;
644 if (in_terminal_loop == term)
645 in_terminal_loop = NULL;
646}
647
648/*
649 * Write job output "msg[len]" to the vterm.
650 */
651 static void
652term_write_job_output(term_T *term, char_u *msg, size_t len)
653{
654 VTerm *vterm = term->tl_vterm;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200655
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100656 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657
658 /* this invokes the damage callbacks */
659 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
660}
661
662 static void
663update_cursor(term_T *term, int redraw)
664{
665 if (term->tl_normal_mode)
666 return;
667 setcursor();
668 if (redraw)
669 {
670 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
671 cursor_on();
672 out_flush();
673#ifdef FEAT_GUI
674 if (gui.in_use)
675 gui_update_cursor(FALSE, FALSE);
676#endif
677 }
678}
679
680/*
681 * Invoked when "msg" output from a job was received. Write it to the terminal
682 * of "buffer".
683 */
684 void
685write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
686{
687 size_t len = STRLEN(msg);
688 term_T *term = buffer->b_term;
689
690 if (term->tl_vterm == NULL)
691 {
692 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
693 return;
694 }
695 ch_log(channel, "writing %d bytes to terminal", (int)len);
696 term_write_job_output(term, msg, len);
697
698 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
699 * contents, thus no screen update is needed. */
700 if (!term->tl_normal_mode)
701 {
702 /* TODO: only update once in a while. */
703 ch_log(term->tl_job->jv_channel, "updating screen");
704 if (buffer == curbuf)
705 {
706 update_screen(0);
707 update_cursor(term, TRUE);
708 }
709 else
710 redraw_after_callback(TRUE);
711 }
712}
713
714/*
715 * Send a mouse position and click to the vterm
716 */
717 static int
718term_send_mouse(VTerm *vterm, int button, int pressed)
719{
720 VTermModifier mod = VTERM_MOD_NONE;
721
722 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200723 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100724 if (button != 0)
725 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200726 return TRUE;
727}
728
729/*
730 * Convert typed key "c" into bytes to send to the job.
731 * Return the number of bytes in "buf".
732 */
733 static int
734term_convert_key(term_T *term, int c, char *buf)
735{
736 VTerm *vterm = term->tl_vterm;
737 VTermKey key = VTERM_KEY_NONE;
738 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100739 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200740
741 switch (c)
742 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100743 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
744
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 /* don't use VTERM_KEY_BACKSPACE, it always
746 * becomes 0x7f DEL */
747 case K_BS: c = term_backspace_char; break;
748
749 case ESC: key = VTERM_KEY_ESCAPE; break;
750 case K_DEL: key = VTERM_KEY_DEL; break;
751 case K_DOWN: key = VTERM_KEY_DOWN; break;
752 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
753 key = VTERM_KEY_DOWN; break;
754 case K_END: key = VTERM_KEY_END; break;
755 case K_S_END: mod = VTERM_MOD_SHIFT;
756 key = VTERM_KEY_END; break;
757 case K_C_END: mod = VTERM_MOD_CTRL;
758 key = VTERM_KEY_END; break;
759 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
760 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
761 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
762 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
763 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
764 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
765 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
766 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
767 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
768 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
769 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
770 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
771 case K_HOME: key = VTERM_KEY_HOME; break;
772 case K_S_HOME: mod = VTERM_MOD_SHIFT;
773 key = VTERM_KEY_HOME; break;
774 case K_C_HOME: mod = VTERM_MOD_CTRL;
775 key = VTERM_KEY_HOME; break;
776 case K_INS: key = VTERM_KEY_INS; break;
777 case K_K0: key = VTERM_KEY_KP_0; break;
778 case K_K1: key = VTERM_KEY_KP_1; break;
779 case K_K2: key = VTERM_KEY_KP_2; break;
780 case K_K3: key = VTERM_KEY_KP_3; break;
781 case K_K4: key = VTERM_KEY_KP_4; break;
782 case K_K5: key = VTERM_KEY_KP_5; break;
783 case K_K6: key = VTERM_KEY_KP_6; break;
784 case K_K7: key = VTERM_KEY_KP_7; break;
785 case K_K8: key = VTERM_KEY_KP_8; break;
786 case K_K9: key = VTERM_KEY_KP_9; break;
787 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
788 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
789 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
790 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
791 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
792 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
793 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
794 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
795 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
796 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
797 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
798 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
799 case K_LEFT: key = VTERM_KEY_LEFT; break;
800 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
801 key = VTERM_KEY_LEFT; break;
802 case K_C_LEFT: mod = VTERM_MOD_CTRL;
803 key = VTERM_KEY_LEFT; break;
804 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
805 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
806 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
807 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
808 key = VTERM_KEY_RIGHT; break;
809 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
810 key = VTERM_KEY_RIGHT; break;
811 case K_UP: key = VTERM_KEY_UP; break;
812 case K_S_UP: mod = VTERM_MOD_SHIFT;
813 key = VTERM_KEY_UP; break;
814 case TAB: key = VTERM_KEY_TAB; break;
815
Bram Moolenaara42ad572017-11-16 13:08:04 +0100816 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
817 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818 case K_MOUSELEFT: /* TODO */ return 0;
819 case K_MOUSERIGHT: /* TODO */ return 0;
820
821 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100822 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
823 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100825 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100826 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100827 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
828 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
829 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
830 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
831 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
832 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 case K_X1MOUSE: /* TODO */ return 0;
834 case K_X1DRAG: /* TODO */ return 0;
835 case K_X1RELEASE: /* TODO */ return 0;
836 case K_X2MOUSE: /* TODO */ return 0;
837 case K_X2DRAG: /* TODO */ return 0;
838 case K_X2RELEASE: /* TODO */ return 0;
839
840 case K_IGNORE: return 0;
841 case K_NOP: return 0;
842 case K_UNDO: return 0;
843 case K_HELP: return 0;
844 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
845 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
846 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
847 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
848 case K_SELECT: return 0;
849#ifdef FEAT_GUI
850 case K_VER_SCROLLBAR: return 0;
851 case K_HOR_SCROLLBAR: return 0;
852#endif
853#ifdef FEAT_GUI_TABLINE
854 case K_TABLINE: return 0;
855 case K_TABMENU: return 0;
856#endif
857#ifdef FEAT_NETBEANS_INTG
858 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
859#endif
860#ifdef FEAT_DND
861 case K_DROP: return 0;
862#endif
863#ifdef FEAT_AUTOCMD
864 case K_CURSORHOLD: return 0;
865#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100866 case K_PS: vterm_keyboard_start_paste(vterm);
867 other = TRUE;
868 break;
869 case K_PE: vterm_keyboard_end_paste(vterm);
870 other = TRUE;
871 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200872 }
873
874 /*
875 * Convert special keys to vterm keys:
876 * - Write keys to vterm: vterm_keyboard_key()
877 * - Write output to channel.
878 * TODO: use mod_mask
879 */
880 if (key != VTERM_KEY_NONE)
881 /* Special key, let vterm convert it. */
882 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100883 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 /* Normal character, let vterm convert it. */
885 vterm_keyboard_unichar(vterm, c, mod);
886
887 /* Read back the converted escape sequence. */
888 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
889}
890
891/*
892 * Return TRUE if the job for "term" is still running.
893 */
894 int
895term_job_running(term_T *term)
896{
897 /* Also consider the job finished when the channel is closed, to avoid a
898 * race condition when updating the title. */
899 return term != NULL
900 && term->tl_job != NULL
901 && channel_is_open(term->tl_job->jv_channel)
902 && (term->tl_job->jv_status == JOB_STARTED
903 || term->tl_job->jv_channel->ch_keep_open);
904}
905
906/*
907 * Return TRUE if "term" has an active channel and used ":term NONE".
908 */
909 int
910term_none_open(term_T *term)
911{
912 /* Also consider the job finished when the channel is closed, to avoid a
913 * race condition when updating the title. */
914 return term != NULL
915 && term->tl_job != NULL
916 && channel_is_open(term->tl_job->jv_channel)
917 && term->tl_job->jv_channel->ch_keep_open;
918}
919
920/*
921 * Add the last line of the scrollback buffer to the buffer in the window.
922 */
923 static void
924add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
925{
926 buf_T *buf = term->tl_buffer;
927 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
928 linenr_T lnum = buf->b_ml.ml_line_count;
929
930#ifdef WIN3264
931 if (!enc_utf8 && enc_codepage > 0)
932 {
933 WCHAR *ret = NULL;
934 int length = 0;
935
936 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
937 &ret, &length);
938 if (ret != NULL)
939 {
940 WideCharToMultiByte_alloc(enc_codepage, 0,
941 ret, length, (char **)&text, &len, 0, 0);
942 vim_free(ret);
943 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
944 vim_free(text);
945 }
946 }
947 else
948#endif
949 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
950 if (empty)
951 {
952 /* Delete the empty line that was in the empty buffer. */
953 curbuf = buf;
954 ml_delete(1, FALSE);
955 curbuf = curwin->w_buffer;
956 }
957}
958
959 static void
960cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
961{
962 attr->width = cell->width;
963 attr->attrs = cell->attrs;
964 attr->fg = cell->fg;
965 attr->bg = cell->bg;
966}
967
968 static int
969equal_celattr(cellattr_T *a, cellattr_T *b)
970{
971 /* Comparing the colors should be sufficient. */
972 return a->fg.red == b->fg.red
973 && a->fg.green == b->fg.green
974 && a->fg.blue == b->fg.blue
975 && a->bg.red == b->bg.red
976 && a->bg.green == b->bg.green
977 && a->bg.blue == b->bg.blue;
978}
979
980
981/*
982 * Add the current lines of the terminal to scrollback and to the buffer.
983 * Called after the job has ended and when switching to Terminal-Normal mode.
984 */
985 static void
986move_terminal_to_buffer(term_T *term)
987{
988 win_T *wp;
989 int len;
990 int lines_skipped = 0;
991 VTermPos pos;
992 VTermScreenCell cell;
993 cellattr_T fill_attr, new_fill_attr;
994 cellattr_T *p;
995 VTermScreen *screen;
996
997 if (term->tl_vterm == NULL)
998 return;
999 screen = vterm_obtain_screen(term->tl_vterm);
1000 fill_attr = new_fill_attr = term->tl_default_color;
1001
1002 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1003 {
1004 len = 0;
1005 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1006 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1007 && cell.chars[0] != NUL)
1008 {
1009 len = pos.col + 1;
1010 new_fill_attr = term->tl_default_color;
1011 }
1012 else
1013 /* Assume the last attr is the filler attr. */
1014 cell2cellattr(&cell, &new_fill_attr);
1015
1016 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1017 ++lines_skipped;
1018 else
1019 {
1020 while (lines_skipped > 0)
1021 {
1022 /* Line was skipped, add an empty line. */
1023 --lines_skipped;
1024 if (ga_grow(&term->tl_scrollback, 1) == OK)
1025 {
1026 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1027 + term->tl_scrollback.ga_len;
1028
1029 line->sb_cols = 0;
1030 line->sb_cells = NULL;
1031 line->sb_fill_attr = fill_attr;
1032 ++term->tl_scrollback.ga_len;
1033
1034 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1035 }
1036 }
1037
1038 if (len == 0)
1039 p = NULL;
1040 else
1041 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1042 if ((p != NULL || len == 0)
1043 && ga_grow(&term->tl_scrollback, 1) == OK)
1044 {
1045 garray_T ga;
1046 int width;
1047 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1048 + term->tl_scrollback.ga_len;
1049
1050 ga_init2(&ga, 1, 100);
1051 for (pos.col = 0; pos.col < len; pos.col += width)
1052 {
1053 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1054 {
1055 width = 1;
1056 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1057 if (ga_grow(&ga, 1) == OK)
1058 ga.ga_len += utf_char2bytes(' ',
1059 (char_u *)ga.ga_data + ga.ga_len);
1060 }
1061 else
1062 {
1063 width = cell.width;
1064
1065 cell2cellattr(&cell, &p[pos.col]);
1066
1067 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1068 {
1069 int i;
1070 int c;
1071
1072 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1073 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1074 (char_u *)ga.ga_data + ga.ga_len);
1075 }
1076 }
1077 }
1078 line->sb_cols = len;
1079 line->sb_cells = p;
1080 line->sb_fill_attr = new_fill_attr;
1081 fill_attr = new_fill_attr;
1082 ++term->tl_scrollback.ga_len;
1083
1084 if (ga_grow(&ga, 1) == FAIL)
1085 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1086 else
1087 {
1088 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1089 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1090 }
1091 ga_clear(&ga);
1092 }
1093 else
1094 vim_free(p);
1095 }
1096 }
1097
1098 /* Obtain the current background color. */
1099 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1100 &term->tl_default_color.fg, &term->tl_default_color.bg);
1101
1102 FOR_ALL_WINDOWS(wp)
1103 {
1104 if (wp->w_buffer == term->tl_buffer)
1105 {
1106 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1107 wp->w_cursor.col = 0;
1108 wp->w_valid = 0;
1109 if (wp->w_cursor.lnum >= wp->w_height)
1110 {
1111 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1112
1113 if (wp->w_topline < min_topline)
1114 wp->w_topline = min_topline;
1115 }
1116 redraw_win_later(wp, NOT_VALID);
1117 }
1118 }
1119}
1120
1121 static void
1122set_terminal_mode(term_T *term, int normal_mode)
1123{
1124 term->tl_normal_mode = normal_mode;
1125 vim_free(term->tl_status_text);
1126 term->tl_status_text = NULL;
1127 if (term->tl_buffer == curbuf)
1128 maketitle();
1129}
1130
1131/*
1132 * Called after the job if finished and Terminal mode is not active:
1133 * Move the vterm contents into the scrollback buffer and free the vterm.
1134 */
1135 static void
1136cleanup_vterm(term_T *term)
1137{
1138 if (term->tl_finish != 'c')
1139 move_terminal_to_buffer(term);
1140 term_free_vterm(term);
1141 set_terminal_mode(term, FALSE);
1142}
1143
1144/*
1145 * Switch from Terminal-Job mode to Terminal-Normal mode.
1146 * Suspends updating the terminal window.
1147 */
1148 static void
1149term_enter_normal_mode(void)
1150{
1151 term_T *term = curbuf->b_term;
1152
1153 /* Append the current terminal contents to the buffer. */
1154 move_terminal_to_buffer(term);
1155
1156 set_terminal_mode(term, TRUE);
1157
1158 /* Move the window cursor to the position of the cursor in the
1159 * terminal. */
1160 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1161 + term->tl_cursor_pos.row + 1;
1162 check_cursor();
1163 coladvance(term->tl_cursor_pos.col);
1164
1165 /* Display the same lines as in the terminal. */
1166 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1167}
1168
1169/*
1170 * Returns TRUE if the current window contains a terminal and we are in
1171 * Terminal-Normal mode.
1172 */
1173 int
1174term_in_normal_mode(void)
1175{
1176 term_T *term = curbuf->b_term;
1177
1178 return term != NULL && term->tl_normal_mode;
1179}
1180
1181/*
1182 * Switch from Terminal-Normal mode to Terminal-Job mode.
1183 * Restores updating the terminal window.
1184 */
1185 void
1186term_enter_job_mode()
1187{
1188 term_T *term = curbuf->b_term;
1189 sb_line_T *line;
1190 garray_T *gap;
1191
1192 /* Remove the terminal contents from the scrollback and the buffer. */
1193 gap = &term->tl_scrollback;
1194 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1195 && gap->ga_len > 0)
1196 {
1197 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1198 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1199 vim_free(line->sb_cells);
1200 --gap->ga_len;
1201 }
1202 check_cursor();
1203
1204 set_terminal_mode(term, FALSE);
1205
1206 if (term->tl_channel_closed)
1207 cleanup_vterm(term);
1208 redraw_buf_and_status_later(curbuf, NOT_VALID);
1209}
1210
1211/*
1212 * Get a key from the user without mapping.
1213 * Note: while waiting a terminal may be closed and freed if the channel is
1214 * closed and ++close was used.
1215 * Uses terminal mode mappings.
1216 */
1217 static int
1218term_vgetc()
1219{
1220 int c;
1221 int save_State = State;
1222
1223 State = TERMINAL;
1224 got_int = FALSE;
1225#ifdef WIN3264
1226 ctrl_break_was_pressed = FALSE;
1227#endif
1228 c = vgetc();
1229 got_int = FALSE;
1230 State = save_State;
1231 return c;
1232}
1233
1234/*
1235 * Get the part that is connected to the tty. Normally this is PART_IN, but
1236 * when writing buffer lines to the job it can be another. This makes it
1237 * possible to do "1,5term vim -".
1238 */
1239 static ch_part_T
1240get_tty_part(term_T *term)
1241{
1242#ifdef UNIX
1243 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1244 int i;
1245
1246 for (i = 0; i < 3; ++i)
1247 {
1248 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1249
1250 if (isatty(fd))
1251 return parts[i];
1252 }
1253#endif
1254 return PART_IN;
1255}
1256
1257/*
1258 * Send keys to terminal.
1259 * Return FAIL when the key needs to be handled in Normal mode.
1260 * Return OK when the key was dropped or sent to the terminal.
1261 */
1262 int
1263send_keys_to_term(term_T *term, int c, int typed)
1264{
1265 char msg[KEY_BUF_LEN];
1266 size_t len;
1267 static int mouse_was_outside = FALSE;
1268 int dragging_outside = FALSE;
1269
1270 /* Catch keys that need to be handled as in Normal mode. */
1271 switch (c)
1272 {
1273 case NUL:
1274 case K_ZERO:
1275 if (typed)
1276 stuffcharReadbuff(c);
1277 return FAIL;
1278
1279 case K_IGNORE:
1280 return FAIL;
1281
1282 case K_LEFTDRAG:
1283 case K_MIDDLEDRAG:
1284 case K_RIGHTDRAG:
1285 case K_X1DRAG:
1286 case K_X2DRAG:
1287 dragging_outside = mouse_was_outside;
1288 /* FALLTHROUGH */
1289 case K_LEFTMOUSE:
1290 case K_LEFTMOUSE_NM:
1291 case K_LEFTRELEASE:
1292 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001293 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 case K_MIDDLEMOUSE:
1295 case K_MIDDLERELEASE:
1296 case K_RIGHTMOUSE:
1297 case K_RIGHTRELEASE:
1298 case K_X1MOUSE:
1299 case K_X1RELEASE:
1300 case K_X2MOUSE:
1301 case K_X2RELEASE:
1302
1303 case K_MOUSEUP:
1304 case K_MOUSEDOWN:
1305 case K_MOUSELEFT:
1306 case K_MOUSERIGHT:
1307 if (mouse_row < W_WINROW(curwin)
Bram Moolenaar73675fb2017-11-20 21:49:19 +01001308 || mouse_row > (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001309 || mouse_col < curwin->w_wincol
Bram Moolenaar73675fb2017-11-20 21:49:19 +01001310 || mouse_col > W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001311 || dragging_outside)
1312 {
1313 /* click or scroll outside the current window */
1314 if (typed)
1315 {
1316 stuffcharReadbuff(c);
1317 mouse_was_outside = TRUE;
1318 }
1319 return FAIL;
1320 }
1321 }
1322 if (typed)
1323 mouse_was_outside = FALSE;
1324
1325 /* Convert the typed key to a sequence of bytes for the job. */
1326 len = term_convert_key(term, c, msg);
1327 if (len > 0)
1328 /* TODO: if FAIL is returned, stop? */
1329 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1330 (char_u *)msg, (int)len, NULL);
1331
1332 return OK;
1333}
1334
1335 static void
1336position_cursor(win_T *wp, VTermPos *pos)
1337{
1338 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1339 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1340 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1341}
1342
1343/*
1344 * Handle CTRL-W "": send register contents to the job.
1345 */
1346 static void
1347term_paste_register(int prev_c UNUSED)
1348{
1349 int c;
1350 list_T *l;
1351 listitem_T *item;
1352 long reglen = 0;
1353 int type;
1354
1355#ifdef FEAT_CMDL_INFO
1356 if (add_to_showcmd(prev_c))
1357 if (add_to_showcmd('"'))
1358 out_flush();
1359#endif
1360 c = term_vgetc();
1361#ifdef FEAT_CMDL_INFO
1362 clear_showcmd();
1363#endif
1364 if (!term_use_loop())
1365 /* job finished while waiting for a character */
1366 return;
1367
1368 /* CTRL-W "= prompt for expression to evaluate. */
1369 if (c == '=' && get_expr_register() != '=')
1370 return;
1371 if (!term_use_loop())
1372 /* job finished while waiting for a character */
1373 return;
1374
1375 l = (list_T *)get_reg_contents(c, GREG_LIST);
1376 if (l != NULL)
1377 {
1378 type = get_reg_type(c, &reglen);
1379 for (item = l->lv_first; item != NULL; item = item->li_next)
1380 {
1381 char_u *s = get_tv_string(&item->li_tv);
1382#ifdef WIN3264
1383 char_u *tmp = s;
1384
1385 if (!enc_utf8 && enc_codepage > 0)
1386 {
1387 WCHAR *ret = NULL;
1388 int length = 0;
1389
1390 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1391 (int)STRLEN(s), &ret, &length);
1392 if (ret != NULL)
1393 {
1394 WideCharToMultiByte_alloc(CP_UTF8, 0,
1395 ret, length, (char **)&s, &length, 0, 0);
1396 vim_free(ret);
1397 }
1398 }
1399#endif
1400 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1401 s, (int)STRLEN(s), NULL);
1402#ifdef WIN3264
1403 if (tmp != s)
1404 vim_free(s);
1405#endif
1406
1407 if (item->li_next != NULL || type == MLINE)
1408 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1409 (char_u *)"\r", 1, NULL);
1410 }
1411 list_free(l);
1412 }
1413}
1414
1415#if defined(FEAT_GUI) || defined(PROTO)
1416/*
1417 * Return TRUE when the cursor of the terminal should be displayed.
1418 */
1419 int
1420terminal_is_active()
1421{
1422 return in_terminal_loop != NULL;
1423}
1424
1425 cursorentry_T *
1426term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1427{
1428 term_T *term = in_terminal_loop;
1429 static cursorentry_T entry;
1430
1431 vim_memset(&entry, 0, sizeof(entry));
1432 entry.shape = entry.mshape =
1433 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1434 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1435 SHAPE_BLOCK;
1436 entry.percentage = 20;
1437 if (term->tl_cursor_blink)
1438 {
1439 entry.blinkwait = 700;
1440 entry.blinkon = 400;
1441 entry.blinkoff = 250;
1442 }
1443 *fg = gui.back_pixel;
1444 if (term->tl_cursor_color == NULL)
1445 *bg = gui.norm_pixel;
1446 else
1447 *bg = color_name2handle(term->tl_cursor_color);
1448 entry.name = "n";
1449 entry.used_for = SHAPE_CURSOR;
1450
1451 return &entry;
1452}
1453#endif
1454
1455static int did_change_cursor = FALSE;
1456
1457 static void
1458may_set_cursor_props(term_T *term)
1459{
1460#ifdef FEAT_GUI
1461 /* For the GUI the cursor properties are obtained with
1462 * term_get_cursor_shape(). */
1463 if (gui.in_use)
1464 return;
1465#endif
1466 if (in_terminal_loop == term)
1467 {
1468 did_change_cursor = TRUE;
1469 if (term->tl_cursor_color != NULL)
1470 term_cursor_color(term->tl_cursor_color);
1471 else
1472 term_cursor_color((char_u *)"");
1473 term_cursor_shape(term->tl_cursor_shape, term->tl_cursor_blink);
1474 }
1475}
1476
1477 static void
1478may_restore_cursor_props(void)
1479{
1480#ifdef FEAT_GUI
1481 if (gui.in_use)
1482 return;
1483#endif
1484 if (did_change_cursor)
1485 {
1486 did_change_cursor = FALSE;
1487 term_cursor_color((char_u *)"");
1488 /* this will restore the initial cursor style, if possible */
1489 ui_cursor_shape_forced(TRUE);
1490 }
1491}
1492
1493/*
1494 * Returns TRUE if the current window contains a terminal and we are sending
1495 * keys to the job.
1496 */
1497 int
1498term_use_loop(void)
1499{
1500 term_T *term = curbuf->b_term;
1501
1502 return term != NULL
1503 && !term->tl_normal_mode
1504 && term->tl_vterm != NULL
1505 && term_job_running(term);
1506}
1507
1508/*
1509 * Wait for input and send it to the job.
1510 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1511 * when there is no more typahead.
1512 * Return when the start of a CTRL-W command is typed or anything else that
1513 * should be handled as a Normal mode command.
1514 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1515 * the terminal was closed.
1516 */
1517 int
1518terminal_loop(int blocking)
1519{
1520 int c;
1521 int termkey = 0;
1522 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001523#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001524 int tty_fd = curbuf->b_term->tl_job->jv_channel
1525 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001526#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001527
1528 /* Remember the terminal we are sending keys to. However, the terminal
1529 * might be closed while waiting for a character, e.g. typing "exit" in a
1530 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1531 * stored reference. */
1532 in_terminal_loop = curbuf->b_term;
1533
1534 if (*curwin->w_p_tk != NUL)
1535 termkey = string_to_key(curwin->w_p_tk, TRUE);
1536 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1537 may_set_cursor_props(curbuf->b_term);
1538
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001539 while (blocking || vpeekc() != NUL)
1540 {
1541 /* TODO: skip screen update when handling a sequence of keys. */
1542 /* Repeat redrawing in case a message is received while redrawing. */
1543 while (must_redraw != 0)
1544 if (update_screen(0) == FAIL)
1545 break;
1546 update_cursor(curbuf->b_term, FALSE);
1547
1548 c = term_vgetc();
1549 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001550 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001551 /* Job finished while waiting for a character. Push back the
1552 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001553 if (c != K_IGNORE)
1554 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001556 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001557 if (c == K_IGNORE)
1558 continue;
1559
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001560#ifdef UNIX
1561 /*
1562 * The shell or another program may change the tty settings. Getting
1563 * them for every typed character is a bit of overhead, but it's needed
1564 * for the first character typed, e.g. when Vim starts in a shell.
1565 */
1566 if (isatty(tty_fd))
1567 {
1568 ttyinfo_T info;
1569
1570 /* Get the current backspace character of the pty. */
1571 if (get_tty_info(tty_fd, &info) == OK)
1572 term_backspace_char = info.backspace;
1573 }
1574#endif
1575
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576#ifdef WIN3264
1577 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1578 * Use CTRL-BREAK to kill the job. */
1579 if (ctrl_break_was_pressed)
1580 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1581#endif
1582 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1583 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1584 {
1585 int prev_c = c;
1586
1587#ifdef FEAT_CMDL_INFO
1588 if (add_to_showcmd(c))
1589 out_flush();
1590#endif
1591 c = term_vgetc();
1592#ifdef FEAT_CMDL_INFO
1593 clear_showcmd();
1594#endif
1595 if (!term_use_loop())
1596 /* job finished while waiting for a character */
1597 break;
1598
1599 if (prev_c == Ctrl_BSL)
1600 {
1601 if (c == Ctrl_N)
1602 {
1603 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1604 term_enter_normal_mode();
1605 ret = FAIL;
1606 goto theend;
1607 }
1608 /* Send both keys to the terminal. */
1609 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1610 }
1611 else if (c == Ctrl_C)
1612 {
1613 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1614 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1615 }
1616 else if (termkey == 0 && c == '.')
1617 {
1618 /* "CTRL-W .": send CTRL-W to the job */
1619 c = Ctrl_W;
1620 }
1621 else if (c == 'N')
1622 {
1623 /* CTRL-W N : go to Terminal-Normal mode. */
1624 term_enter_normal_mode();
1625 ret = FAIL;
1626 goto theend;
1627 }
1628 else if (c == '"')
1629 {
1630 term_paste_register(prev_c);
1631 continue;
1632 }
1633 else if (termkey == 0 || c != termkey)
1634 {
1635 stuffcharReadbuff(Ctrl_W);
1636 stuffcharReadbuff(c);
1637 ret = OK;
1638 goto theend;
1639 }
1640 }
1641# ifdef WIN3264
1642 if (!enc_utf8 && has_mbyte && c >= 0x80)
1643 {
1644 WCHAR wc;
1645 char_u mb[3];
1646
1647 mb[0] = (unsigned)c >> 8;
1648 mb[1] = c;
1649 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1650 c = wc;
1651 }
1652# endif
1653 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1654 {
1655 ret = OK;
1656 goto theend;
1657 }
1658 }
1659 ret = FAIL;
1660
1661theend:
1662 in_terminal_loop = NULL;
1663 may_restore_cursor_props();
1664 return ret;
1665}
1666
1667/*
1668 * Called when a job has finished.
1669 * This updates the title and status, but does not close the vterm, because
1670 * there might still be pending output in the channel.
1671 */
1672 void
1673term_job_ended(job_T *job)
1674{
1675 term_T *term;
1676 int did_one = FALSE;
1677
1678 for (term = first_term; term != NULL; term = term->tl_next)
1679 if (term->tl_job == job)
1680 {
1681 vim_free(term->tl_title);
1682 term->tl_title = NULL;
1683 vim_free(term->tl_status_text);
1684 term->tl_status_text = NULL;
1685 redraw_buf_and_status_later(term->tl_buffer, VALID);
1686 did_one = TRUE;
1687 }
1688 if (did_one)
1689 redraw_statuslines();
1690 if (curbuf->b_term != NULL)
1691 {
1692 if (curbuf->b_term->tl_job == job)
1693 maketitle();
1694 update_cursor(curbuf->b_term, TRUE);
1695 }
1696}
1697
1698 static void
1699may_toggle_cursor(term_T *term)
1700{
1701 if (in_terminal_loop == term)
1702 {
1703 if (term->tl_cursor_visible)
1704 cursor_on();
1705 else
1706 cursor_off();
1707 }
1708}
1709
1710/*
1711 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001712 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 */
1714 static int
1715color2index(VTermColor *color, int fg, int *boldp)
1716{
1717 int red = color->red;
1718 int blue = color->blue;
1719 int green = color->green;
1720
Bram Moolenaar46359e12017-11-29 22:33:38 +01001721 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001722 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001723 /* First 16 colors and default: use the ANSI index, because these
1724 * colors can be redefined. */
1725 if (t_colors >= 16)
1726 return color->ansi_index;
1727 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001728 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001729 case 0: return 0;
1730 case 1: return lookup_color( 0, fg, boldp) + 1;
1731 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1732 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1733 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1734 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1735 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1736 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1737 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1738 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1739 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1740 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1741 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1742 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1743 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1744 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1745 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 }
1747 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001748
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001749 if (t_colors >= 256)
1750 {
1751 if (red == blue && red == green)
1752 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001753 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001755 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1756 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1757 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001758 int i;
1759
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001760 if (red < 5)
1761 return 17; /* 00/00/00 */
1762 if (red > 245) /* ff/ff/ff */
1763 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 for (i = 0; i < 23; ++i)
1765 if (red < cutoff[i])
1766 return i + 233;
1767 return 256;
1768 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001769 {
1770 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1771 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001773 /* 216-color cube */
1774 for (ri = 0; ri < 5; ++ri)
1775 if (red < cutoff[ri])
1776 break;
1777 for (gi = 0; gi < 5; ++gi)
1778 if (green < cutoff[gi])
1779 break;
1780 for (bi = 0; bi < 5; ++bi)
1781 if (blue < cutoff[bi])
1782 break;
1783 return 17 + ri * 36 + gi * 6 + bi;
1784 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001785 }
1786 return 0;
1787}
1788
1789/*
1790 * Convert the attributes of a vterm cell into an attribute index.
1791 */
1792 static int
1793cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1794{
1795 int attr = 0;
1796
1797 if (cellattrs.bold)
1798 attr |= HL_BOLD;
1799 if (cellattrs.underline)
1800 attr |= HL_UNDERLINE;
1801 if (cellattrs.italic)
1802 attr |= HL_ITALIC;
1803 if (cellattrs.strike)
1804 attr |= HL_STRIKETHROUGH;
1805 if (cellattrs.reverse)
1806 attr |= HL_INVERSE;
1807
1808#ifdef FEAT_GUI
1809 if (gui.in_use)
1810 {
1811 guicolor_T fg, bg;
1812
1813 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1814 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1815 return get_gui_attr_idx(attr, fg, bg);
1816 }
1817 else
1818#endif
1819#ifdef FEAT_TERMGUICOLORS
1820 if (p_tgc)
1821 {
1822 guicolor_T fg, bg;
1823
1824 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1825 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1826
1827 return get_tgc_attr_idx(attr, fg, bg);
1828 }
1829 else
1830#endif
1831 {
1832 int bold = MAYBE;
1833 int fg = color2index(&cellfg, TRUE, &bold);
1834 int bg = color2index(&cellbg, FALSE, &bold);
1835
1836 /* with 8 colors set the bold attribute to get a bright foreground */
1837 if (bold == TRUE)
1838 attr |= HL_BOLD;
1839 return get_cterm_attr_idx(attr, fg, bg);
1840 }
1841 return 0;
1842}
1843
1844 static int
1845handle_damage(VTermRect rect, void *user)
1846{
1847 term_T *term = (term_T *)user;
1848
1849 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1850 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1851 redraw_buf_later(term->tl_buffer, NOT_VALID);
1852 return 1;
1853}
1854
1855 static int
1856handle_moverect(VTermRect dest, VTermRect src, void *user)
1857{
1858 term_T *term = (term_T *)user;
1859
1860 /* Scrolling up is done much more efficiently by deleting lines instead of
1861 * redrawing the text. */
1862 if (dest.start_col == src.start_col
1863 && dest.end_col == src.end_col
1864 && dest.start_row < src.start_row)
1865 {
1866 win_T *wp;
1867 VTermColor fg, bg;
1868 VTermScreenCellAttrs attr;
1869 int clear_attr;
1870
1871 /* Set the color to clear lines with. */
1872 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1873 &fg, &bg);
1874 vim_memset(&attr, 0, sizeof(attr));
1875 clear_attr = cell2attr(attr, fg, bg);
1876
1877 FOR_ALL_WINDOWS(wp)
1878 {
1879 if (wp->w_buffer == term->tl_buffer)
1880 win_del_lines(wp, dest.start_row,
1881 src.start_row - dest.start_row, FALSE, FALSE,
1882 clear_attr);
1883 }
1884 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02001885
1886 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
1887 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
1888
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889 redraw_buf_later(term->tl_buffer, NOT_VALID);
1890 return 1;
1891}
1892
1893 static int
1894handle_movecursor(
1895 VTermPos pos,
1896 VTermPos oldpos UNUSED,
1897 int visible,
1898 void *user)
1899{
1900 term_T *term = (term_T *)user;
1901 win_T *wp;
1902
1903 term->tl_cursor_pos = pos;
1904 term->tl_cursor_visible = visible;
1905
1906 FOR_ALL_WINDOWS(wp)
1907 {
1908 if (wp->w_buffer == term->tl_buffer)
1909 position_cursor(wp, &pos);
1910 }
1911 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
1912 {
1913 may_toggle_cursor(term);
1914 update_cursor(term, term->tl_cursor_visible);
1915 }
1916
1917 return 1;
1918}
1919
1920 static int
1921handle_settermprop(
1922 VTermProp prop,
1923 VTermValue *value,
1924 void *user)
1925{
1926 term_T *term = (term_T *)user;
1927
1928 switch (prop)
1929 {
1930 case VTERM_PROP_TITLE:
1931 vim_free(term->tl_title);
1932 /* a blank title isn't useful, make it empty, so that "running" is
1933 * displayed */
1934 if (*skipwhite((char_u *)value->string) == NUL)
1935 term->tl_title = NULL;
1936#ifdef WIN3264
1937 else if (!enc_utf8 && enc_codepage > 0)
1938 {
1939 WCHAR *ret = NULL;
1940 int length = 0;
1941
1942 MultiByteToWideChar_alloc(CP_UTF8, 0,
1943 (char*)value->string, (int)STRLEN(value->string),
1944 &ret, &length);
1945 if (ret != NULL)
1946 {
1947 WideCharToMultiByte_alloc(enc_codepage, 0,
1948 ret, length, (char**)&term->tl_title,
1949 &length, 0, 0);
1950 vim_free(ret);
1951 }
1952 }
1953#endif
1954 else
1955 term->tl_title = vim_strsave((char_u *)value->string);
1956 vim_free(term->tl_status_text);
1957 term->tl_status_text = NULL;
1958 if (term == curbuf->b_term)
1959 maketitle();
1960 break;
1961
1962 case VTERM_PROP_CURSORVISIBLE:
1963 term->tl_cursor_visible = value->boolean;
1964 may_toggle_cursor(term);
1965 out_flush();
1966 break;
1967
1968 case VTERM_PROP_CURSORBLINK:
1969 term->tl_cursor_blink = value->boolean;
1970 may_set_cursor_props(term);
1971 break;
1972
1973 case VTERM_PROP_CURSORSHAPE:
1974 term->tl_cursor_shape = value->number;
1975 may_set_cursor_props(term);
1976 break;
1977
1978 case VTERM_PROP_CURSORCOLOR:
1979 vim_free(term->tl_cursor_color);
1980 if (*value->string == NUL)
1981 term->tl_cursor_color = NULL;
1982 else
1983 term->tl_cursor_color = vim_strsave((char_u *)value->string);
1984 may_set_cursor_props(term);
1985 break;
1986
1987 case VTERM_PROP_ALTSCREEN:
1988 /* TODO: do anything else? */
1989 term->tl_using_altscreen = value->boolean;
1990 break;
1991
1992 default:
1993 break;
1994 }
1995 /* Always return 1, otherwise vterm doesn't store the value internally. */
1996 return 1;
1997}
1998
1999/*
2000 * The job running in the terminal resized the terminal.
2001 */
2002 static int
2003handle_resize(int rows, int cols, void *user)
2004{
2005 term_T *term = (term_T *)user;
2006 win_T *wp;
2007
2008 term->tl_rows = rows;
2009 term->tl_cols = cols;
2010 if (term->tl_vterm_size_changed)
2011 /* Size was set by vterm_set_size(), don't set the window size. */
2012 term->tl_vterm_size_changed = FALSE;
2013 else
2014 {
2015 FOR_ALL_WINDOWS(wp)
2016 {
2017 if (wp->w_buffer == term->tl_buffer)
2018 {
2019 win_setheight_win(rows, wp);
2020 win_setwidth_win(cols, wp);
2021 }
2022 }
2023 redraw_buf_later(term->tl_buffer, NOT_VALID);
2024 }
2025 return 1;
2026}
2027
2028/*
2029 * Handle a line that is pushed off the top of the screen.
2030 */
2031 static int
2032handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2033{
2034 term_T *term = (term_T *)user;
2035
2036 /* TODO: Limit the number of lines that are stored. */
2037 if (ga_grow(&term->tl_scrollback, 1) == OK)
2038 {
2039 cellattr_T *p = NULL;
2040 int len = 0;
2041 int i;
2042 int c;
2043 int col;
2044 sb_line_T *line;
2045 garray_T ga;
2046 cellattr_T fill_attr = term->tl_default_color;
2047
2048 /* do not store empty cells at the end */
2049 for (i = 0; i < cols; ++i)
2050 if (cells[i].chars[0] != 0)
2051 len = i + 1;
2052 else
2053 cell2cellattr(&cells[i], &fill_attr);
2054
2055 ga_init2(&ga, 1, 100);
2056 if (len > 0)
2057 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2058 if (p != NULL)
2059 {
2060 for (col = 0; col < len; col += cells[col].width)
2061 {
2062 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2063 {
2064 ga.ga_len = 0;
2065 break;
2066 }
2067 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2068 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2069 (char_u *)ga.ga_data + ga.ga_len);
2070 cell2cellattr(&cells[col], &p[col]);
2071 }
2072 }
2073 if (ga_grow(&ga, 1) == FAIL)
2074 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2075 else
2076 {
2077 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2078 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2079 }
2080 ga_clear(&ga);
2081
2082 line = (sb_line_T *)term->tl_scrollback.ga_data
2083 + term->tl_scrollback.ga_len;
2084 line->sb_cols = len;
2085 line->sb_cells = p;
2086 line->sb_fill_attr = fill_attr;
2087 ++term->tl_scrollback.ga_len;
2088 ++term->tl_scrollback_scrolled;
2089 }
2090 return 0; /* ignored */
2091}
2092
2093static VTermScreenCallbacks screen_callbacks = {
2094 handle_damage, /* damage */
2095 handle_moverect, /* moverect */
2096 handle_movecursor, /* movecursor */
2097 handle_settermprop, /* settermprop */
2098 NULL, /* bell */
2099 handle_resize, /* resize */
2100 handle_pushline, /* sb_pushline */
2101 NULL /* sb_popline */
2102};
2103
2104/*
2105 * Called when a channel has been closed.
2106 * If this was a channel for a terminal window then finish it up.
2107 */
2108 void
2109term_channel_closed(channel_T *ch)
2110{
2111 term_T *term;
2112 int did_one = FALSE;
2113
2114 for (term = first_term; term != NULL; term = term->tl_next)
2115 if (term->tl_job == ch->ch_job)
2116 {
2117 term->tl_channel_closed = TRUE;
2118 did_one = TRUE;
2119
2120 vim_free(term->tl_title);
2121 term->tl_title = NULL;
2122 vim_free(term->tl_status_text);
2123 term->tl_status_text = NULL;
2124
2125 /* Unless in Terminal-Normal mode: clear the vterm. */
2126 if (!term->tl_normal_mode)
2127 {
2128 int fnum = term->tl_buffer->b_fnum;
2129
2130 cleanup_vterm(term);
2131
2132 if (term->tl_finish == 'c')
2133 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002134 aco_save_T aco;
2135
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 /* ++close or term_finish == "close" */
2137 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002138 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002139 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002140 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 break;
2142 }
2143 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2144 {
2145 char buf[50];
2146
2147 /* TODO: use term_opencmd */
2148 ch_log(NULL, "terminal job finished, opening window");
2149 vim_snprintf(buf, sizeof(buf),
2150 term->tl_opencmd == NULL
2151 ? "botright sbuf %d"
2152 : (char *)term->tl_opencmd, fnum);
2153 do_cmdline_cmd((char_u *)buf);
2154 }
2155 else
2156 ch_log(NULL, "terminal job finished");
2157 }
2158
2159 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2160 }
2161 if (did_one)
2162 {
2163 redraw_statuslines();
2164
2165 /* Need to break out of vgetc(). */
2166 ins_char_typebuf(K_IGNORE);
2167 typebuf_was_filled = TRUE;
2168
2169 term = curbuf->b_term;
2170 if (term != NULL)
2171 {
2172 if (term->tl_job == ch->ch_job)
2173 maketitle();
2174 update_cursor(term, term->tl_cursor_visible);
2175 }
2176 }
2177}
2178
2179/*
2180 * Called to update a window that contains an active terminal.
2181 * Returns FAIL when there is no terminal running in this window or in
2182 * Terminal-Normal mode.
2183 */
2184 int
2185term_update_window(win_T *wp)
2186{
2187 term_T *term = wp->w_buffer->b_term;
2188 VTerm *vterm;
2189 VTermScreen *screen;
2190 VTermState *state;
2191 VTermPos pos;
2192
2193 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2194 return FAIL;
2195
2196 vterm = term->tl_vterm;
2197 screen = vterm_obtain_screen(vterm);
2198 state = vterm_obtain_state(vterm);
2199
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002200 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002201 {
2202 term->tl_dirty_row_start = 0;
2203 term->tl_dirty_row_end = MAX_ROW;
2204 }
2205
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002206 /*
2207 * If the window was resized a redraw will be triggered and we get here.
2208 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2209 */
2210 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2211 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2212 {
2213 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2214 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2215 win_T *twp;
2216
2217 FOR_ALL_WINDOWS(twp)
2218 {
2219 /* When more than one window shows the same terminal, use the
2220 * smallest size. */
2221 if (twp->w_buffer == term->tl_buffer)
2222 {
2223 if (!term->tl_rows_fixed && rows > twp->w_height)
2224 rows = twp->w_height;
2225 if (!term->tl_cols_fixed && cols > twp->w_width)
2226 cols = twp->w_width;
2227 }
2228 }
2229
2230 term->tl_vterm_size_changed = TRUE;
2231 vterm_set_size(vterm, rows, cols);
2232 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2233 rows);
2234 term_report_winsize(term, rows, cols);
2235 }
2236
2237 /* The cursor may have been moved when resizing. */
2238 vterm_state_get_cursorpos(state, &pos);
2239 position_cursor(wp, &pos);
2240
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002241 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2242 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243 {
2244 int off = screen_get_current_line_off();
2245 int max_col = MIN(wp->w_width, term->tl_cols);
2246
2247 if (pos.row < term->tl_rows)
2248 {
2249 for (pos.col = 0; pos.col < max_col; )
2250 {
2251 VTermScreenCell cell;
2252 int c;
2253
2254 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2255 vim_memset(&cell, 0, sizeof(cell));
2256
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002257 c = cell.chars[0];
2258 if (c == NUL)
2259 {
2260 ScreenLines[off] = ' ';
2261 if (enc_utf8)
2262 ScreenLinesUC[off] = NUL;
2263 }
2264 else
2265 {
2266 if (enc_utf8)
2267 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002268 int i;
2269
2270 /* composing chars */
2271 for (i = 0; i < Screen_mco
2272 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2273 {
2274 ScreenLinesC[i][off] = cell.chars[i + 1];
2275 if (cell.chars[i + 1] == 0)
2276 break;
2277 }
2278 if (c >= 0x80 || (Screen_mco > 0
2279 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280 {
2281 ScreenLines[off] = ' ';
2282 ScreenLinesUC[off] = c;
2283 }
2284 else
2285 {
2286 ScreenLines[off] = c;
2287 ScreenLinesUC[off] = NUL;
2288 }
2289 }
2290#ifdef WIN3264
2291 else if (has_mbyte && c >= 0x80)
2292 {
2293 char_u mb[MB_MAXBYTES+1];
2294 WCHAR wc = c;
2295
2296 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2297 (char*)mb, 2, 0, 0) > 1)
2298 {
2299 ScreenLines[off] = mb[0];
2300 ScreenLines[off + 1] = mb[1];
2301 cell.width = mb_ptr2cells(mb);
2302 }
2303 else
2304 ScreenLines[off] = c;
2305 }
2306#endif
2307 else
2308 ScreenLines[off] = c;
2309 }
2310 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2311
2312 ++pos.col;
2313 ++off;
2314 if (cell.width == 2)
2315 {
2316 if (enc_utf8)
2317 ScreenLinesUC[off] = NUL;
2318
2319 /* don't set the second byte to NUL for a DBCS encoding, it
2320 * has been set above */
2321 if (enc_utf8 || !has_mbyte)
2322 ScreenLines[off] = NUL;
2323
2324 ++pos.col;
2325 ++off;
2326 }
2327 }
2328 }
2329 else
2330 pos.col = 0;
2331
2332 screen_line(wp->w_winrow + pos.row, wp->w_wincol,
2333 pos.col, wp->w_width, FALSE);
2334 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002335 term->tl_dirty_row_start = MAX_ROW;
2336 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337
2338 return OK;
2339}
2340
2341/*
2342 * Return TRUE if "wp" is a terminal window where the job has finished.
2343 */
2344 int
2345term_is_finished(buf_T *buf)
2346{
2347 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2348}
2349
2350/*
2351 * Return TRUE if "wp" is a terminal window where the job has finished or we
2352 * are in Terminal-Normal mode, thus we show the buffer contents.
2353 */
2354 int
2355term_show_buffer(buf_T *buf)
2356{
2357 term_T *term = buf->b_term;
2358
2359 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2360}
2361
2362/*
2363 * The current buffer is going to be changed. If there is terminal
2364 * highlighting remove it now.
2365 */
2366 void
2367term_change_in_curbuf(void)
2368{
2369 term_T *term = curbuf->b_term;
2370
2371 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2372 {
2373 free_scrollback(term);
2374 redraw_buf_later(term->tl_buffer, NOT_VALID);
2375
2376 /* The buffer is now like a normal buffer, it cannot be easily
2377 * abandoned when changed. */
2378 set_string_option_direct((char_u *)"buftype", -1,
2379 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2380 }
2381}
2382
2383/*
2384 * Get the screen attribute for a position in the buffer.
2385 * Use a negative "col" to get the filler background color.
2386 */
2387 int
2388term_get_attr(buf_T *buf, linenr_T lnum, int col)
2389{
2390 term_T *term = buf->b_term;
2391 sb_line_T *line;
2392 cellattr_T *cellattr;
2393
2394 if (lnum > term->tl_scrollback.ga_len)
2395 cellattr = &term->tl_default_color;
2396 else
2397 {
2398 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2399 if (col < 0 || col >= line->sb_cols)
2400 cellattr = &line->sb_fill_attr;
2401 else
2402 cellattr = line->sb_cells + col;
2403 }
2404 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2405}
2406
2407static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002408 { 0, 0, 0, 1}, /* black */
2409 {224, 0, 0, 2}, /* dark red */
2410 { 0, 224, 0, 3}, /* dark green */
2411 {224, 224, 0, 4}, /* dark yellow / brown */
2412 { 0, 0, 224, 5}, /* dark blue */
2413 {224, 0, 224, 6}, /* dark magenta */
2414 { 0, 224, 224, 7}, /* dark cyan */
2415 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416
Bram Moolenaar46359e12017-11-29 22:33:38 +01002417 {128, 128, 128, 9}, /* dark grey */
2418 {255, 64, 64, 10}, /* light red */
2419 { 64, 255, 64, 11}, /* light green */
2420 {255, 255, 64, 12}, /* yellow */
2421 { 64, 64, 255, 13}, /* light blue */
2422 {255, 64, 255, 14}, /* light magenta */
2423 { 64, 255, 255, 15}, /* light cyan */
2424 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425};
2426
2427static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002428 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002429};
2430
2431static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002432 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2433 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434};
2435
2436/*
2437 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002438 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 */
2440 static void
2441cterm_color2rgb(int nr, VTermColor *rgb)
2442{
2443 int idx;
2444
2445 if (nr < 16)
2446 {
2447 *rgb = ansi_table[nr];
2448 }
2449 else if (nr < 232)
2450 {
2451 /* 216 color cube */
2452 idx = nr - 16;
2453 rgb->blue = cube_value[idx % 6];
2454 rgb->green = cube_value[idx / 6 % 6];
2455 rgb->red = cube_value[idx / 36 % 6];
2456 }
2457 else if (nr < 256)
2458 {
2459 /* 24 grey scale ramp */
2460 idx = nr - 232;
2461 rgb->blue = grey_ramp[idx];
2462 rgb->green = grey_ramp[idx];
2463 rgb->red = grey_ramp[idx];
2464 }
2465}
2466
2467/*
2468 * Create a new vterm and initialize it.
2469 */
2470 static void
2471create_vterm(term_T *term, int rows, int cols)
2472{
2473 VTerm *vterm;
2474 VTermScreen *screen;
2475 VTermValue value;
2476 VTermColor *fg, *bg;
2477 int fgval, bgval;
2478 int id;
2479
2480 vterm = vterm_new(rows, cols);
2481 term->tl_vterm = vterm;
2482 screen = vterm_obtain_screen(vterm);
2483 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2484 /* TODO: depends on 'encoding'. */
2485 vterm_set_utf8(vterm, 1);
2486
2487 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2488 term->tl_default_color.width = 1;
2489 fg = &term->tl_default_color.fg;
2490 bg = &term->tl_default_color.bg;
2491
2492 /* Vterm uses a default black background. Set it to white when
2493 * 'background' is "light". */
2494 if (*p_bg == 'l')
2495 {
2496 fgval = 0;
2497 bgval = 255;
2498 }
2499 else
2500 {
2501 fgval = 255;
2502 bgval = 0;
2503 }
2504 fg->red = fg->green = fg->blue = fgval;
2505 bg->red = bg->green = bg->blue = bgval;
2506
2507 /* The "Terminal" highlight group overrules the defaults. */
2508 id = syn_name2id((char_u *)"Terminal");
2509
Bram Moolenaar46359e12017-11-29 22:33:38 +01002510 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2512 if (0
2513# ifdef FEAT_GUI
2514 || gui.in_use
2515# endif
2516# ifdef FEAT_TERMGUICOLORS
2517 || p_tgc
2518# endif
2519 )
2520 {
2521 guicolor_T fg_rgb = INVALCOLOR;
2522 guicolor_T bg_rgb = INVALCOLOR;
2523
2524 if (id != 0)
2525 syn_id2colors(id, &fg_rgb, &bg_rgb);
2526
2527# ifdef FEAT_GUI
2528 if (gui.in_use)
2529 {
2530 if (fg_rgb == INVALCOLOR)
2531 fg_rgb = gui.norm_pixel;
2532 if (bg_rgb == INVALCOLOR)
2533 bg_rgb = gui.back_pixel;
2534 }
2535# ifdef FEAT_TERMGUICOLORS
2536 else
2537# endif
2538# endif
2539# ifdef FEAT_TERMGUICOLORS
2540 {
2541 if (fg_rgb == INVALCOLOR)
2542 fg_rgb = cterm_normal_fg_gui_color;
2543 if (bg_rgb == INVALCOLOR)
2544 bg_rgb = cterm_normal_bg_gui_color;
2545 }
2546# endif
2547 if (fg_rgb != INVALCOLOR)
2548 {
2549 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2550
2551 fg->red = (unsigned)(rgb >> 16);
2552 fg->green = (unsigned)(rgb >> 8) & 255;
2553 fg->blue = (unsigned)rgb & 255;
2554 }
2555 if (bg_rgb != INVALCOLOR)
2556 {
2557 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2558
2559 bg->red = (unsigned)(rgb >> 16);
2560 bg->green = (unsigned)(rgb >> 8) & 255;
2561 bg->blue = (unsigned)rgb & 255;
2562 }
2563 }
2564 else
2565#endif
2566 if (id != 0 && t_colors >= 16)
2567 {
2568 int cterm_fg, cterm_bg;
2569
2570 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
2571 if (cterm_fg >= 0)
2572 cterm_color2rgb(cterm_fg, fg);
2573 if (cterm_bg >= 0)
2574 cterm_color2rgb(cterm_bg, bg);
2575 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002576 else
2577 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002578#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002579 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002580#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581
2582 /* In an MS-Windows console we know the normal colors. */
2583 if (cterm_normal_fg_color > 0)
2584 {
2585 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002586# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002587 tmp = fg->red;
2588 fg->red = fg->blue;
2589 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002590# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002591 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002592# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002593 else
2594 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002595# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 if (cterm_normal_bg_color > 0)
2598 {
2599 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002600# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002601 tmp = bg->red;
2602 bg->red = bg->blue;
2603 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002604# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002606# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002607 else
2608 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002609# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002610 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002611
2612 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2613
2614 /* Required to initialize most things. */
2615 vterm_screen_reset(screen, 1 /* hard */);
2616
2617 /* Allow using alternate screen. */
2618 vterm_screen_enable_altscreen(screen, 1);
2619
2620 /* For unix do not use a blinking cursor. In an xterm this causes the
2621 * cursor to blink if it's blinking in the xterm.
2622 * For Windows we respect the system wide setting. */
2623#ifdef WIN3264
2624 if (GetCaretBlinkTime() == INFINITE)
2625 value.boolean = 0;
2626 else
2627 value.boolean = 1;
2628#else
2629 value.boolean = 0;
2630#endif
2631 vterm_state_set_termprop(vterm_obtain_state(vterm),
2632 VTERM_PROP_CURSORBLINK, &value);
2633}
2634
2635/*
2636 * Return the text to show for the buffer name and status.
2637 */
2638 char_u *
2639term_get_status_text(term_T *term)
2640{
2641 if (term->tl_status_text == NULL)
2642 {
2643 char_u *txt;
2644 size_t len;
2645
2646 if (term->tl_normal_mode)
2647 {
2648 if (term_job_running(term))
2649 txt = (char_u *)_("Terminal");
2650 else
2651 txt = (char_u *)_("Terminal-finished");
2652 }
2653 else if (term->tl_title != NULL)
2654 txt = term->tl_title;
2655 else if (term_none_open(term))
2656 txt = (char_u *)_("active");
2657 else if (term_job_running(term))
2658 txt = (char_u *)_("running");
2659 else
2660 txt = (char_u *)_("finished");
2661 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2662 term->tl_status_text = alloc((int)len);
2663 if (term->tl_status_text != NULL)
2664 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2665 term->tl_buffer->b_fname, txt);
2666 }
2667 return term->tl_status_text;
2668}
2669
2670/*
2671 * Mark references in jobs of terminals.
2672 */
2673 int
2674set_ref_in_term(int copyID)
2675{
2676 int abort = FALSE;
2677 term_T *term;
2678 typval_T tv;
2679
2680 for (term = first_term; term != NULL; term = term->tl_next)
2681 if (term->tl_job != NULL)
2682 {
2683 tv.v_type = VAR_JOB;
2684 tv.vval.v_job = term->tl_job;
2685 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2686 }
2687 return abort;
2688}
2689
2690/*
2691 * Get the buffer from the first argument in "argvars".
2692 * Returns NULL when the buffer is not for a terminal window.
2693 */
2694 static buf_T *
2695term_get_buf(typval_T *argvars)
2696{
2697 buf_T *buf;
2698
2699 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2700 ++emsg_off;
2701 buf = get_buf_tv(&argvars[0], FALSE);
2702 --emsg_off;
2703 if (buf == NULL || buf->b_term == NULL)
2704 return NULL;
2705 return buf;
2706}
2707
2708/*
2709 * "term_getaltscreen(buf)" function
2710 */
2711 void
2712f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2713{
2714 buf_T *buf = term_get_buf(argvars);
2715
2716 if (buf == NULL)
2717 return;
2718 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2719}
2720
2721/*
2722 * "term_getattr(attr, name)" function
2723 */
2724 void
2725f_term_getattr(typval_T *argvars, typval_T *rettv)
2726{
2727 int attr;
2728 size_t i;
2729 char_u *name;
2730
2731 static struct {
2732 char *name;
2733 int attr;
2734 } attrs[] = {
2735 {"bold", HL_BOLD},
2736 {"italic", HL_ITALIC},
2737 {"underline", HL_UNDERLINE},
2738 {"strike", HL_STRIKETHROUGH},
2739 {"reverse", HL_INVERSE},
2740 };
2741
2742 attr = get_tv_number(&argvars[0]);
2743 name = get_tv_string_chk(&argvars[1]);
2744 if (name == NULL)
2745 return;
2746
2747 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2748 if (STRCMP(name, attrs[i].name) == 0)
2749 {
2750 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2751 break;
2752 }
2753}
2754
2755/*
2756 * "term_getcursor(buf)" function
2757 */
2758 void
2759f_term_getcursor(typval_T *argvars, typval_T *rettv)
2760{
2761 buf_T *buf = term_get_buf(argvars);
2762 term_T *term;
2763 list_T *l;
2764 dict_T *d;
2765
2766 if (rettv_list_alloc(rettv) == FAIL)
2767 return;
2768 if (buf == NULL)
2769 return;
2770 term = buf->b_term;
2771
2772 l = rettv->vval.v_list;
2773 list_append_number(l, term->tl_cursor_pos.row + 1);
2774 list_append_number(l, term->tl_cursor_pos.col + 1);
2775
2776 d = dict_alloc();
2777 if (d != NULL)
2778 {
2779 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2780 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2781 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2782 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2783 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2784 ? (char_u *)"" : term->tl_cursor_color);
2785 list_append_dict(l, d);
2786 }
2787}
2788
2789/*
2790 * "term_getjob(buf)" function
2791 */
2792 void
2793f_term_getjob(typval_T *argvars, typval_T *rettv)
2794{
2795 buf_T *buf = term_get_buf(argvars);
2796
2797 rettv->v_type = VAR_JOB;
2798 rettv->vval.v_job = NULL;
2799 if (buf == NULL)
2800 return;
2801
2802 rettv->vval.v_job = buf->b_term->tl_job;
2803 if (rettv->vval.v_job != NULL)
2804 ++rettv->vval.v_job->jv_refcount;
2805}
2806
2807 static int
2808get_row_number(typval_T *tv, term_T *term)
2809{
2810 if (tv->v_type == VAR_STRING
2811 && tv->vval.v_string != NULL
2812 && STRCMP(tv->vval.v_string, ".") == 0)
2813 return term->tl_cursor_pos.row;
2814 return (int)get_tv_number(tv) - 1;
2815}
2816
2817/*
2818 * "term_getline(buf, row)" function
2819 */
2820 void
2821f_term_getline(typval_T *argvars, typval_T *rettv)
2822{
2823 buf_T *buf = term_get_buf(argvars);
2824 term_T *term;
2825 int row;
2826
2827 rettv->v_type = VAR_STRING;
2828 if (buf == NULL)
2829 return;
2830 term = buf->b_term;
2831 row = get_row_number(&argvars[1], term);
2832
2833 if (term->tl_vterm == NULL)
2834 {
2835 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2836
2837 /* vterm is finished, get the text from the buffer */
2838 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2839 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2840 }
2841 else
2842 {
2843 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2844 VTermRect rect;
2845 int len;
2846 char_u *p;
2847
2848 if (row < 0 || row >= term->tl_rows)
2849 return;
2850 len = term->tl_cols * MB_MAXBYTES + 1;
2851 p = alloc(len);
2852 if (p == NULL)
2853 return;
2854 rettv->vval.v_string = p;
2855
2856 rect.start_col = 0;
2857 rect.end_col = term->tl_cols;
2858 rect.start_row = row;
2859 rect.end_row = row + 1;
2860 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2861 }
2862}
2863
2864/*
2865 * "term_getscrolled(buf)" function
2866 */
2867 void
2868f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2869{
2870 buf_T *buf = term_get_buf(argvars);
2871
2872 if (buf == NULL)
2873 return;
2874 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2875}
2876
2877/*
2878 * "term_getsize(buf)" function
2879 */
2880 void
2881f_term_getsize(typval_T *argvars, typval_T *rettv)
2882{
2883 buf_T *buf = term_get_buf(argvars);
2884 list_T *l;
2885
2886 if (rettv_list_alloc(rettv) == FAIL)
2887 return;
2888 if (buf == NULL)
2889 return;
2890
2891 l = rettv->vval.v_list;
2892 list_append_number(l, buf->b_term->tl_rows);
2893 list_append_number(l, buf->b_term->tl_cols);
2894}
2895
2896/*
2897 * "term_getstatus(buf)" function
2898 */
2899 void
2900f_term_getstatus(typval_T *argvars, typval_T *rettv)
2901{
2902 buf_T *buf = term_get_buf(argvars);
2903 term_T *term;
2904 char_u val[100];
2905
2906 rettv->v_type = VAR_STRING;
2907 if (buf == NULL)
2908 return;
2909 term = buf->b_term;
2910
2911 if (term_job_running(term))
2912 STRCPY(val, "running");
2913 else
2914 STRCPY(val, "finished");
2915 if (term->tl_normal_mode)
2916 STRCAT(val, ",normal");
2917 rettv->vval.v_string = vim_strsave(val);
2918}
2919
2920/*
2921 * "term_gettitle(buf)" function
2922 */
2923 void
2924f_term_gettitle(typval_T *argvars, typval_T *rettv)
2925{
2926 buf_T *buf = term_get_buf(argvars);
2927
2928 rettv->v_type = VAR_STRING;
2929 if (buf == NULL)
2930 return;
2931
2932 if (buf->b_term->tl_title != NULL)
2933 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
2934}
2935
2936/*
2937 * "term_gettty(buf)" function
2938 */
2939 void
2940f_term_gettty(typval_T *argvars, typval_T *rettv)
2941{
2942 buf_T *buf = term_get_buf(argvars);
2943 char_u *p;
2944 int num = 0;
2945
2946 rettv->v_type = VAR_STRING;
2947 if (buf == NULL)
2948 return;
2949 if (argvars[1].v_type != VAR_UNKNOWN)
2950 num = get_tv_number(&argvars[1]);
2951
2952 switch (num)
2953 {
2954 case 0:
2955 if (buf->b_term->tl_job != NULL)
2956 p = buf->b_term->tl_job->jv_tty_out;
2957 else
2958 p = buf->b_term->tl_tty_out;
2959 break;
2960 case 1:
2961 if (buf->b_term->tl_job != NULL)
2962 p = buf->b_term->tl_job->jv_tty_in;
2963 else
2964 p = buf->b_term->tl_tty_in;
2965 break;
2966 default:
2967 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
2968 return;
2969 }
2970 if (p != NULL)
2971 rettv->vval.v_string = vim_strsave(p);
2972}
2973
2974/*
2975 * "term_list()" function
2976 */
2977 void
2978f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
2979{
2980 term_T *tp;
2981 list_T *l;
2982
2983 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
2984 return;
2985
2986 l = rettv->vval.v_list;
2987 for (tp = first_term; tp != NULL; tp = tp->tl_next)
2988 if (tp != NULL && tp->tl_buffer != NULL)
2989 if (list_append_number(l,
2990 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
2991 return;
2992}
2993
2994/*
2995 * "term_scrape(buf, row)" function
2996 */
2997 void
2998f_term_scrape(typval_T *argvars, typval_T *rettv)
2999{
3000 buf_T *buf = term_get_buf(argvars);
3001 VTermScreen *screen = NULL;
3002 VTermPos pos;
3003 list_T *l;
3004 term_T *term;
3005 char_u *p;
3006 sb_line_T *line;
3007
3008 if (rettv_list_alloc(rettv) == FAIL)
3009 return;
3010 if (buf == NULL)
3011 return;
3012 term = buf->b_term;
3013
3014 l = rettv->vval.v_list;
3015 pos.row = get_row_number(&argvars[1], term);
3016
3017 if (term->tl_vterm != NULL)
3018 {
3019 screen = vterm_obtain_screen(term->tl_vterm);
3020 p = NULL;
3021 line = NULL;
3022 }
3023 else
3024 {
3025 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3026
3027 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3028 return;
3029 p = ml_get_buf(buf, lnum + 1, FALSE);
3030 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3031 }
3032
3033 for (pos.col = 0; pos.col < term->tl_cols; )
3034 {
3035 dict_T *dcell;
3036 int width;
3037 VTermScreenCellAttrs attrs;
3038 VTermColor fg, bg;
3039 char_u rgb[8];
3040 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3041 int off = 0;
3042 int i;
3043
3044 if (screen == NULL)
3045 {
3046 cellattr_T *cellattr;
3047 int len;
3048
3049 /* vterm has finished, get the cell from scrollback */
3050 if (pos.col >= line->sb_cols)
3051 break;
3052 cellattr = line->sb_cells + pos.col;
3053 width = cellattr->width;
3054 attrs = cellattr->attrs;
3055 fg = cellattr->fg;
3056 bg = cellattr->bg;
3057 len = MB_PTR2LEN(p);
3058 mch_memmove(mbs, p, len);
3059 mbs[len] = NUL;
3060 p += len;
3061 }
3062 else
3063 {
3064 VTermScreenCell cell;
3065 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3066 break;
3067 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3068 {
3069 if (cell.chars[i] == 0)
3070 break;
3071 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3072 }
3073 mbs[off] = NUL;
3074 width = cell.width;
3075 attrs = cell.attrs;
3076 fg = cell.fg;
3077 bg = cell.bg;
3078 }
3079 dcell = dict_alloc();
3080 list_append_dict(l, dcell);
3081
3082 dict_add_nr_str(dcell, "chars", 0, mbs);
3083
3084 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3085 fg.red, fg.green, fg.blue);
3086 dict_add_nr_str(dcell, "fg", 0, rgb);
3087 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3088 bg.red, bg.green, bg.blue);
3089 dict_add_nr_str(dcell, "bg", 0, rgb);
3090
3091 dict_add_nr_str(dcell, "attr",
3092 cell2attr(attrs, fg, bg), NULL);
3093 dict_add_nr_str(dcell, "width", width, NULL);
3094
3095 ++pos.col;
3096 if (width == 2)
3097 ++pos.col;
3098 }
3099}
3100
3101/*
3102 * "term_sendkeys(buf, keys)" function
3103 */
3104 void
3105f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3106{
3107 buf_T *buf = term_get_buf(argvars);
3108 char_u *msg;
3109 term_T *term;
3110
3111 rettv->v_type = VAR_UNKNOWN;
3112 if (buf == NULL)
3113 return;
3114
3115 msg = get_tv_string_chk(&argvars[1]);
3116 if (msg == NULL)
3117 return;
3118 term = buf->b_term;
3119 if (term->tl_vterm == NULL)
3120 return;
3121
3122 while (*msg != NUL)
3123 {
3124 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003125 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003126 }
3127}
3128
3129/*
3130 * "term_start(command, options)" function
3131 */
3132 void
3133f_term_start(typval_T *argvars, typval_T *rettv)
3134{
3135 jobopt_T opt;
3136 buf_T *buf;
3137
3138 init_job_options(&opt);
3139 if (argvars[1].v_type != VAR_UNKNOWN
3140 && get_job_options(&argvars[1], &opt,
3141 JO_TIMEOUT_ALL + JO_STOPONEXIT
3142 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3143 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3144 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3145 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3146 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3147 return;
3148
3149 if (opt.jo_vertical)
3150 cmdmod.split = WSP_VERT;
3151 buf = term_start(&argvars[0], &opt, FALSE);
3152
3153 if (buf != NULL && buf->b_term != NULL)
3154 rettv->vval.v_number = buf->b_fnum;
3155}
3156
3157/*
3158 * "term_wait" function
3159 */
3160 void
3161f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3162{
3163 buf_T *buf = term_get_buf(argvars);
3164
3165 if (buf == NULL)
3166 {
3167 ch_log(NULL, "term_wait(): invalid argument");
3168 return;
3169 }
3170 if (buf->b_term->tl_job == NULL)
3171 {
3172 ch_log(NULL, "term_wait(): no job to wait for");
3173 return;
3174 }
3175 if (buf->b_term->tl_job->jv_channel == NULL)
3176 /* channel is closed, nothing to do */
3177 return;
3178
3179 /* Get the job status, this will detect a job that finished. */
3180 if ((buf->b_term->tl_job->jv_channel == NULL
3181 || !buf->b_term->tl_job->jv_channel->ch_keep_open)
3182 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3183 {
3184 /* The job is dead, keep reading channel I/O until the channel is
3185 * closed. buf->b_term may become NULL if the terminal was closed while
3186 * waiting. */
3187 ch_log(NULL, "term_wait(): waiting for channel to close");
3188 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3189 {
3190 mch_check_messages();
3191 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01003192 if (!buf_valid(buf))
3193 /* If the terminal is closed when the channel is closed the
3194 * buffer disappears. */
3195 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003196 ui_delay(10L, FALSE);
3197 }
3198 mch_check_messages();
3199 parse_queued_messages();
3200 }
3201 else
3202 {
3203 long wait = 10L;
3204
3205 mch_check_messages();
3206 parse_queued_messages();
3207
3208 /* Wait for some time for any channel I/O. */
3209 if (argvars[1].v_type != VAR_UNKNOWN)
3210 wait = get_tv_number(&argvars[1]);
3211 ui_delay(wait, TRUE);
3212 mch_check_messages();
3213
3214 /* Flushing messages on channels is hopefully sufficient.
3215 * TODO: is there a better way? */
3216 parse_queued_messages();
3217 }
3218}
3219
3220/*
3221 * Called when a channel has sent all the lines to a terminal.
3222 * Send a CTRL-D to mark the end of the text.
3223 */
3224 void
3225term_send_eof(channel_T *ch)
3226{
3227 term_T *term;
3228
3229 for (term = first_term; term != NULL; term = term->tl_next)
3230 if (term->tl_job == ch->ch_job)
3231 {
3232 if (term->tl_eof_chars != NULL)
3233 {
3234 channel_send(ch, PART_IN, term->tl_eof_chars,
3235 (int)STRLEN(term->tl_eof_chars), NULL);
3236 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3237 }
3238# ifdef WIN3264
3239 else
3240 /* Default: CTRL-D */
3241 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3242# endif
3243 }
3244}
3245
3246# if defined(WIN3264) || defined(PROTO)
3247
3248/**************************************
3249 * 2. MS-Windows implementation.
3250 */
3251
3252# ifndef PROTO
3253
3254#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3255#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
3256#define WINPTY_MOUSE_MODE_FORCE 2
3257
3258void* (*winpty_config_new)(UINT64, void*);
3259void* (*winpty_open)(void*, void*);
3260void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3261BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3262void (*winpty_config_set_mouse_mode)(void*, int);
3263void (*winpty_config_set_initial_size)(void*, int, int);
3264LPCWSTR (*winpty_conin_name)(void*);
3265LPCWSTR (*winpty_conout_name)(void*);
3266LPCWSTR (*winpty_conerr_name)(void*);
3267void (*winpty_free)(void*);
3268void (*winpty_config_free)(void*);
3269void (*winpty_spawn_config_free)(void*);
3270void (*winpty_error_free)(void*);
3271LPCWSTR (*winpty_error_msg)(void*);
3272BOOL (*winpty_set_size)(void*, int, int, void*);
3273HANDLE (*winpty_agent_process)(void*);
3274
3275#define WINPTY_DLL "winpty.dll"
3276
3277static HINSTANCE hWinPtyDLL = NULL;
3278# endif
3279
3280 static int
3281dyn_winpty_init(int verbose)
3282{
3283 int i;
3284 static struct
3285 {
3286 char *name;
3287 FARPROC *ptr;
3288 } winpty_entry[] =
3289 {
3290 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3291 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3292 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3293 {"winpty_config_set_mouse_mode",
3294 (FARPROC*)&winpty_config_set_mouse_mode},
3295 {"winpty_config_set_initial_size",
3296 (FARPROC*)&winpty_config_set_initial_size},
3297 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3298 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3299 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3300 {"winpty_free", (FARPROC*)&winpty_free},
3301 {"winpty_open", (FARPROC*)&winpty_open},
3302 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3303 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3304 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3305 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3306 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3307 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3308 {NULL, NULL}
3309 };
3310
3311 /* No need to initialize twice. */
3312 if (hWinPtyDLL)
3313 return OK;
3314 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3315 * winpty.dll. */
3316 if (*p_winptydll != NUL)
3317 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3318 if (!hWinPtyDLL)
3319 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3320 if (!hWinPtyDLL)
3321 {
3322 if (verbose)
3323 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3324 : (char_u *)WINPTY_DLL);
3325 return FAIL;
3326 }
3327 for (i = 0; winpty_entry[i].name != NULL
3328 && winpty_entry[i].ptr != NULL; ++i)
3329 {
3330 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3331 winpty_entry[i].name)) == NULL)
3332 {
3333 if (verbose)
3334 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3335 return FAIL;
3336 }
3337 }
3338
3339 return OK;
3340}
3341
3342/*
3343 * Create a new terminal of "rows" by "cols" cells.
3344 * Store a reference in "term".
3345 * Return OK or FAIL.
3346 */
3347 static int
3348term_and_job_init(
3349 term_T *term,
3350 typval_T *argvar,
3351 jobopt_T *opt)
3352{
3353 WCHAR *cmd_wchar = NULL;
3354 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003355 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356 channel_T *channel = NULL;
3357 job_T *job = NULL;
3358 DWORD error;
3359 HANDLE jo = NULL;
3360 HANDLE child_process_handle;
3361 HANDLE child_thread_handle;
3362 void *winpty_err;
3363 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003364 garray_T ga_cmd, ga_env;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003365 char_u *cmd;
3366
3367 if (dyn_winpty_init(TRUE) == FAIL)
3368 return FAIL;
3369
3370 if (argvar->v_type == VAR_STRING)
3371 cmd = argvar->vval.v_string;
3372 else
3373 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003374 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
3375 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003377 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003378 }
3379
3380 cmd_wchar = enc_to_utf16(cmd, NULL);
3381 if (cmd_wchar == NULL)
3382 return FAIL;
3383 if (opt->jo_cwd != NULL)
3384 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003385
3386 ga_init2(&ga_env, (int)sizeof(char*), 20);
3387 win32_build_env(opt->jo_env, &ga_env, TRUE);
3388 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003389
3390 job = job_alloc();
3391 if (job == NULL)
3392 goto failed;
3393
3394 channel = add_channel();
3395 if (channel == NULL)
3396 goto failed;
3397
3398 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3399 if (term->tl_winpty_config == NULL)
3400 goto failed;
3401
3402 winpty_config_set_mouse_mode(term->tl_winpty_config,
3403 WINPTY_MOUSE_MODE_FORCE);
3404 winpty_config_set_initial_size(term->tl_winpty_config,
3405 term->tl_cols, term->tl_rows);
3406 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3407 if (term->tl_winpty == NULL)
3408 goto failed;
3409
3410 spawn_config = winpty_spawn_config_new(
3411 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3412 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3413 NULL,
3414 cmd_wchar,
3415 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003416 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003417 &winpty_err);
3418 if (spawn_config == NULL)
3419 goto failed;
3420
3421 channel = add_channel();
3422 if (channel == NULL)
3423 goto failed;
3424
3425 job = job_alloc();
3426 if (job == NULL)
3427 goto failed;
3428
3429 if (opt->jo_set & JO_IN_BUF)
3430 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3431
3432 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3433 &child_thread_handle, &error, &winpty_err))
3434 goto failed;
3435
3436 channel_set_pipes(channel,
3437 (sock_T)CreateFileW(
3438 winpty_conin_name(term->tl_winpty),
3439 GENERIC_WRITE, 0, NULL,
3440 OPEN_EXISTING, 0, NULL),
3441 (sock_T)CreateFileW(
3442 winpty_conout_name(term->tl_winpty),
3443 GENERIC_READ, 0, NULL,
3444 OPEN_EXISTING, 0, NULL),
3445 (sock_T)CreateFileW(
3446 winpty_conerr_name(term->tl_winpty),
3447 GENERIC_READ, 0, NULL,
3448 OPEN_EXISTING, 0, NULL));
3449
3450 /* Write lines with CR instead of NL. */
3451 channel->ch_write_text_mode = TRUE;
3452
3453 jo = CreateJobObject(NULL, NULL);
3454 if (jo == NULL)
3455 goto failed;
3456
3457 if (!AssignProcessToJobObject(jo, child_process_handle))
3458 {
3459 /* Failed, switch the way to terminate process with TerminateProcess. */
3460 CloseHandle(jo);
3461 jo = NULL;
3462 }
3463
3464 winpty_spawn_config_free(spawn_config);
3465 vim_free(cmd_wchar);
3466 vim_free(cwd_wchar);
3467
3468 create_vterm(term, term->tl_rows, term->tl_cols);
3469
3470 channel_set_job(channel, job, opt);
3471 job_set_options(job, opt);
3472
3473 job->jv_channel = channel;
3474 job->jv_proc_info.hProcess = child_process_handle;
3475 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3476 job->jv_job_object = jo;
3477 job->jv_status = JOB_STARTED;
3478 job->jv_tty_in = utf16_to_enc(
3479 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3480 job->jv_tty_out = utf16_to_enc(
3481 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3482 ++job->jv_refcount;
3483 term->tl_job = job;
3484
3485 return OK;
3486
3487failed:
3488 if (argvar->v_type == VAR_LIST)
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003489 vim_free(ga_cmd.ga_data);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003490 vim_free(ga_env.ga_data);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003491 vim_free(cmd_wchar);
3492 vim_free(cwd_wchar);
3493 if (spawn_config != NULL)
3494 winpty_spawn_config_free(spawn_config);
3495 if (channel != NULL)
3496 channel_clear(channel);
3497 if (job != NULL)
3498 {
3499 job->jv_channel = NULL;
3500 job_cleanup(job);
3501 }
3502 term->tl_job = NULL;
3503 if (jo != NULL)
3504 CloseHandle(jo);
3505 if (term->tl_winpty != NULL)
3506 winpty_free(term->tl_winpty);
3507 term->tl_winpty = NULL;
3508 if (term->tl_winpty_config != NULL)
3509 winpty_config_free(term->tl_winpty_config);
3510 term->tl_winpty_config = NULL;
3511 if (winpty_err != NULL)
3512 {
3513 char_u *msg = utf16_to_enc(
3514 (short_u *)winpty_error_msg(winpty_err), NULL);
3515
3516 EMSG(msg);
3517 winpty_error_free(winpty_err);
3518 }
3519 return FAIL;
3520}
3521
3522 static int
3523create_pty_only(term_T *term, jobopt_T *options)
3524{
3525 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3526 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3527 char in_name[80], out_name[80];
3528 channel_T *channel = NULL;
3529
3530 create_vterm(term, term->tl_rows, term->tl_cols);
3531
3532 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3533 GetCurrentProcessId(),
3534 curbuf->b_fnum);
3535 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3536 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3537 PIPE_UNLIMITED_INSTANCES,
3538 0, 0, NMPWAIT_NOWAIT, NULL);
3539 if (hPipeIn == INVALID_HANDLE_VALUE)
3540 goto failed;
3541
3542 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3543 GetCurrentProcessId(),
3544 curbuf->b_fnum);
3545 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3546 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3547 PIPE_UNLIMITED_INSTANCES,
3548 0, 0, 0, NULL);
3549 if (hPipeOut == INVALID_HANDLE_VALUE)
3550 goto failed;
3551
3552 ConnectNamedPipe(hPipeIn, NULL);
3553 ConnectNamedPipe(hPipeOut, NULL);
3554
3555 term->tl_job = job_alloc();
3556 if (term->tl_job == NULL)
3557 goto failed;
3558 ++term->tl_job->jv_refcount;
3559
3560 /* behave like the job is already finished */
3561 term->tl_job->jv_status = JOB_FINISHED;
3562
3563 channel = add_channel();
3564 if (channel == NULL)
3565 goto failed;
3566 term->tl_job->jv_channel = channel;
3567 channel->ch_keep_open = TRUE;
3568 channel->ch_named_pipe = TRUE;
3569
3570 channel_set_pipes(channel,
3571 (sock_T)hPipeIn,
3572 (sock_T)hPipeOut,
3573 (sock_T)hPipeOut);
3574 channel_set_job(channel, term->tl_job, options);
3575 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3576 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3577
3578 return OK;
3579
3580failed:
3581 if (hPipeIn != NULL)
3582 CloseHandle(hPipeIn);
3583 if (hPipeOut != NULL)
3584 CloseHandle(hPipeOut);
3585 return FAIL;
3586}
3587
3588/*
3589 * Free the terminal emulator part of "term".
3590 */
3591 static void
3592term_free_vterm(term_T *term)
3593{
3594 if (term->tl_winpty != NULL)
3595 winpty_free(term->tl_winpty);
3596 term->tl_winpty = NULL;
3597 if (term->tl_winpty_config != NULL)
3598 winpty_config_free(term->tl_winpty_config);
3599 term->tl_winpty_config = NULL;
3600 if (term->tl_vterm != NULL)
3601 vterm_free(term->tl_vterm);
3602 term->tl_vterm = NULL;
3603}
3604
3605/*
3606 * Request size to terminal.
3607 */
3608 static void
3609term_report_winsize(term_T *term, int rows, int cols)
3610{
3611 if (term->tl_winpty)
3612 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3613}
3614
3615 int
3616terminal_enabled(void)
3617{
3618 return dyn_winpty_init(FALSE) == OK;
3619}
3620
3621# else
3622
3623/**************************************
3624 * 3. Unix-like implementation.
3625 */
3626
3627/*
3628 * Create a new terminal of "rows" by "cols" cells.
3629 * Start job for "cmd".
3630 * Store the pointers in "term".
3631 * Return OK or FAIL.
3632 */
3633 static int
3634term_and_job_init(
3635 term_T *term,
3636 typval_T *argvar,
3637 jobopt_T *opt)
3638{
3639 create_vterm(term, term->tl_rows, term->tl_cols);
3640
3641 term->tl_job = job_start(argvar, opt);
3642 if (term->tl_job != NULL)
3643 ++term->tl_job->jv_refcount;
3644
3645 return term->tl_job != NULL
3646 && term->tl_job->jv_channel != NULL
3647 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3648}
3649
3650 static int
3651create_pty_only(term_T *term, jobopt_T *opt)
3652{
3653 create_vterm(term, term->tl_rows, term->tl_cols);
3654
3655 term->tl_job = job_alloc();
3656 if (term->tl_job == NULL)
3657 return FAIL;
3658 ++term->tl_job->jv_refcount;
3659
3660 /* behave like the job is already finished */
3661 term->tl_job->jv_status = JOB_FINISHED;
3662
3663 return mch_create_pty_channel(term->tl_job, opt);
3664}
3665
3666/*
3667 * Free the terminal emulator part of "term".
3668 */
3669 static void
3670term_free_vterm(term_T *term)
3671{
3672 if (term->tl_vterm != NULL)
3673 vterm_free(term->tl_vterm);
3674 term->tl_vterm = NULL;
3675}
3676
3677/*
3678 * Request size to terminal.
3679 */
3680 static void
3681term_report_winsize(term_T *term, int rows, int cols)
3682{
3683 /* Use an ioctl() to report the new window size to the job. */
3684 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3685 {
3686 int fd = -1;
3687 int part;
3688
3689 for (part = PART_OUT; part < PART_COUNT; ++part)
3690 {
3691 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3692 if (isatty(fd))
3693 break;
3694 }
3695 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3696 mch_signal_job(term->tl_job, (char_u *)"winch");
3697 }
3698}
3699
3700# endif
3701
3702#endif /* FEAT_TERMINAL */