blob: eca9f1bd8632cf834c3f42da5ea5db839a70ba0d [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
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100478 if (!opt->jo_hidden)
479 {
480 ++curbuf->b_locked;
481 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
482 --curbuf->b_locked;
483 }
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200484#endif
485
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200486 if (old_curbuf != NULL)
487 {
488 --curbuf->b_nwindows;
489 curbuf = old_curbuf;
490 curwin->w_buffer = curbuf;
491 ++curbuf->b_nwindows;
492 }
493 }
494 else
495 {
496 buf_T *buf = curbuf;
497
498 free_terminal(curbuf);
499 if (old_curbuf != NULL)
500 {
501 --curbuf->b_nwindows;
502 curbuf = old_curbuf;
503 curwin->w_buffer = curbuf;
504 ++curbuf->b_nwindows;
505 }
506
507 /* Wiping out the buffer will also close the window and call
508 * free_terminal(). */
509 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
510 return NULL;
511 }
512 return newbuf;
513}
514
515/*
516 * ":terminal": open a terminal window and execute a job in it.
517 */
518 void
519ex_terminal(exarg_T *eap)
520{
521 typval_T argvar[2];
522 jobopt_T opt;
523 char_u *cmd;
524 char_u *tofree = NULL;
525
526 init_job_options(&opt);
527
528 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100529 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200530 {
531 char_u *p, *ep;
532
533 cmd += 2;
534 p = skiptowhite(cmd);
535 ep = vim_strchr(cmd, '=');
536 if (ep != NULL && ep < p)
537 p = ep;
538
539 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
540 opt.jo_term_finish = 'c';
541 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
542 opt.jo_term_finish = 'o';
543 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
544 opt.jo_curwin = 1;
545 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
546 opt.jo_hidden = 1;
547 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
548 && ep != NULL && isdigit(ep[1]))
549 {
550 opt.jo_set2 |= JO2_TERM_ROWS;
551 opt.jo_term_rows = atoi((char *)ep + 1);
552 p = skiptowhite(cmd);
553 }
554 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
555 && ep != NULL && isdigit(ep[1]))
556 {
557 opt.jo_set2 |= JO2_TERM_COLS;
558 opt.jo_term_cols = atoi((char *)ep + 1);
559 p = skiptowhite(cmd);
560 }
561 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
562 && ep != NULL)
563 {
564 char_u *buf = NULL;
565 char_u *keys;
566
567 p = skiptowhite(cmd);
568 *p = NUL;
569 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
570 opt.jo_set2 |= JO2_EOF_CHARS;
571 opt.jo_eof_chars = vim_strsave(keys);
572 vim_free(buf);
573 *p = ' ';
574 }
575 else
576 {
577 if (*p)
578 *p = NUL;
579 EMSG2(_("E181: Invalid attribute: %s"), cmd);
580 return;
581 }
582 cmd = skipwhite(p);
583 }
584 if (*cmd == NUL)
585 /* Make a copy of 'shell', an autocommand may change the option. */
586 tofree = cmd = vim_strsave(p_sh);
587
588 if (eap->addr_count > 0)
589 {
590 /* Write lines from current buffer to the job. */
591 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
592 opt.jo_io[PART_IN] = JIO_BUFFER;
593 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
594 opt.jo_in_top = eap->line1;
595 opt.jo_in_bot = eap->line2;
596 }
597
598 argvar[0].v_type = VAR_STRING;
599 argvar[0].vval.v_string = cmd;
600 argvar[1].v_type = VAR_UNKNOWN;
601 term_start(argvar, &opt, eap->forceit);
602 vim_free(tofree);
603 vim_free(opt.jo_eof_chars);
604}
605
606/*
607 * Free the scrollback buffer for "term".
608 */
609 static void
610free_scrollback(term_T *term)
611{
612 int i;
613
614 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
615 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
616 ga_clear(&term->tl_scrollback);
617}
618
619/*
620 * Free a terminal and everything it refers to.
621 * Kills the job if there is one.
622 * Called when wiping out a buffer.
623 */
624 void
625free_terminal(buf_T *buf)
626{
627 term_T *term = buf->b_term;
628 term_T *tp;
629
630 if (term == NULL)
631 return;
632 if (first_term == term)
633 first_term = term->tl_next;
634 else
635 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
636 if (tp->tl_next == term)
637 {
638 tp->tl_next = term->tl_next;
639 break;
640 }
641
642 if (term->tl_job != NULL)
643 {
644 if (term->tl_job->jv_status != JOB_ENDED
645 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100646 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200647 job_stop(term->tl_job, NULL, "kill");
648 job_unref(term->tl_job);
649 }
650
651 free_scrollback(term);
652
653 term_free_vterm(term);
654 vim_free(term->tl_title);
655 vim_free(term->tl_status_text);
656 vim_free(term->tl_opencmd);
657 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100658 if (desired_cursor_color == term->tl_cursor_color)
659 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 vim_free(term->tl_cursor_color);
661 vim_free(term);
662 buf->b_term = NULL;
663 if (in_terminal_loop == term)
664 in_terminal_loop = NULL;
665}
666
667/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100668 * Get the part that is connected to the tty. Normally this is PART_IN, but
669 * when writing buffer lines to the job it can be another. This makes it
670 * possible to do "1,5term vim -".
671 */
672 static ch_part_T
673get_tty_part(term_T *term)
674{
675#ifdef UNIX
676 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
677 int i;
678
679 for (i = 0; i < 3; ++i)
680 {
681 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
682
683 if (isatty(fd))
684 return parts[i];
685 }
686#endif
687 return PART_IN;
688}
689
690/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200691 * Write job output "msg[len]" to the vterm.
692 */
693 static void
694term_write_job_output(term_T *term, char_u *msg, size_t len)
695{
696 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100697 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200698
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100699 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200700
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100701 /* flush vterm buffer when vterm responded to control sequence */
702 if (prevlen != vterm_output_get_buffer_current(vterm))
703 {
704 char buf[KEY_BUF_LEN];
705 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
706
707 if (curlen > 0)
708 channel_send(term->tl_job->jv_channel, get_tty_part(term),
709 (char_u *)buf, (int)curlen, NULL);
710 }
711
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200712 /* this invokes the damage callbacks */
713 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
714}
715
716 static void
717update_cursor(term_T *term, int redraw)
718{
719 if (term->tl_normal_mode)
720 return;
721 setcursor();
722 if (redraw)
723 {
724 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
725 cursor_on();
726 out_flush();
727#ifdef FEAT_GUI
728 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100729 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100731 gui_mch_flush();
732 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733#endif
734 }
735}
736
737/*
738 * Invoked when "msg" output from a job was received. Write it to the terminal
739 * of "buffer".
740 */
741 void
742write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
743{
744 size_t len = STRLEN(msg);
745 term_T *term = buffer->b_term;
746
747 if (term->tl_vterm == NULL)
748 {
749 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
750 return;
751 }
752 ch_log(channel, "writing %d bytes to terminal", (int)len);
753 term_write_job_output(term, msg, len);
754
755 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
756 * contents, thus no screen update is needed. */
757 if (!term->tl_normal_mode)
758 {
759 /* TODO: only update once in a while. */
760 ch_log(term->tl_job->jv_channel, "updating screen");
761 if (buffer == curbuf)
762 {
763 update_screen(0);
764 update_cursor(term, TRUE);
765 }
766 else
767 redraw_after_callback(TRUE);
768 }
769}
770
771/*
772 * Send a mouse position and click to the vterm
773 */
774 static int
775term_send_mouse(VTerm *vterm, int button, int pressed)
776{
777 VTermModifier mod = VTERM_MOD_NONE;
778
779 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200780 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100781 if (button != 0)
782 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200783 return TRUE;
784}
785
786/*
787 * Convert typed key "c" into bytes to send to the job.
788 * Return the number of bytes in "buf".
789 */
790 static int
791term_convert_key(term_T *term, int c, char *buf)
792{
793 VTerm *vterm = term->tl_vterm;
794 VTermKey key = VTERM_KEY_NONE;
795 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100796 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200797
798 switch (c)
799 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100800 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200802 /* don't use VTERM_KEY_BACKSPACE, it always
803 * becomes 0x7f DEL */
804 case K_BS: c = term_backspace_char; break;
805
806 case ESC: key = VTERM_KEY_ESCAPE; break;
807 case K_DEL: key = VTERM_KEY_DEL; break;
808 case K_DOWN: key = VTERM_KEY_DOWN; break;
809 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
810 key = VTERM_KEY_DOWN; break;
811 case K_END: key = VTERM_KEY_END; break;
812 case K_S_END: mod = VTERM_MOD_SHIFT;
813 key = VTERM_KEY_END; break;
814 case K_C_END: mod = VTERM_MOD_CTRL;
815 key = VTERM_KEY_END; break;
816 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
817 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
818 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
819 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
820 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
821 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
822 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
823 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
824 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
825 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
826 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
827 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
828 case K_HOME: key = VTERM_KEY_HOME; break;
829 case K_S_HOME: mod = VTERM_MOD_SHIFT;
830 key = VTERM_KEY_HOME; break;
831 case K_C_HOME: mod = VTERM_MOD_CTRL;
832 key = VTERM_KEY_HOME; break;
833 case K_INS: key = VTERM_KEY_INS; break;
834 case K_K0: key = VTERM_KEY_KP_0; break;
835 case K_K1: key = VTERM_KEY_KP_1; break;
836 case K_K2: key = VTERM_KEY_KP_2; break;
837 case K_K3: key = VTERM_KEY_KP_3; break;
838 case K_K4: key = VTERM_KEY_KP_4; break;
839 case K_K5: key = VTERM_KEY_KP_5; break;
840 case K_K6: key = VTERM_KEY_KP_6; break;
841 case K_K7: key = VTERM_KEY_KP_7; break;
842 case K_K8: key = VTERM_KEY_KP_8; break;
843 case K_K9: key = VTERM_KEY_KP_9; break;
844 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
845 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
846 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
847 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
848 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
849 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
850 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
851 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
852 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
853 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
854 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
855 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
856 case K_LEFT: key = VTERM_KEY_LEFT; break;
857 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
858 key = VTERM_KEY_LEFT; break;
859 case K_C_LEFT: mod = VTERM_MOD_CTRL;
860 key = VTERM_KEY_LEFT; break;
861 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
862 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
863 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
864 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
865 key = VTERM_KEY_RIGHT; break;
866 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
867 key = VTERM_KEY_RIGHT; break;
868 case K_UP: key = VTERM_KEY_UP; break;
869 case K_S_UP: mod = VTERM_MOD_SHIFT;
870 key = VTERM_KEY_UP; break;
871 case TAB: key = VTERM_KEY_TAB; break;
872
Bram Moolenaara42ad572017-11-16 13:08:04 +0100873 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
874 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200875 case K_MOUSELEFT: /* TODO */ return 0;
876 case K_MOUSERIGHT: /* TODO */ return 0;
877
878 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100879 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
880 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100882 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100883 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100884 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
885 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
886 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
887 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
888 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
889 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200890 case K_X1MOUSE: /* TODO */ return 0;
891 case K_X1DRAG: /* TODO */ return 0;
892 case K_X1RELEASE: /* TODO */ return 0;
893 case K_X2MOUSE: /* TODO */ return 0;
894 case K_X2DRAG: /* TODO */ return 0;
895 case K_X2RELEASE: /* TODO */ return 0;
896
897 case K_IGNORE: return 0;
898 case K_NOP: return 0;
899 case K_UNDO: return 0;
900 case K_HELP: return 0;
901 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
902 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
903 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
904 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
905 case K_SELECT: return 0;
906#ifdef FEAT_GUI
907 case K_VER_SCROLLBAR: return 0;
908 case K_HOR_SCROLLBAR: return 0;
909#endif
910#ifdef FEAT_GUI_TABLINE
911 case K_TABLINE: return 0;
912 case K_TABMENU: return 0;
913#endif
914#ifdef FEAT_NETBEANS_INTG
915 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
916#endif
917#ifdef FEAT_DND
918 case K_DROP: return 0;
919#endif
920#ifdef FEAT_AUTOCMD
921 case K_CURSORHOLD: return 0;
922#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100923 case K_PS: vterm_keyboard_start_paste(vterm);
924 other = TRUE;
925 break;
926 case K_PE: vterm_keyboard_end_paste(vterm);
927 other = TRUE;
928 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200929 }
930
931 /*
932 * Convert special keys to vterm keys:
933 * - Write keys to vterm: vterm_keyboard_key()
934 * - Write output to channel.
935 * TODO: use mod_mask
936 */
937 if (key != VTERM_KEY_NONE)
938 /* Special key, let vterm convert it. */
939 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100940 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200941 /* Normal character, let vterm convert it. */
942 vterm_keyboard_unichar(vterm, c, mod);
943
944 /* Read back the converted escape sequence. */
945 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
946}
947
948/*
949 * Return TRUE if the job for "term" is still running.
950 */
951 int
952term_job_running(term_T *term)
953{
954 /* Also consider the job finished when the channel is closed, to avoid a
955 * race condition when updating the title. */
956 return term != NULL
957 && term->tl_job != NULL
958 && channel_is_open(term->tl_job->jv_channel)
959 && (term->tl_job->jv_status == JOB_STARTED
960 || term->tl_job->jv_channel->ch_keep_open);
961}
962
963/*
964 * Return TRUE if "term" has an active channel and used ":term NONE".
965 */
966 int
967term_none_open(term_T *term)
968{
969 /* Also consider the job finished when the channel is closed, to avoid a
970 * race condition when updating the title. */
971 return term != NULL
972 && term->tl_job != NULL
973 && channel_is_open(term->tl_job->jv_channel)
974 && term->tl_job->jv_channel->ch_keep_open;
975}
976
977/*
978 * Add the last line of the scrollback buffer to the buffer in the window.
979 */
980 static void
981add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
982{
983 buf_T *buf = term->tl_buffer;
984 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
985 linenr_T lnum = buf->b_ml.ml_line_count;
986
987#ifdef WIN3264
988 if (!enc_utf8 && enc_codepage > 0)
989 {
990 WCHAR *ret = NULL;
991 int length = 0;
992
993 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
994 &ret, &length);
995 if (ret != NULL)
996 {
997 WideCharToMultiByte_alloc(enc_codepage, 0,
998 ret, length, (char **)&text, &len, 0, 0);
999 vim_free(ret);
1000 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1001 vim_free(text);
1002 }
1003 }
1004 else
1005#endif
1006 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1007 if (empty)
1008 {
1009 /* Delete the empty line that was in the empty buffer. */
1010 curbuf = buf;
1011 ml_delete(1, FALSE);
1012 curbuf = curwin->w_buffer;
1013 }
1014}
1015
1016 static void
1017cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1018{
1019 attr->width = cell->width;
1020 attr->attrs = cell->attrs;
1021 attr->fg = cell->fg;
1022 attr->bg = cell->bg;
1023}
1024
1025 static int
1026equal_celattr(cellattr_T *a, cellattr_T *b)
1027{
1028 /* Comparing the colors should be sufficient. */
1029 return a->fg.red == b->fg.red
1030 && a->fg.green == b->fg.green
1031 && a->fg.blue == b->fg.blue
1032 && a->bg.red == b->bg.red
1033 && a->bg.green == b->bg.green
1034 && a->bg.blue == b->bg.blue;
1035}
1036
1037
1038/*
1039 * Add the current lines of the terminal to scrollback and to the buffer.
1040 * Called after the job has ended and when switching to Terminal-Normal mode.
1041 */
1042 static void
1043move_terminal_to_buffer(term_T *term)
1044{
1045 win_T *wp;
1046 int len;
1047 int lines_skipped = 0;
1048 VTermPos pos;
1049 VTermScreenCell cell;
1050 cellattr_T fill_attr, new_fill_attr;
1051 cellattr_T *p;
1052 VTermScreen *screen;
1053
1054 if (term->tl_vterm == NULL)
1055 return;
1056 screen = vterm_obtain_screen(term->tl_vterm);
1057 fill_attr = new_fill_attr = term->tl_default_color;
1058
1059 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1060 {
1061 len = 0;
1062 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1063 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1064 && cell.chars[0] != NUL)
1065 {
1066 len = pos.col + 1;
1067 new_fill_attr = term->tl_default_color;
1068 }
1069 else
1070 /* Assume the last attr is the filler attr. */
1071 cell2cellattr(&cell, &new_fill_attr);
1072
1073 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1074 ++lines_skipped;
1075 else
1076 {
1077 while (lines_skipped > 0)
1078 {
1079 /* Line was skipped, add an empty line. */
1080 --lines_skipped;
1081 if (ga_grow(&term->tl_scrollback, 1) == OK)
1082 {
1083 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1084 + term->tl_scrollback.ga_len;
1085
1086 line->sb_cols = 0;
1087 line->sb_cells = NULL;
1088 line->sb_fill_attr = fill_attr;
1089 ++term->tl_scrollback.ga_len;
1090
1091 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1092 }
1093 }
1094
1095 if (len == 0)
1096 p = NULL;
1097 else
1098 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1099 if ((p != NULL || len == 0)
1100 && ga_grow(&term->tl_scrollback, 1) == OK)
1101 {
1102 garray_T ga;
1103 int width;
1104 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1105 + term->tl_scrollback.ga_len;
1106
1107 ga_init2(&ga, 1, 100);
1108 for (pos.col = 0; pos.col < len; pos.col += width)
1109 {
1110 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1111 {
1112 width = 1;
1113 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1114 if (ga_grow(&ga, 1) == OK)
1115 ga.ga_len += utf_char2bytes(' ',
1116 (char_u *)ga.ga_data + ga.ga_len);
1117 }
1118 else
1119 {
1120 width = cell.width;
1121
1122 cell2cellattr(&cell, &p[pos.col]);
1123
1124 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1125 {
1126 int i;
1127 int c;
1128
1129 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1130 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1131 (char_u *)ga.ga_data + ga.ga_len);
1132 }
1133 }
1134 }
1135 line->sb_cols = len;
1136 line->sb_cells = p;
1137 line->sb_fill_attr = new_fill_attr;
1138 fill_attr = new_fill_attr;
1139 ++term->tl_scrollback.ga_len;
1140
1141 if (ga_grow(&ga, 1) == FAIL)
1142 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1143 else
1144 {
1145 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1146 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1147 }
1148 ga_clear(&ga);
1149 }
1150 else
1151 vim_free(p);
1152 }
1153 }
1154
1155 /* Obtain the current background color. */
1156 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1157 &term->tl_default_color.fg, &term->tl_default_color.bg);
1158
1159 FOR_ALL_WINDOWS(wp)
1160 {
1161 if (wp->w_buffer == term->tl_buffer)
1162 {
1163 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1164 wp->w_cursor.col = 0;
1165 wp->w_valid = 0;
1166 if (wp->w_cursor.lnum >= wp->w_height)
1167 {
1168 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1169
1170 if (wp->w_topline < min_topline)
1171 wp->w_topline = min_topline;
1172 }
1173 redraw_win_later(wp, NOT_VALID);
1174 }
1175 }
1176}
1177
1178 static void
1179set_terminal_mode(term_T *term, int normal_mode)
1180{
1181 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001182 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001183 if (term->tl_buffer == curbuf)
1184 maketitle();
1185}
1186
1187/*
1188 * Called after the job if finished and Terminal mode is not active:
1189 * Move the vterm contents into the scrollback buffer and free the vterm.
1190 */
1191 static void
1192cleanup_vterm(term_T *term)
1193{
1194 if (term->tl_finish != 'c')
1195 move_terminal_to_buffer(term);
1196 term_free_vterm(term);
1197 set_terminal_mode(term, FALSE);
1198}
1199
1200/*
1201 * Switch from Terminal-Job mode to Terminal-Normal mode.
1202 * Suspends updating the terminal window.
1203 */
1204 static void
1205term_enter_normal_mode(void)
1206{
1207 term_T *term = curbuf->b_term;
1208
1209 /* Append the current terminal contents to the buffer. */
1210 move_terminal_to_buffer(term);
1211
1212 set_terminal_mode(term, TRUE);
1213
1214 /* Move the window cursor to the position of the cursor in the
1215 * terminal. */
1216 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1217 + term->tl_cursor_pos.row + 1;
1218 check_cursor();
1219 coladvance(term->tl_cursor_pos.col);
1220
1221 /* Display the same lines as in the terminal. */
1222 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1223}
1224
1225/*
1226 * Returns TRUE if the current window contains a terminal and we are in
1227 * Terminal-Normal mode.
1228 */
1229 int
1230term_in_normal_mode(void)
1231{
1232 term_T *term = curbuf->b_term;
1233
1234 return term != NULL && term->tl_normal_mode;
1235}
1236
1237/*
1238 * Switch from Terminal-Normal mode to Terminal-Job mode.
1239 * Restores updating the terminal window.
1240 */
1241 void
1242term_enter_job_mode()
1243{
1244 term_T *term = curbuf->b_term;
1245 sb_line_T *line;
1246 garray_T *gap;
1247
1248 /* Remove the terminal contents from the scrollback and the buffer. */
1249 gap = &term->tl_scrollback;
1250 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1251 && gap->ga_len > 0)
1252 {
1253 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1254 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1255 vim_free(line->sb_cells);
1256 --gap->ga_len;
1257 }
1258 check_cursor();
1259
1260 set_terminal_mode(term, FALSE);
1261
1262 if (term->tl_channel_closed)
1263 cleanup_vterm(term);
1264 redraw_buf_and_status_later(curbuf, NOT_VALID);
1265}
1266
1267/*
1268 * Get a key from the user without mapping.
1269 * Note: while waiting a terminal may be closed and freed if the channel is
1270 * closed and ++close was used.
1271 * Uses terminal mode mappings.
1272 */
1273 static int
1274term_vgetc()
1275{
1276 int c;
1277 int save_State = State;
1278
1279 State = TERMINAL;
1280 got_int = FALSE;
1281#ifdef WIN3264
1282 ctrl_break_was_pressed = FALSE;
1283#endif
1284 c = vgetc();
1285 got_int = FALSE;
1286 State = save_State;
1287 return c;
1288}
1289
1290/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291 * Send keys to terminal.
1292 * Return FAIL when the key needs to be handled in Normal mode.
1293 * Return OK when the key was dropped or sent to the terminal.
1294 */
1295 int
1296send_keys_to_term(term_T *term, int c, int typed)
1297{
1298 char msg[KEY_BUF_LEN];
1299 size_t len;
1300 static int mouse_was_outside = FALSE;
1301 int dragging_outside = FALSE;
1302
1303 /* Catch keys that need to be handled as in Normal mode. */
1304 switch (c)
1305 {
1306 case NUL:
1307 case K_ZERO:
1308 if (typed)
1309 stuffcharReadbuff(c);
1310 return FAIL;
1311
1312 case K_IGNORE:
1313 return FAIL;
1314
1315 case K_LEFTDRAG:
1316 case K_MIDDLEDRAG:
1317 case K_RIGHTDRAG:
1318 case K_X1DRAG:
1319 case K_X2DRAG:
1320 dragging_outside = mouse_was_outside;
1321 /* FALLTHROUGH */
1322 case K_LEFTMOUSE:
1323 case K_LEFTMOUSE_NM:
1324 case K_LEFTRELEASE:
1325 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001326 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001327 case K_MIDDLEMOUSE:
1328 case K_MIDDLERELEASE:
1329 case K_RIGHTMOUSE:
1330 case K_RIGHTRELEASE:
1331 case K_X1MOUSE:
1332 case K_X1RELEASE:
1333 case K_X2MOUSE:
1334 case K_X2RELEASE:
1335
1336 case K_MOUSEUP:
1337 case K_MOUSEDOWN:
1338 case K_MOUSELEFT:
1339 case K_MOUSERIGHT:
1340 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001341 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001342 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001343 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001344 || dragging_outside)
1345 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001346 /* click or scroll outside the current window or on status line
1347 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001348 if (typed)
1349 {
1350 stuffcharReadbuff(c);
1351 mouse_was_outside = TRUE;
1352 }
1353 return FAIL;
1354 }
1355 }
1356 if (typed)
1357 mouse_was_outside = FALSE;
1358
1359 /* Convert the typed key to a sequence of bytes for the job. */
1360 len = term_convert_key(term, c, msg);
1361 if (len > 0)
1362 /* TODO: if FAIL is returned, stop? */
1363 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1364 (char_u *)msg, (int)len, NULL);
1365
1366 return OK;
1367}
1368
1369 static void
1370position_cursor(win_T *wp, VTermPos *pos)
1371{
1372 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1373 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1374 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1375}
1376
1377/*
1378 * Handle CTRL-W "": send register contents to the job.
1379 */
1380 static void
1381term_paste_register(int prev_c UNUSED)
1382{
1383 int c;
1384 list_T *l;
1385 listitem_T *item;
1386 long reglen = 0;
1387 int type;
1388
1389#ifdef FEAT_CMDL_INFO
1390 if (add_to_showcmd(prev_c))
1391 if (add_to_showcmd('"'))
1392 out_flush();
1393#endif
1394 c = term_vgetc();
1395#ifdef FEAT_CMDL_INFO
1396 clear_showcmd();
1397#endif
1398 if (!term_use_loop())
1399 /* job finished while waiting for a character */
1400 return;
1401
1402 /* CTRL-W "= prompt for expression to evaluate. */
1403 if (c == '=' && get_expr_register() != '=')
1404 return;
1405 if (!term_use_loop())
1406 /* job finished while waiting for a character */
1407 return;
1408
1409 l = (list_T *)get_reg_contents(c, GREG_LIST);
1410 if (l != NULL)
1411 {
1412 type = get_reg_type(c, &reglen);
1413 for (item = l->lv_first; item != NULL; item = item->li_next)
1414 {
1415 char_u *s = get_tv_string(&item->li_tv);
1416#ifdef WIN3264
1417 char_u *tmp = s;
1418
1419 if (!enc_utf8 && enc_codepage > 0)
1420 {
1421 WCHAR *ret = NULL;
1422 int length = 0;
1423
1424 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1425 (int)STRLEN(s), &ret, &length);
1426 if (ret != NULL)
1427 {
1428 WideCharToMultiByte_alloc(CP_UTF8, 0,
1429 ret, length, (char **)&s, &length, 0, 0);
1430 vim_free(ret);
1431 }
1432 }
1433#endif
1434 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1435 s, (int)STRLEN(s), NULL);
1436#ifdef WIN3264
1437 if (tmp != s)
1438 vim_free(s);
1439#endif
1440
1441 if (item->li_next != NULL || type == MLINE)
1442 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1443 (char_u *)"\r", 1, NULL);
1444 }
1445 list_free(l);
1446 }
1447}
1448
1449#if defined(FEAT_GUI) || defined(PROTO)
1450/*
1451 * Return TRUE when the cursor of the terminal should be displayed.
1452 */
1453 int
1454terminal_is_active()
1455{
1456 return in_terminal_loop != NULL;
1457}
1458
1459 cursorentry_T *
1460term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1461{
1462 term_T *term = in_terminal_loop;
1463 static cursorentry_T entry;
1464
1465 vim_memset(&entry, 0, sizeof(entry));
1466 entry.shape = entry.mshape =
1467 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1468 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1469 SHAPE_BLOCK;
1470 entry.percentage = 20;
1471 if (term->tl_cursor_blink)
1472 {
1473 entry.blinkwait = 700;
1474 entry.blinkon = 400;
1475 entry.blinkoff = 250;
1476 }
1477 *fg = gui.back_pixel;
1478 if (term->tl_cursor_color == NULL)
1479 *bg = gui.norm_pixel;
1480 else
1481 *bg = color_name2handle(term->tl_cursor_color);
1482 entry.name = "n";
1483 entry.used_for = SHAPE_CURSOR;
1484
1485 return &entry;
1486}
1487#endif
1488
Bram Moolenaard317b382018-02-08 22:33:31 +01001489 static void
1490may_output_cursor_props(void)
1491{
1492 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1493 || last_set_cursor_shape != desired_cursor_shape
1494 || last_set_cursor_blink != desired_cursor_blink)
1495 {
1496 last_set_cursor_color = desired_cursor_color;
1497 last_set_cursor_shape = desired_cursor_shape;
1498 last_set_cursor_blink = desired_cursor_blink;
1499 term_cursor_color(desired_cursor_color);
1500 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1501 /* this will restore the initial cursor style, if possible */
1502 ui_cursor_shape_forced(TRUE);
1503 else
1504 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1505 }
1506}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507
Bram Moolenaard317b382018-02-08 22:33:31 +01001508/*
1509 * Set the cursor color and shape, if not last set to these.
1510 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001511 static void
1512may_set_cursor_props(term_T *term)
1513{
1514#ifdef FEAT_GUI
1515 /* For the GUI the cursor properties are obtained with
1516 * term_get_cursor_shape(). */
1517 if (gui.in_use)
1518 return;
1519#endif
1520 if (in_terminal_loop == term)
1521 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001522 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001523 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001524 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001525 desired_cursor_color = (char_u *)"";
1526 desired_cursor_shape = term->tl_cursor_shape;
1527 desired_cursor_blink = term->tl_cursor_blink;
1528 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001529 }
1530}
1531
Bram Moolenaard317b382018-02-08 22:33:31 +01001532/*
1533 * Reset the desired cursor properties and restore them when needed.
1534 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001535 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001536prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001537{
1538#ifdef FEAT_GUI
1539 if (gui.in_use)
1540 return;
1541#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001542 desired_cursor_color = (char_u *)"";
1543 desired_cursor_shape = -1;
1544 desired_cursor_blink = -1;
1545 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001546}
1547
1548/*
1549 * Returns TRUE if the current window contains a terminal and we are sending
1550 * keys to the job.
1551 */
1552 int
1553term_use_loop(void)
1554{
1555 term_T *term = curbuf->b_term;
1556
1557 return term != NULL
1558 && !term->tl_normal_mode
1559 && term->tl_vterm != NULL
1560 && term_job_running(term);
1561}
1562
1563/*
1564 * Wait for input and send it to the job.
1565 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1566 * when there is no more typahead.
1567 * Return when the start of a CTRL-W command is typed or anything else that
1568 * should be handled as a Normal mode command.
1569 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1570 * the terminal was closed.
1571 */
1572 int
1573terminal_loop(int blocking)
1574{
1575 int c;
1576 int termkey = 0;
1577 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001578#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001579 int tty_fd = curbuf->b_term->tl_job->jv_channel
1580 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001581#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001582 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001583
1584 /* Remember the terminal we are sending keys to. However, the terminal
1585 * might be closed while waiting for a character, e.g. typing "exit" in a
1586 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1587 * stored reference. */
1588 in_terminal_loop = curbuf->b_term;
1589
1590 if (*curwin->w_p_tk != NUL)
1591 termkey = string_to_key(curwin->w_p_tk, TRUE);
1592 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1593 may_set_cursor_props(curbuf->b_term);
1594
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595 while (blocking || vpeekc() != NUL)
1596 {
1597 /* TODO: skip screen update when handling a sequence of keys. */
1598 /* Repeat redrawing in case a message is received while redrawing. */
1599 while (must_redraw != 0)
1600 if (update_screen(0) == FAIL)
1601 break;
1602 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001603 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001604
1605 c = term_vgetc();
1606 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001607 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001608 /* Job finished while waiting for a character. Push back the
1609 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001610 if (c != K_IGNORE)
1611 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001612 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001613 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001614 if (c == K_IGNORE)
1615 continue;
1616
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001617#ifdef UNIX
1618 /*
1619 * The shell or another program may change the tty settings. Getting
1620 * them for every typed character is a bit of overhead, but it's needed
1621 * for the first character typed, e.g. when Vim starts in a shell.
1622 */
1623 if (isatty(tty_fd))
1624 {
1625 ttyinfo_T info;
1626
1627 /* Get the current backspace character of the pty. */
1628 if (get_tty_info(tty_fd, &info) == OK)
1629 term_backspace_char = info.backspace;
1630 }
1631#endif
1632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001633#ifdef WIN3264
1634 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1635 * Use CTRL-BREAK to kill the job. */
1636 if (ctrl_break_was_pressed)
1637 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1638#endif
1639 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1640 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1641 {
1642 int prev_c = c;
1643
1644#ifdef FEAT_CMDL_INFO
1645 if (add_to_showcmd(c))
1646 out_flush();
1647#endif
1648 c = term_vgetc();
1649#ifdef FEAT_CMDL_INFO
1650 clear_showcmd();
1651#endif
1652 if (!term_use_loop())
1653 /* job finished while waiting for a character */
1654 break;
1655
1656 if (prev_c == Ctrl_BSL)
1657 {
1658 if (c == Ctrl_N)
1659 {
1660 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1661 term_enter_normal_mode();
1662 ret = FAIL;
1663 goto theend;
1664 }
1665 /* Send both keys to the terminal. */
1666 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1667 }
1668 else if (c == Ctrl_C)
1669 {
1670 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1671 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1672 }
1673 else if (termkey == 0 && c == '.')
1674 {
1675 /* "CTRL-W .": send CTRL-W to the job */
1676 c = Ctrl_W;
1677 }
1678 else if (c == 'N')
1679 {
1680 /* CTRL-W N : go to Terminal-Normal mode. */
1681 term_enter_normal_mode();
1682 ret = FAIL;
1683 goto theend;
1684 }
1685 else if (c == '"')
1686 {
1687 term_paste_register(prev_c);
1688 continue;
1689 }
1690 else if (termkey == 0 || c != termkey)
1691 {
1692 stuffcharReadbuff(Ctrl_W);
1693 stuffcharReadbuff(c);
1694 ret = OK;
1695 goto theend;
1696 }
1697 }
1698# ifdef WIN3264
1699 if (!enc_utf8 && has_mbyte && c >= 0x80)
1700 {
1701 WCHAR wc;
1702 char_u mb[3];
1703
1704 mb[0] = (unsigned)c >> 8;
1705 mb[1] = c;
1706 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1707 c = wc;
1708 }
1709# endif
1710 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1711 {
Bram Moolenaard317b382018-02-08 22:33:31 +01001712 if (c == K_MOUSEMOVE)
1713 /* We are sure to come back here, don't reset the cursor color
1714 * and shape to avoid flickering. */
1715 restore_cursor = FALSE;
1716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 ret = OK;
1718 goto theend;
1719 }
1720 }
1721 ret = FAIL;
1722
1723theend:
1724 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01001725 if (restore_cursor)
1726 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 return ret;
1728}
1729
1730/*
1731 * Called when a job has finished.
1732 * This updates the title and status, but does not close the vterm, because
1733 * there might still be pending output in the channel.
1734 */
1735 void
1736term_job_ended(job_T *job)
1737{
1738 term_T *term;
1739 int did_one = FALSE;
1740
1741 for (term = first_term; term != NULL; term = term->tl_next)
1742 if (term->tl_job == job)
1743 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01001744 VIM_CLEAR(term->tl_title);
1745 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 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);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002026 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 if (term == curbuf->b_term)
2028 maketitle();
2029 break;
2030
2031 case VTERM_PROP_CURSORVISIBLE:
2032 term->tl_cursor_visible = value->boolean;
2033 may_toggle_cursor(term);
2034 out_flush();
2035 break;
2036
2037 case VTERM_PROP_CURSORBLINK:
2038 term->tl_cursor_blink = value->boolean;
2039 may_set_cursor_props(term);
2040 break;
2041
2042 case VTERM_PROP_CURSORSHAPE:
2043 term->tl_cursor_shape = value->number;
2044 may_set_cursor_props(term);
2045 break;
2046
2047 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002048 if (desired_cursor_color == term->tl_cursor_color)
2049 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002050 vim_free(term->tl_cursor_color);
2051 if (*value->string == NUL)
2052 term->tl_cursor_color = NULL;
2053 else
2054 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2055 may_set_cursor_props(term);
2056 break;
2057
2058 case VTERM_PROP_ALTSCREEN:
2059 /* TODO: do anything else? */
2060 term->tl_using_altscreen = value->boolean;
2061 break;
2062
2063 default:
2064 break;
2065 }
2066 /* Always return 1, otherwise vterm doesn't store the value internally. */
2067 return 1;
2068}
2069
2070/*
2071 * The job running in the terminal resized the terminal.
2072 */
2073 static int
2074handle_resize(int rows, int cols, void *user)
2075{
2076 term_T *term = (term_T *)user;
2077 win_T *wp;
2078
2079 term->tl_rows = rows;
2080 term->tl_cols = cols;
2081 if (term->tl_vterm_size_changed)
2082 /* Size was set by vterm_set_size(), don't set the window size. */
2083 term->tl_vterm_size_changed = FALSE;
2084 else
2085 {
2086 FOR_ALL_WINDOWS(wp)
2087 {
2088 if (wp->w_buffer == term->tl_buffer)
2089 {
2090 win_setheight_win(rows, wp);
2091 win_setwidth_win(cols, wp);
2092 }
2093 }
2094 redraw_buf_later(term->tl_buffer, NOT_VALID);
2095 }
2096 return 1;
2097}
2098
2099/*
2100 * Handle a line that is pushed off the top of the screen.
2101 */
2102 static int
2103handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2104{
2105 term_T *term = (term_T *)user;
2106
2107 /* TODO: Limit the number of lines that are stored. */
2108 if (ga_grow(&term->tl_scrollback, 1) == OK)
2109 {
2110 cellattr_T *p = NULL;
2111 int len = 0;
2112 int i;
2113 int c;
2114 int col;
2115 sb_line_T *line;
2116 garray_T ga;
2117 cellattr_T fill_attr = term->tl_default_color;
2118
2119 /* do not store empty cells at the end */
2120 for (i = 0; i < cols; ++i)
2121 if (cells[i].chars[0] != 0)
2122 len = i + 1;
2123 else
2124 cell2cellattr(&cells[i], &fill_attr);
2125
2126 ga_init2(&ga, 1, 100);
2127 if (len > 0)
2128 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2129 if (p != NULL)
2130 {
2131 for (col = 0; col < len; col += cells[col].width)
2132 {
2133 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2134 {
2135 ga.ga_len = 0;
2136 break;
2137 }
2138 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2139 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2140 (char_u *)ga.ga_data + ga.ga_len);
2141 cell2cellattr(&cells[col], &p[col]);
2142 }
2143 }
2144 if (ga_grow(&ga, 1) == FAIL)
2145 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2146 else
2147 {
2148 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2149 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2150 }
2151 ga_clear(&ga);
2152
2153 line = (sb_line_T *)term->tl_scrollback.ga_data
2154 + term->tl_scrollback.ga_len;
2155 line->sb_cols = len;
2156 line->sb_cells = p;
2157 line->sb_fill_attr = fill_attr;
2158 ++term->tl_scrollback.ga_len;
2159 ++term->tl_scrollback_scrolled;
2160 }
2161 return 0; /* ignored */
2162}
2163
2164static VTermScreenCallbacks screen_callbacks = {
2165 handle_damage, /* damage */
2166 handle_moverect, /* moverect */
2167 handle_movecursor, /* movecursor */
2168 handle_settermprop, /* settermprop */
2169 NULL, /* bell */
2170 handle_resize, /* resize */
2171 handle_pushline, /* sb_pushline */
2172 NULL /* sb_popline */
2173};
2174
2175/*
2176 * Called when a channel has been closed.
2177 * If this was a channel for a terminal window then finish it up.
2178 */
2179 void
2180term_channel_closed(channel_T *ch)
2181{
2182 term_T *term;
2183 int did_one = FALSE;
2184
2185 for (term = first_term; term != NULL; term = term->tl_next)
2186 if (term->tl_job == ch->ch_job)
2187 {
2188 term->tl_channel_closed = TRUE;
2189 did_one = TRUE;
2190
Bram Moolenaard23a8232018-02-10 18:45:26 +01002191 VIM_CLEAR(term->tl_title);
2192 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193
2194 /* Unless in Terminal-Normal mode: clear the vterm. */
2195 if (!term->tl_normal_mode)
2196 {
2197 int fnum = term->tl_buffer->b_fnum;
2198
2199 cleanup_vterm(term);
2200
2201 if (term->tl_finish == 'c')
2202 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002203 aco_save_T aco;
2204
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002205 /* ++close or term_finish == "close" */
2206 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002207 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002209 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210 break;
2211 }
2212 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2213 {
2214 char buf[50];
2215
2216 /* TODO: use term_opencmd */
2217 ch_log(NULL, "terminal job finished, opening window");
2218 vim_snprintf(buf, sizeof(buf),
2219 term->tl_opencmd == NULL
2220 ? "botright sbuf %d"
2221 : (char *)term->tl_opencmd, fnum);
2222 do_cmdline_cmd((char_u *)buf);
2223 }
2224 else
2225 ch_log(NULL, "terminal job finished");
2226 }
2227
2228 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2229 }
2230 if (did_one)
2231 {
2232 redraw_statuslines();
2233
2234 /* Need to break out of vgetc(). */
2235 ins_char_typebuf(K_IGNORE);
2236 typebuf_was_filled = TRUE;
2237
2238 term = curbuf->b_term;
2239 if (term != NULL)
2240 {
2241 if (term->tl_job == ch->ch_job)
2242 maketitle();
2243 update_cursor(term, term->tl_cursor_visible);
2244 }
2245 }
2246}
2247
2248/*
2249 * Called to update a window that contains an active terminal.
2250 * Returns FAIL when there is no terminal running in this window or in
2251 * Terminal-Normal mode.
2252 */
2253 int
2254term_update_window(win_T *wp)
2255{
2256 term_T *term = wp->w_buffer->b_term;
2257 VTerm *vterm;
2258 VTermScreen *screen;
2259 VTermState *state;
2260 VTermPos pos;
2261
2262 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2263 return FAIL;
2264
2265 vterm = term->tl_vterm;
2266 screen = vterm_obtain_screen(vterm);
2267 state = vterm_obtain_state(vterm);
2268
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002269 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002270 {
2271 term->tl_dirty_row_start = 0;
2272 term->tl_dirty_row_end = MAX_ROW;
2273 }
2274
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 /*
2276 * If the window was resized a redraw will be triggered and we get here.
2277 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2278 */
2279 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2280 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2281 {
2282 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2283 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2284 win_T *twp;
2285
2286 FOR_ALL_WINDOWS(twp)
2287 {
2288 /* When more than one window shows the same terminal, use the
2289 * smallest size. */
2290 if (twp->w_buffer == term->tl_buffer)
2291 {
2292 if (!term->tl_rows_fixed && rows > twp->w_height)
2293 rows = twp->w_height;
2294 if (!term->tl_cols_fixed && cols > twp->w_width)
2295 cols = twp->w_width;
2296 }
2297 }
2298
2299 term->tl_vterm_size_changed = TRUE;
2300 vterm_set_size(vterm, rows, cols);
2301 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2302 rows);
2303 term_report_winsize(term, rows, cols);
2304 }
2305
2306 /* The cursor may have been moved when resizing. */
2307 vterm_state_get_cursorpos(state, &pos);
2308 position_cursor(wp, &pos);
2309
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002310 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2311 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002312 {
2313 int off = screen_get_current_line_off();
2314 int max_col = MIN(wp->w_width, term->tl_cols);
2315
2316 if (pos.row < term->tl_rows)
2317 {
2318 for (pos.col = 0; pos.col < max_col; )
2319 {
2320 VTermScreenCell cell;
2321 int c;
2322
2323 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2324 vim_memset(&cell, 0, sizeof(cell));
2325
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002326 c = cell.chars[0];
2327 if (c == NUL)
2328 {
2329 ScreenLines[off] = ' ';
2330 if (enc_utf8)
2331 ScreenLinesUC[off] = NUL;
2332 }
2333 else
2334 {
2335 if (enc_utf8)
2336 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002337 int i;
2338
2339 /* composing chars */
2340 for (i = 0; i < Screen_mco
2341 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2342 {
2343 ScreenLinesC[i][off] = cell.chars[i + 1];
2344 if (cell.chars[i + 1] == 0)
2345 break;
2346 }
2347 if (c >= 0x80 || (Screen_mco > 0
2348 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002349 {
2350 ScreenLines[off] = ' ';
2351 ScreenLinesUC[off] = c;
2352 }
2353 else
2354 {
2355 ScreenLines[off] = c;
2356 ScreenLinesUC[off] = NUL;
2357 }
2358 }
2359#ifdef WIN3264
2360 else if (has_mbyte && c >= 0x80)
2361 {
2362 char_u mb[MB_MAXBYTES+1];
2363 WCHAR wc = c;
2364
2365 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2366 (char*)mb, 2, 0, 0) > 1)
2367 {
2368 ScreenLines[off] = mb[0];
2369 ScreenLines[off + 1] = mb[1];
2370 cell.width = mb_ptr2cells(mb);
2371 }
2372 else
2373 ScreenLines[off] = c;
2374 }
2375#endif
2376 else
2377 ScreenLines[off] = c;
2378 }
2379 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2380
2381 ++pos.col;
2382 ++off;
2383 if (cell.width == 2)
2384 {
2385 if (enc_utf8)
2386 ScreenLinesUC[off] = NUL;
2387
2388 /* don't set the second byte to NUL for a DBCS encoding, it
2389 * has been set above */
2390 if (enc_utf8 || !has_mbyte)
2391 ScreenLines[off] = NUL;
2392
2393 ++pos.col;
2394 ++off;
2395 }
2396 }
2397 }
2398 else
2399 pos.col = 0;
2400
2401 screen_line(wp->w_winrow + pos.row, wp->w_wincol,
2402 pos.col, wp->w_width, FALSE);
2403 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002404 term->tl_dirty_row_start = MAX_ROW;
2405 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002406
2407 return OK;
2408}
2409
2410/*
2411 * Return TRUE if "wp" is a terminal window where the job has finished.
2412 */
2413 int
2414term_is_finished(buf_T *buf)
2415{
2416 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2417}
2418
2419/*
2420 * Return TRUE if "wp" is a terminal window where the job has finished or we
2421 * are in Terminal-Normal mode, thus we show the buffer contents.
2422 */
2423 int
2424term_show_buffer(buf_T *buf)
2425{
2426 term_T *term = buf->b_term;
2427
2428 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2429}
2430
2431/*
2432 * The current buffer is going to be changed. If there is terminal
2433 * highlighting remove it now.
2434 */
2435 void
2436term_change_in_curbuf(void)
2437{
2438 term_T *term = curbuf->b_term;
2439
2440 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2441 {
2442 free_scrollback(term);
2443 redraw_buf_later(term->tl_buffer, NOT_VALID);
2444
2445 /* The buffer is now like a normal buffer, it cannot be easily
2446 * abandoned when changed. */
2447 set_string_option_direct((char_u *)"buftype", -1,
2448 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2449 }
2450}
2451
2452/*
2453 * Get the screen attribute for a position in the buffer.
2454 * Use a negative "col" to get the filler background color.
2455 */
2456 int
2457term_get_attr(buf_T *buf, linenr_T lnum, int col)
2458{
2459 term_T *term = buf->b_term;
2460 sb_line_T *line;
2461 cellattr_T *cellattr;
2462
2463 if (lnum > term->tl_scrollback.ga_len)
2464 cellattr = &term->tl_default_color;
2465 else
2466 {
2467 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2468 if (col < 0 || col >= line->sb_cols)
2469 cellattr = &line->sb_fill_attr;
2470 else
2471 cellattr = line->sb_cells + col;
2472 }
2473 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2474}
2475
2476static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002477 { 0, 0, 0, 1}, /* black */
2478 {224, 0, 0, 2}, /* dark red */
2479 { 0, 224, 0, 3}, /* dark green */
2480 {224, 224, 0, 4}, /* dark yellow / brown */
2481 { 0, 0, 224, 5}, /* dark blue */
2482 {224, 0, 224, 6}, /* dark magenta */
2483 { 0, 224, 224, 7}, /* dark cyan */
2484 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485
Bram Moolenaar46359e12017-11-29 22:33:38 +01002486 {128, 128, 128, 9}, /* dark grey */
2487 {255, 64, 64, 10}, /* light red */
2488 { 64, 255, 64, 11}, /* light green */
2489 {255, 255, 64, 12}, /* yellow */
2490 { 64, 64, 255, 13}, /* light blue */
2491 {255, 64, 255, 14}, /* light magenta */
2492 { 64, 255, 255, 15}, /* light cyan */
2493 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494};
2495
2496static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002497 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002498};
2499
2500static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002501 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2502 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503};
2504
2505/*
2506 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002507 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 */
2509 static void
2510cterm_color2rgb(int nr, VTermColor *rgb)
2511{
2512 int idx;
2513
2514 if (nr < 16)
2515 {
2516 *rgb = ansi_table[nr];
2517 }
2518 else if (nr < 232)
2519 {
2520 /* 216 color cube */
2521 idx = nr - 16;
2522 rgb->blue = cube_value[idx % 6];
2523 rgb->green = cube_value[idx / 6 % 6];
2524 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002525 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 }
2527 else if (nr < 256)
2528 {
2529 /* 24 grey scale ramp */
2530 idx = nr - 232;
2531 rgb->blue = grey_ramp[idx];
2532 rgb->green = grey_ramp[idx];
2533 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002534 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 }
2536}
2537
2538/*
2539 * Create a new vterm and initialize it.
2540 */
2541 static void
2542create_vterm(term_T *term, int rows, int cols)
2543{
2544 VTerm *vterm;
2545 VTermScreen *screen;
2546 VTermValue value;
2547 VTermColor *fg, *bg;
2548 int fgval, bgval;
2549 int id;
2550
2551 vterm = vterm_new(rows, cols);
2552 term->tl_vterm = vterm;
2553 screen = vterm_obtain_screen(vterm);
2554 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2555 /* TODO: depends on 'encoding'. */
2556 vterm_set_utf8(vterm, 1);
2557
2558 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2559 term->tl_default_color.width = 1;
2560 fg = &term->tl_default_color.fg;
2561 bg = &term->tl_default_color.bg;
2562
2563 /* Vterm uses a default black background. Set it to white when
2564 * 'background' is "light". */
2565 if (*p_bg == 'l')
2566 {
2567 fgval = 0;
2568 bgval = 255;
2569 }
2570 else
2571 {
2572 fgval = 255;
2573 bgval = 0;
2574 }
2575 fg->red = fg->green = fg->blue = fgval;
2576 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002577 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578
2579 /* The "Terminal" highlight group overrules the defaults. */
2580 id = syn_name2id((char_u *)"Terminal");
2581
Bram Moolenaar46359e12017-11-29 22:33:38 +01002582 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2584 if (0
2585# ifdef FEAT_GUI
2586 || gui.in_use
2587# endif
2588# ifdef FEAT_TERMGUICOLORS
2589 || p_tgc
2590# endif
2591 )
2592 {
2593 guicolor_T fg_rgb = INVALCOLOR;
2594 guicolor_T bg_rgb = INVALCOLOR;
2595
2596 if (id != 0)
2597 syn_id2colors(id, &fg_rgb, &bg_rgb);
2598
2599# ifdef FEAT_GUI
2600 if (gui.in_use)
2601 {
2602 if (fg_rgb == INVALCOLOR)
2603 fg_rgb = gui.norm_pixel;
2604 if (bg_rgb == INVALCOLOR)
2605 bg_rgb = gui.back_pixel;
2606 }
2607# ifdef FEAT_TERMGUICOLORS
2608 else
2609# endif
2610# endif
2611# ifdef FEAT_TERMGUICOLORS
2612 {
2613 if (fg_rgb == INVALCOLOR)
2614 fg_rgb = cterm_normal_fg_gui_color;
2615 if (bg_rgb == INVALCOLOR)
2616 bg_rgb = cterm_normal_bg_gui_color;
2617 }
2618# endif
2619 if (fg_rgb != INVALCOLOR)
2620 {
2621 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2622
2623 fg->red = (unsigned)(rgb >> 16);
2624 fg->green = (unsigned)(rgb >> 8) & 255;
2625 fg->blue = (unsigned)rgb & 255;
2626 }
2627 if (bg_rgb != INVALCOLOR)
2628 {
2629 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2630
2631 bg->red = (unsigned)(rgb >> 16);
2632 bg->green = (unsigned)(rgb >> 8) & 255;
2633 bg->blue = (unsigned)rgb & 255;
2634 }
2635 }
2636 else
2637#endif
2638 if (id != 0 && t_colors >= 16)
2639 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002640 if (term_default_cterm_fg >= 0)
2641 cterm_color2rgb(term_default_cterm_fg, fg);
2642 if (term_default_cterm_bg >= 0)
2643 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002644 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645 else
2646 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002647#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002648 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002649#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650
2651 /* In an MS-Windows console we know the normal colors. */
2652 if (cterm_normal_fg_color > 0)
2653 {
2654 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002655# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 tmp = fg->red;
2657 fg->red = fg->blue;
2658 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002659# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002660 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002661# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002662 else
2663 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002664# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002666 if (cterm_normal_bg_color > 0)
2667 {
2668 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002669# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002670 tmp = bg->red;
2671 bg->red = bg->blue;
2672 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002673# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002674 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002675# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002676 else
2677 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002678# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002679 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002680
2681 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2682
2683 /* Required to initialize most things. */
2684 vterm_screen_reset(screen, 1 /* hard */);
2685
2686 /* Allow using alternate screen. */
2687 vterm_screen_enable_altscreen(screen, 1);
2688
2689 /* For unix do not use a blinking cursor. In an xterm this causes the
2690 * cursor to blink if it's blinking in the xterm.
2691 * For Windows we respect the system wide setting. */
2692#ifdef WIN3264
2693 if (GetCaretBlinkTime() == INFINITE)
2694 value.boolean = 0;
2695 else
2696 value.boolean = 1;
2697#else
2698 value.boolean = 0;
2699#endif
2700 vterm_state_set_termprop(vterm_obtain_state(vterm),
2701 VTERM_PROP_CURSORBLINK, &value);
2702}
2703
2704/*
2705 * Return the text to show for the buffer name and status.
2706 */
2707 char_u *
2708term_get_status_text(term_T *term)
2709{
2710 if (term->tl_status_text == NULL)
2711 {
2712 char_u *txt;
2713 size_t len;
2714
2715 if (term->tl_normal_mode)
2716 {
2717 if (term_job_running(term))
2718 txt = (char_u *)_("Terminal");
2719 else
2720 txt = (char_u *)_("Terminal-finished");
2721 }
2722 else if (term->tl_title != NULL)
2723 txt = term->tl_title;
2724 else if (term_none_open(term))
2725 txt = (char_u *)_("active");
2726 else if (term_job_running(term))
2727 txt = (char_u *)_("running");
2728 else
2729 txt = (char_u *)_("finished");
2730 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2731 term->tl_status_text = alloc((int)len);
2732 if (term->tl_status_text != NULL)
2733 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2734 term->tl_buffer->b_fname, txt);
2735 }
2736 return term->tl_status_text;
2737}
2738
2739/*
2740 * Mark references in jobs of terminals.
2741 */
2742 int
2743set_ref_in_term(int copyID)
2744{
2745 int abort = FALSE;
2746 term_T *term;
2747 typval_T tv;
2748
2749 for (term = first_term; term != NULL; term = term->tl_next)
2750 if (term->tl_job != NULL)
2751 {
2752 tv.v_type = VAR_JOB;
2753 tv.vval.v_job = term->tl_job;
2754 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2755 }
2756 return abort;
2757}
2758
2759/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002760 * Cache "Terminal" highlight group colors.
2761 */
2762 void
2763set_terminal_default_colors(int cterm_fg, int cterm_bg)
2764{
2765 term_default_cterm_fg = cterm_fg - 1;
2766 term_default_cterm_bg = cterm_bg - 1;
2767}
2768
2769/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002770 * Get the buffer from the first argument in "argvars".
2771 * Returns NULL when the buffer is not for a terminal window.
2772 */
2773 static buf_T *
2774term_get_buf(typval_T *argvars)
2775{
2776 buf_T *buf;
2777
2778 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2779 ++emsg_off;
2780 buf = get_buf_tv(&argvars[0], FALSE);
2781 --emsg_off;
2782 if (buf == NULL || buf->b_term == NULL)
2783 return NULL;
2784 return buf;
2785}
2786
2787/*
2788 * "term_getaltscreen(buf)" function
2789 */
2790 void
2791f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2792{
2793 buf_T *buf = term_get_buf(argvars);
2794
2795 if (buf == NULL)
2796 return;
2797 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2798}
2799
2800/*
2801 * "term_getattr(attr, name)" function
2802 */
2803 void
2804f_term_getattr(typval_T *argvars, typval_T *rettv)
2805{
2806 int attr;
2807 size_t i;
2808 char_u *name;
2809
2810 static struct {
2811 char *name;
2812 int attr;
2813 } attrs[] = {
2814 {"bold", HL_BOLD},
2815 {"italic", HL_ITALIC},
2816 {"underline", HL_UNDERLINE},
2817 {"strike", HL_STRIKETHROUGH},
2818 {"reverse", HL_INVERSE},
2819 };
2820
2821 attr = get_tv_number(&argvars[0]);
2822 name = get_tv_string_chk(&argvars[1]);
2823 if (name == NULL)
2824 return;
2825
2826 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2827 if (STRCMP(name, attrs[i].name) == 0)
2828 {
2829 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2830 break;
2831 }
2832}
2833
2834/*
2835 * "term_getcursor(buf)" function
2836 */
2837 void
2838f_term_getcursor(typval_T *argvars, typval_T *rettv)
2839{
2840 buf_T *buf = term_get_buf(argvars);
2841 term_T *term;
2842 list_T *l;
2843 dict_T *d;
2844
2845 if (rettv_list_alloc(rettv) == FAIL)
2846 return;
2847 if (buf == NULL)
2848 return;
2849 term = buf->b_term;
2850
2851 l = rettv->vval.v_list;
2852 list_append_number(l, term->tl_cursor_pos.row + 1);
2853 list_append_number(l, term->tl_cursor_pos.col + 1);
2854
2855 d = dict_alloc();
2856 if (d != NULL)
2857 {
2858 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2859 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2860 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2861 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2862 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2863 ? (char_u *)"" : term->tl_cursor_color);
2864 list_append_dict(l, d);
2865 }
2866}
2867
2868/*
2869 * "term_getjob(buf)" function
2870 */
2871 void
2872f_term_getjob(typval_T *argvars, typval_T *rettv)
2873{
2874 buf_T *buf = term_get_buf(argvars);
2875
2876 rettv->v_type = VAR_JOB;
2877 rettv->vval.v_job = NULL;
2878 if (buf == NULL)
2879 return;
2880
2881 rettv->vval.v_job = buf->b_term->tl_job;
2882 if (rettv->vval.v_job != NULL)
2883 ++rettv->vval.v_job->jv_refcount;
2884}
2885
2886 static int
2887get_row_number(typval_T *tv, term_T *term)
2888{
2889 if (tv->v_type == VAR_STRING
2890 && tv->vval.v_string != NULL
2891 && STRCMP(tv->vval.v_string, ".") == 0)
2892 return term->tl_cursor_pos.row;
2893 return (int)get_tv_number(tv) - 1;
2894}
2895
2896/*
2897 * "term_getline(buf, row)" function
2898 */
2899 void
2900f_term_getline(typval_T *argvars, typval_T *rettv)
2901{
2902 buf_T *buf = term_get_buf(argvars);
2903 term_T *term;
2904 int row;
2905
2906 rettv->v_type = VAR_STRING;
2907 if (buf == NULL)
2908 return;
2909 term = buf->b_term;
2910 row = get_row_number(&argvars[1], term);
2911
2912 if (term->tl_vterm == NULL)
2913 {
2914 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2915
2916 /* vterm is finished, get the text from the buffer */
2917 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2918 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2919 }
2920 else
2921 {
2922 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2923 VTermRect rect;
2924 int len;
2925 char_u *p;
2926
2927 if (row < 0 || row >= term->tl_rows)
2928 return;
2929 len = term->tl_cols * MB_MAXBYTES + 1;
2930 p = alloc(len);
2931 if (p == NULL)
2932 return;
2933 rettv->vval.v_string = p;
2934
2935 rect.start_col = 0;
2936 rect.end_col = term->tl_cols;
2937 rect.start_row = row;
2938 rect.end_row = row + 1;
2939 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2940 }
2941}
2942
2943/*
2944 * "term_getscrolled(buf)" function
2945 */
2946 void
2947f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2948{
2949 buf_T *buf = term_get_buf(argvars);
2950
2951 if (buf == NULL)
2952 return;
2953 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2954}
2955
2956/*
2957 * "term_getsize(buf)" function
2958 */
2959 void
2960f_term_getsize(typval_T *argvars, typval_T *rettv)
2961{
2962 buf_T *buf = term_get_buf(argvars);
2963 list_T *l;
2964
2965 if (rettv_list_alloc(rettv) == FAIL)
2966 return;
2967 if (buf == NULL)
2968 return;
2969
2970 l = rettv->vval.v_list;
2971 list_append_number(l, buf->b_term->tl_rows);
2972 list_append_number(l, buf->b_term->tl_cols);
2973}
2974
2975/*
2976 * "term_getstatus(buf)" function
2977 */
2978 void
2979f_term_getstatus(typval_T *argvars, typval_T *rettv)
2980{
2981 buf_T *buf = term_get_buf(argvars);
2982 term_T *term;
2983 char_u val[100];
2984
2985 rettv->v_type = VAR_STRING;
2986 if (buf == NULL)
2987 return;
2988 term = buf->b_term;
2989
2990 if (term_job_running(term))
2991 STRCPY(val, "running");
2992 else
2993 STRCPY(val, "finished");
2994 if (term->tl_normal_mode)
2995 STRCAT(val, ",normal");
2996 rettv->vval.v_string = vim_strsave(val);
2997}
2998
2999/*
3000 * "term_gettitle(buf)" function
3001 */
3002 void
3003f_term_gettitle(typval_T *argvars, typval_T *rettv)
3004{
3005 buf_T *buf = term_get_buf(argvars);
3006
3007 rettv->v_type = VAR_STRING;
3008 if (buf == NULL)
3009 return;
3010
3011 if (buf->b_term->tl_title != NULL)
3012 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
3013}
3014
3015/*
3016 * "term_gettty(buf)" function
3017 */
3018 void
3019f_term_gettty(typval_T *argvars, typval_T *rettv)
3020{
3021 buf_T *buf = term_get_buf(argvars);
3022 char_u *p;
3023 int num = 0;
3024
3025 rettv->v_type = VAR_STRING;
3026 if (buf == NULL)
3027 return;
3028 if (argvars[1].v_type != VAR_UNKNOWN)
3029 num = get_tv_number(&argvars[1]);
3030
3031 switch (num)
3032 {
3033 case 0:
3034 if (buf->b_term->tl_job != NULL)
3035 p = buf->b_term->tl_job->jv_tty_out;
3036 else
3037 p = buf->b_term->tl_tty_out;
3038 break;
3039 case 1:
3040 if (buf->b_term->tl_job != NULL)
3041 p = buf->b_term->tl_job->jv_tty_in;
3042 else
3043 p = buf->b_term->tl_tty_in;
3044 break;
3045 default:
3046 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
3047 return;
3048 }
3049 if (p != NULL)
3050 rettv->vval.v_string = vim_strsave(p);
3051}
3052
3053/*
3054 * "term_list()" function
3055 */
3056 void
3057f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3058{
3059 term_T *tp;
3060 list_T *l;
3061
3062 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3063 return;
3064
3065 l = rettv->vval.v_list;
3066 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3067 if (tp != NULL && tp->tl_buffer != NULL)
3068 if (list_append_number(l,
3069 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3070 return;
3071}
3072
3073/*
3074 * "term_scrape(buf, row)" function
3075 */
3076 void
3077f_term_scrape(typval_T *argvars, typval_T *rettv)
3078{
3079 buf_T *buf = term_get_buf(argvars);
3080 VTermScreen *screen = NULL;
3081 VTermPos pos;
3082 list_T *l;
3083 term_T *term;
3084 char_u *p;
3085 sb_line_T *line;
3086
3087 if (rettv_list_alloc(rettv) == FAIL)
3088 return;
3089 if (buf == NULL)
3090 return;
3091 term = buf->b_term;
3092
3093 l = rettv->vval.v_list;
3094 pos.row = get_row_number(&argvars[1], term);
3095
3096 if (term->tl_vterm != NULL)
3097 {
3098 screen = vterm_obtain_screen(term->tl_vterm);
3099 p = NULL;
3100 line = NULL;
3101 }
3102 else
3103 {
3104 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3105
3106 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3107 return;
3108 p = ml_get_buf(buf, lnum + 1, FALSE);
3109 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3110 }
3111
3112 for (pos.col = 0; pos.col < term->tl_cols; )
3113 {
3114 dict_T *dcell;
3115 int width;
3116 VTermScreenCellAttrs attrs;
3117 VTermColor fg, bg;
3118 char_u rgb[8];
3119 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3120 int off = 0;
3121 int i;
3122
3123 if (screen == NULL)
3124 {
3125 cellattr_T *cellattr;
3126 int len;
3127
3128 /* vterm has finished, get the cell from scrollback */
3129 if (pos.col >= line->sb_cols)
3130 break;
3131 cellattr = line->sb_cells + pos.col;
3132 width = cellattr->width;
3133 attrs = cellattr->attrs;
3134 fg = cellattr->fg;
3135 bg = cellattr->bg;
3136 len = MB_PTR2LEN(p);
3137 mch_memmove(mbs, p, len);
3138 mbs[len] = NUL;
3139 p += len;
3140 }
3141 else
3142 {
3143 VTermScreenCell cell;
3144 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3145 break;
3146 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3147 {
3148 if (cell.chars[i] == 0)
3149 break;
3150 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3151 }
3152 mbs[off] = NUL;
3153 width = cell.width;
3154 attrs = cell.attrs;
3155 fg = cell.fg;
3156 bg = cell.bg;
3157 }
3158 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01003159 if (dcell == NULL)
3160 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003161 list_append_dict(l, dcell);
3162
3163 dict_add_nr_str(dcell, "chars", 0, mbs);
3164
3165 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3166 fg.red, fg.green, fg.blue);
3167 dict_add_nr_str(dcell, "fg", 0, rgb);
3168 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3169 bg.red, bg.green, bg.blue);
3170 dict_add_nr_str(dcell, "bg", 0, rgb);
3171
3172 dict_add_nr_str(dcell, "attr",
3173 cell2attr(attrs, fg, bg), NULL);
3174 dict_add_nr_str(dcell, "width", width, NULL);
3175
3176 ++pos.col;
3177 if (width == 2)
3178 ++pos.col;
3179 }
3180}
3181
3182/*
3183 * "term_sendkeys(buf, keys)" function
3184 */
3185 void
3186f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3187{
3188 buf_T *buf = term_get_buf(argvars);
3189 char_u *msg;
3190 term_T *term;
3191
3192 rettv->v_type = VAR_UNKNOWN;
3193 if (buf == NULL)
3194 return;
3195
3196 msg = get_tv_string_chk(&argvars[1]);
3197 if (msg == NULL)
3198 return;
3199 term = buf->b_term;
3200 if (term->tl_vterm == NULL)
3201 return;
3202
3203 while (*msg != NUL)
3204 {
3205 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003206 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 }
3208}
3209
3210/*
3211 * "term_start(command, options)" function
3212 */
3213 void
3214f_term_start(typval_T *argvars, typval_T *rettv)
3215{
3216 jobopt_T opt;
3217 buf_T *buf;
3218
3219 init_job_options(&opt);
3220 if (argvars[1].v_type != VAR_UNKNOWN
3221 && get_job_options(&argvars[1], &opt,
3222 JO_TIMEOUT_ALL + JO_STOPONEXIT
3223 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3224 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3225 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3226 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3227 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3228 return;
3229
3230 if (opt.jo_vertical)
3231 cmdmod.split = WSP_VERT;
3232 buf = term_start(&argvars[0], &opt, FALSE);
3233
3234 if (buf != NULL && buf->b_term != NULL)
3235 rettv->vval.v_number = buf->b_fnum;
3236}
3237
3238/*
3239 * "term_wait" function
3240 */
3241 void
3242f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3243{
3244 buf_T *buf = term_get_buf(argvars);
3245
3246 if (buf == NULL)
3247 {
3248 ch_log(NULL, "term_wait(): invalid argument");
3249 return;
3250 }
3251 if (buf->b_term->tl_job == NULL)
3252 {
3253 ch_log(NULL, "term_wait(): no job to wait for");
3254 return;
3255 }
3256 if (buf->b_term->tl_job->jv_channel == NULL)
3257 /* channel is closed, nothing to do */
3258 return;
3259
3260 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01003261 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003262 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3263 {
3264 /* The job is dead, keep reading channel I/O until the channel is
3265 * closed. buf->b_term may become NULL if the terminal was closed while
3266 * waiting. */
3267 ch_log(NULL, "term_wait(): waiting for channel to close");
3268 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3269 {
3270 mch_check_messages();
3271 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01003272 if (!buf_valid(buf))
3273 /* If the terminal is closed when the channel is closed the
3274 * buffer disappears. */
3275 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003276 ui_delay(10L, FALSE);
3277 }
3278 mch_check_messages();
3279 parse_queued_messages();
3280 }
3281 else
3282 {
3283 long wait = 10L;
3284
3285 mch_check_messages();
3286 parse_queued_messages();
3287
3288 /* Wait for some time for any channel I/O. */
3289 if (argvars[1].v_type != VAR_UNKNOWN)
3290 wait = get_tv_number(&argvars[1]);
3291 ui_delay(wait, TRUE);
3292 mch_check_messages();
3293
3294 /* Flushing messages on channels is hopefully sufficient.
3295 * TODO: is there a better way? */
3296 parse_queued_messages();
3297 }
3298}
3299
3300/*
3301 * Called when a channel has sent all the lines to a terminal.
3302 * Send a CTRL-D to mark the end of the text.
3303 */
3304 void
3305term_send_eof(channel_T *ch)
3306{
3307 term_T *term;
3308
3309 for (term = first_term; term != NULL; term = term->tl_next)
3310 if (term->tl_job == ch->ch_job)
3311 {
3312 if (term->tl_eof_chars != NULL)
3313 {
3314 channel_send(ch, PART_IN, term->tl_eof_chars,
3315 (int)STRLEN(term->tl_eof_chars), NULL);
3316 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3317 }
3318# ifdef WIN3264
3319 else
3320 /* Default: CTRL-D */
3321 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3322# endif
3323 }
3324}
3325
3326# if defined(WIN3264) || defined(PROTO)
3327
3328/**************************************
3329 * 2. MS-Windows implementation.
3330 */
3331
3332# ifndef PROTO
3333
3334#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3335#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01003336#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337
3338void* (*winpty_config_new)(UINT64, void*);
3339void* (*winpty_open)(void*, void*);
3340void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3341BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3342void (*winpty_config_set_mouse_mode)(void*, int);
3343void (*winpty_config_set_initial_size)(void*, int, int);
3344LPCWSTR (*winpty_conin_name)(void*);
3345LPCWSTR (*winpty_conout_name)(void*);
3346LPCWSTR (*winpty_conerr_name)(void*);
3347void (*winpty_free)(void*);
3348void (*winpty_config_free)(void*);
3349void (*winpty_spawn_config_free)(void*);
3350void (*winpty_error_free)(void*);
3351LPCWSTR (*winpty_error_msg)(void*);
3352BOOL (*winpty_set_size)(void*, int, int, void*);
3353HANDLE (*winpty_agent_process)(void*);
3354
3355#define WINPTY_DLL "winpty.dll"
3356
3357static HINSTANCE hWinPtyDLL = NULL;
3358# endif
3359
3360 static int
3361dyn_winpty_init(int verbose)
3362{
3363 int i;
3364 static struct
3365 {
3366 char *name;
3367 FARPROC *ptr;
3368 } winpty_entry[] =
3369 {
3370 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3371 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3372 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3373 {"winpty_config_set_mouse_mode",
3374 (FARPROC*)&winpty_config_set_mouse_mode},
3375 {"winpty_config_set_initial_size",
3376 (FARPROC*)&winpty_config_set_initial_size},
3377 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3378 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3379 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3380 {"winpty_free", (FARPROC*)&winpty_free},
3381 {"winpty_open", (FARPROC*)&winpty_open},
3382 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3383 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3384 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3385 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3386 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3387 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3388 {NULL, NULL}
3389 };
3390
3391 /* No need to initialize twice. */
3392 if (hWinPtyDLL)
3393 return OK;
3394 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3395 * winpty.dll. */
3396 if (*p_winptydll != NUL)
3397 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3398 if (!hWinPtyDLL)
3399 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3400 if (!hWinPtyDLL)
3401 {
3402 if (verbose)
3403 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3404 : (char_u *)WINPTY_DLL);
3405 return FAIL;
3406 }
3407 for (i = 0; winpty_entry[i].name != NULL
3408 && winpty_entry[i].ptr != NULL; ++i)
3409 {
3410 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3411 winpty_entry[i].name)) == NULL)
3412 {
3413 if (verbose)
3414 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3415 return FAIL;
3416 }
3417 }
3418
3419 return OK;
3420}
3421
3422/*
3423 * Create a new terminal of "rows" by "cols" cells.
3424 * Store a reference in "term".
3425 * Return OK or FAIL.
3426 */
3427 static int
3428term_and_job_init(
3429 term_T *term,
3430 typval_T *argvar,
3431 jobopt_T *opt)
3432{
3433 WCHAR *cmd_wchar = NULL;
3434 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003435 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003436 channel_T *channel = NULL;
3437 job_T *job = NULL;
3438 DWORD error;
3439 HANDLE jo = NULL;
3440 HANDLE child_process_handle;
3441 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01003442 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003443 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003444 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003445 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003446
3447 if (dyn_winpty_init(TRUE) == FAIL)
3448 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003449 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
3450 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003451
3452 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003453 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003454 cmd = argvar->vval.v_string;
3455 }
3456 else if (argvar->v_type == VAR_LIST)
3457 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003458 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003459 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003460 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003461 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003462 if (cmd == NULL || *cmd == NUL)
3463 {
3464 EMSG(_(e_invarg));
3465 goto failed;
3466 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467
3468 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003469 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003470 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003471 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003472 if (opt->jo_cwd != NULL)
3473 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003474
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003475 win32_build_env(opt->jo_env, &ga_env, TRUE);
3476 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003477
3478 job = job_alloc();
3479 if (job == NULL)
3480 goto failed;
3481
3482 channel = add_channel();
3483 if (channel == NULL)
3484 goto failed;
3485
3486 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3487 if (term->tl_winpty_config == NULL)
3488 goto failed;
3489
3490 winpty_config_set_mouse_mode(term->tl_winpty_config,
3491 WINPTY_MOUSE_MODE_FORCE);
3492 winpty_config_set_initial_size(term->tl_winpty_config,
3493 term->tl_cols, term->tl_rows);
3494 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3495 if (term->tl_winpty == NULL)
3496 goto failed;
3497
3498 spawn_config = winpty_spawn_config_new(
3499 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3500 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3501 NULL,
3502 cmd_wchar,
3503 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003504 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003505 &winpty_err);
3506 if (spawn_config == NULL)
3507 goto failed;
3508
3509 channel = add_channel();
3510 if (channel == NULL)
3511 goto failed;
3512
3513 job = job_alloc();
3514 if (job == NULL)
3515 goto failed;
3516
3517 if (opt->jo_set & JO_IN_BUF)
3518 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3519
3520 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3521 &child_thread_handle, &error, &winpty_err))
3522 goto failed;
3523
3524 channel_set_pipes(channel,
3525 (sock_T)CreateFileW(
3526 winpty_conin_name(term->tl_winpty),
3527 GENERIC_WRITE, 0, NULL,
3528 OPEN_EXISTING, 0, NULL),
3529 (sock_T)CreateFileW(
3530 winpty_conout_name(term->tl_winpty),
3531 GENERIC_READ, 0, NULL,
3532 OPEN_EXISTING, 0, NULL),
3533 (sock_T)CreateFileW(
3534 winpty_conerr_name(term->tl_winpty),
3535 GENERIC_READ, 0, NULL,
3536 OPEN_EXISTING, 0, NULL));
3537
3538 /* Write lines with CR instead of NL. */
3539 channel->ch_write_text_mode = TRUE;
3540
3541 jo = CreateJobObject(NULL, NULL);
3542 if (jo == NULL)
3543 goto failed;
3544
3545 if (!AssignProcessToJobObject(jo, child_process_handle))
3546 {
3547 /* Failed, switch the way to terminate process with TerminateProcess. */
3548 CloseHandle(jo);
3549 jo = NULL;
3550 }
3551
3552 winpty_spawn_config_free(spawn_config);
3553 vim_free(cmd_wchar);
3554 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003555 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003556
3557 create_vterm(term, term->tl_rows, term->tl_cols);
3558
3559 channel_set_job(channel, job, opt);
3560 job_set_options(job, opt);
3561
3562 job->jv_channel = channel;
3563 job->jv_proc_info.hProcess = child_process_handle;
3564 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3565 job->jv_job_object = jo;
3566 job->jv_status = JOB_STARTED;
3567 job->jv_tty_in = utf16_to_enc(
3568 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3569 job->jv_tty_out = utf16_to_enc(
3570 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3571 ++job->jv_refcount;
3572 term->tl_job = job;
3573
3574 return OK;
3575
3576failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003577 ga_clear(&ga_cmd);
3578 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003579 vim_free(cmd_wchar);
3580 vim_free(cwd_wchar);
3581 if (spawn_config != NULL)
3582 winpty_spawn_config_free(spawn_config);
3583 if (channel != NULL)
3584 channel_clear(channel);
3585 if (job != NULL)
3586 {
3587 job->jv_channel = NULL;
3588 job_cleanup(job);
3589 }
3590 term->tl_job = NULL;
3591 if (jo != NULL)
3592 CloseHandle(jo);
3593 if (term->tl_winpty != NULL)
3594 winpty_free(term->tl_winpty);
3595 term->tl_winpty = NULL;
3596 if (term->tl_winpty_config != NULL)
3597 winpty_config_free(term->tl_winpty_config);
3598 term->tl_winpty_config = NULL;
3599 if (winpty_err != NULL)
3600 {
3601 char_u *msg = utf16_to_enc(
3602 (short_u *)winpty_error_msg(winpty_err), NULL);
3603
3604 EMSG(msg);
3605 winpty_error_free(winpty_err);
3606 }
3607 return FAIL;
3608}
3609
3610 static int
3611create_pty_only(term_T *term, jobopt_T *options)
3612{
3613 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3614 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3615 char in_name[80], out_name[80];
3616 channel_T *channel = NULL;
3617
3618 create_vterm(term, term->tl_rows, term->tl_cols);
3619
3620 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3621 GetCurrentProcessId(),
3622 curbuf->b_fnum);
3623 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3624 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3625 PIPE_UNLIMITED_INSTANCES,
3626 0, 0, NMPWAIT_NOWAIT, NULL);
3627 if (hPipeIn == INVALID_HANDLE_VALUE)
3628 goto failed;
3629
3630 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3631 GetCurrentProcessId(),
3632 curbuf->b_fnum);
3633 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3634 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3635 PIPE_UNLIMITED_INSTANCES,
3636 0, 0, 0, NULL);
3637 if (hPipeOut == INVALID_HANDLE_VALUE)
3638 goto failed;
3639
3640 ConnectNamedPipe(hPipeIn, NULL);
3641 ConnectNamedPipe(hPipeOut, NULL);
3642
3643 term->tl_job = job_alloc();
3644 if (term->tl_job == NULL)
3645 goto failed;
3646 ++term->tl_job->jv_refcount;
3647
3648 /* behave like the job is already finished */
3649 term->tl_job->jv_status = JOB_FINISHED;
3650
3651 channel = add_channel();
3652 if (channel == NULL)
3653 goto failed;
3654 term->tl_job->jv_channel = channel;
3655 channel->ch_keep_open = TRUE;
3656 channel->ch_named_pipe = TRUE;
3657
3658 channel_set_pipes(channel,
3659 (sock_T)hPipeIn,
3660 (sock_T)hPipeOut,
3661 (sock_T)hPipeOut);
3662 channel_set_job(channel, term->tl_job, options);
3663 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3664 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3665
3666 return OK;
3667
3668failed:
3669 if (hPipeIn != NULL)
3670 CloseHandle(hPipeIn);
3671 if (hPipeOut != NULL)
3672 CloseHandle(hPipeOut);
3673 return FAIL;
3674}
3675
3676/*
3677 * Free the terminal emulator part of "term".
3678 */
3679 static void
3680term_free_vterm(term_T *term)
3681{
3682 if (term->tl_winpty != NULL)
3683 winpty_free(term->tl_winpty);
3684 term->tl_winpty = NULL;
3685 if (term->tl_winpty_config != NULL)
3686 winpty_config_free(term->tl_winpty_config);
3687 term->tl_winpty_config = NULL;
3688 if (term->tl_vterm != NULL)
3689 vterm_free(term->tl_vterm);
3690 term->tl_vterm = NULL;
3691}
3692
3693/*
3694 * Request size to terminal.
3695 */
3696 static void
3697term_report_winsize(term_T *term, int rows, int cols)
3698{
3699 if (term->tl_winpty)
3700 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3701}
3702
3703 int
3704terminal_enabled(void)
3705{
3706 return dyn_winpty_init(FALSE) == OK;
3707}
3708
3709# else
3710
3711/**************************************
3712 * 3. Unix-like implementation.
3713 */
3714
3715/*
3716 * Create a new terminal of "rows" by "cols" cells.
3717 * Start job for "cmd".
3718 * Store the pointers in "term".
3719 * Return OK or FAIL.
3720 */
3721 static int
3722term_and_job_init(
3723 term_T *term,
3724 typval_T *argvar,
3725 jobopt_T *opt)
3726{
3727 create_vterm(term, term->tl_rows, term->tl_cols);
3728
3729 term->tl_job = job_start(argvar, opt);
3730 if (term->tl_job != NULL)
3731 ++term->tl_job->jv_refcount;
3732
3733 return term->tl_job != NULL
3734 && term->tl_job->jv_channel != NULL
3735 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3736}
3737
3738 static int
3739create_pty_only(term_T *term, jobopt_T *opt)
3740{
3741 create_vterm(term, term->tl_rows, term->tl_cols);
3742
3743 term->tl_job = job_alloc();
3744 if (term->tl_job == NULL)
3745 return FAIL;
3746 ++term->tl_job->jv_refcount;
3747
3748 /* behave like the job is already finished */
3749 term->tl_job->jv_status = JOB_FINISHED;
3750
3751 return mch_create_pty_channel(term->tl_job, opt);
3752}
3753
3754/*
3755 * Free the terminal emulator part of "term".
3756 */
3757 static void
3758term_free_vterm(term_T *term)
3759{
3760 if (term->tl_vterm != NULL)
3761 vterm_free(term->tl_vterm);
3762 term->tl_vterm = NULL;
3763}
3764
3765/*
3766 * Request size to terminal.
3767 */
3768 static void
3769term_report_winsize(term_T *term, int rows, int cols)
3770{
3771 /* Use an ioctl() to report the new window size to the job. */
3772 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3773 {
3774 int fd = -1;
3775 int part;
3776
3777 for (part = PART_OUT; part < PART_COUNT; ++part)
3778 {
3779 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3780 if (isatty(fd))
3781 break;
3782 }
3783 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3784 mch_signal_job(term->tl_job, (char_u *)"winch");
3785 }
3786}
3787
3788# endif
3789
3790#endif /* FEAT_TERMINAL */