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