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