blob: f980a099293c06ade3e3629ca8438c21d0c141f4 [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 Moolenaar8fbaeb12018-03-25 18:20:17 +020041 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
Bram Moolenaar4a696342018-04-05 18:45:26 +020042 * redirection. Probably in call to channel_set_pipes().
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010043 * - implement term_setsize()
Bram Moolenaarf59c6e82018-04-10 15:59:11 +020044 * - add an optional limit for the scrollback size. When reaching it remove
45 * 10% at the start.
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010046 * - Copy text in the vterm to the Vim buffer once in a while, so that
47 * completion works.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020048 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
49 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020050 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020051 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
52 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020053 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010054 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020055 * - MS-Windows GUI: WinBar has tearoff item
Bram 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 Moolenaar2e6ab182017-09-20 10:03:07 +020058 * - add test for giving error for invalid 'termsize' value.
59 * - support minimal size when 'termsize' is "rows*cols".
60 * - support minimal size when 'termsize' is empty?
61 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020062 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020063 * - For the GUI fill termios with default values, perhaps like pangoterm:
64 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020065 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
66 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067 */
68
69#include "vim.h"
70
71#if defined(FEAT_TERMINAL) || defined(PROTO)
72
73#ifndef MIN
74# define MIN(x,y) ((x) < (y) ? (x) : (y))
75#endif
76#ifndef MAX
77# define MAX(x,y) ((x) > (y) ? (x) : (y))
78#endif
79
80#include "libvterm/include/vterm.h"
81
82/* This is VTermScreenCell without the characters, thus much smaller. */
83typedef struct {
84 VTermScreenCellAttrs attrs;
85 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010086 VTermColor fg;
87 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020088} cellattr_T;
89
90typedef struct sb_line_S {
91 int sb_cols; /* can differ per line */
92 cellattr_T *sb_cells; /* allocated */
93 cellattr_T sb_fill_attr; /* for short line */
94} sb_line_T;
95
96/* typedef term_T in structs.h */
97struct terminal_S {
98 term_T *tl_next;
99
100 VTerm *tl_vterm;
101 job_T *tl_job;
102 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100103#if defined(FEAT_GUI)
104 int tl_system; /* when non-zero used for :!cmd output */
105 int tl_toprow; /* row with first line of system terminal */
106#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200107
108 /* Set when setting the size of a vterm, reset after redrawing. */
109 int tl_vterm_size_changed;
110
111 /* used when tl_job is NULL and only a pty was created */
112 int tl_tty_fd;
113 char_u *tl_tty_in;
114 char_u *tl_tty_out;
115
116 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
117 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100118 int tl_finish;
119#define TL_FINISH_UNSET NUL
120#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
121#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
122#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123 char_u *tl_opencmd;
124 char_u *tl_eof_chars;
125
126#ifdef WIN3264
127 void *tl_winpty_config;
128 void *tl_winpty;
129#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100130#if defined(FEAT_SESSION)
131 char_u *tl_command;
132#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100133 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
135 /* last known vterm size */
136 int tl_rows;
137 int tl_cols;
138 /* vterm size does not follow window size */
139 int tl_rows_fixed;
140 int tl_cols_fixed;
141
142 char_u *tl_title; /* NULL or allocated */
143 char_u *tl_status_text; /* NULL or allocated */
144
145 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200146 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 int tl_dirty_row_end; /* row below last one to update */
148
149 garray_T tl_scrollback;
150 int tl_scrollback_scrolled;
151 cellattr_T tl_default_color;
152
Bram Moolenaard96ff162018-02-18 22:13:29 +0100153 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
154 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 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 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100182static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200183static 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);
Bram Moolenaar13568252018-03-16 20:46:58 +0100186#ifdef FEAT_GUI
187static void update_system_term(term_T *term);
188#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100190/* The character that we know (or assume) that the terminal expects for the
191 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200192static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100194/* "Terminal" highlight group colors. */
195static int term_default_cterm_fg = -1;
196static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197
Bram Moolenaard317b382018-02-08 22:33:31 +0100198/* Store the last set and the desired cursor properties, so that we only update
199 * them when needed. Doing it unnecessary may result in flicker. */
200static char_u *last_set_cursor_color = (char_u *)"";
201static char_u *desired_cursor_color = (char_u *)"";
202static int last_set_cursor_shape = -1;
203static int desired_cursor_shape = -1;
204static int last_set_cursor_blink = -1;
205static int desired_cursor_blink = -1;
206
207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208/**************************************
209 * 1. Generic code for all systems.
210 */
211
212/*
213 * Determine the terminal size from 'termsize' and the current window.
214 * Assumes term->tl_rows and term->tl_cols are zero.
215 */
216 static void
217set_term_and_win_size(term_T *term)
218{
Bram Moolenaar13568252018-03-16 20:46:58 +0100219#ifdef FEAT_GUI
220 if (term->tl_system)
221 {
222 /* Use the whole screen for the system command. However, it will start
223 * at the command line and scroll up as needed, using tl_toprow. */
224 term->tl_rows = Rows;
225 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200226 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100227 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100228#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200229 if (*curwin->w_p_tms != NUL)
230 {
231 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
232
233 term->tl_rows = atoi((char *)curwin->w_p_tms);
234 term->tl_cols = atoi((char *)p);
235 }
236 if (term->tl_rows == 0)
237 term->tl_rows = curwin->w_height;
238 else
239 {
240 win_setheight_win(term->tl_rows, curwin);
241 term->tl_rows_fixed = TRUE;
242 }
243 if (term->tl_cols == 0)
244 term->tl_cols = curwin->w_width;
245 else
246 {
247 win_setwidth_win(term->tl_cols, curwin);
248 term->tl_cols_fixed = TRUE;
249 }
250}
251
252/*
253 * Initialize job options for a terminal job.
254 * Caller may overrule some of them.
255 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100256 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200257init_job_options(jobopt_T *opt)
258{
259 clear_job_options(opt);
260
261 opt->jo_mode = MODE_RAW;
262 opt->jo_out_mode = MODE_RAW;
263 opt->jo_err_mode = MODE_RAW;
264 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
265}
266
267/*
268 * Set job options mandatory for a terminal job.
269 */
270 static void
271setup_job_options(jobopt_T *opt, int rows, int cols)
272{
273 if (!(opt->jo_set & JO_OUT_IO))
274 {
275 /* Connect stdout to the terminal. */
276 opt->jo_io[PART_OUT] = JIO_BUFFER;
277 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
278 opt->jo_modifiable[PART_OUT] = 0;
279 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
280 }
281
282 if (!(opt->jo_set & JO_ERR_IO))
283 {
284 /* Connect stderr to the terminal. */
285 opt->jo_io[PART_ERR] = JIO_BUFFER;
286 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
287 opt->jo_modifiable[PART_ERR] = 0;
288 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
289 }
290
291 opt->jo_pty = TRUE;
292 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
293 opt->jo_term_rows = rows;
294 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
295 opt->jo_term_cols = cols;
296}
297
298/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100299 * Close a terminal buffer (and its window). Used when creating the terminal
300 * fails.
301 */
302 static void
303term_close_buffer(buf_T *buf, buf_T *old_curbuf)
304{
305 free_terminal(buf);
306 if (old_curbuf != NULL)
307 {
308 --curbuf->b_nwindows;
309 curbuf = old_curbuf;
310 curwin->w_buffer = curbuf;
311 ++curbuf->b_nwindows;
312 }
313
314 /* Wiping out the buffer will also close the window and call
315 * free_terminal(). */
316 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
317}
318
319/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200320 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100321 * Use either "argvar" or "argv", the other must be NULL.
322 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
323 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200324 * Returns NULL when failed.
325 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100326 buf_T *
327term_start(
328 typval_T *argvar,
329 char **argv,
330 jobopt_T *opt,
331 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332{
333 exarg_T split_ea;
334 win_T *old_curwin = curwin;
335 term_T *term;
336 buf_T *old_curbuf = NULL;
337 int res;
338 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100339 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200340
341 if (check_restricted() || check_secure())
342 return NULL;
343
344 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
345 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
346 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
347 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
348 {
349 EMSG(_(e_invarg));
350 return NULL;
351 }
352
353 term = (term_T *)alloc_clear(sizeof(term_T));
354 if (term == NULL)
355 return NULL;
356 term->tl_dirty_row_end = MAX_ROW;
357 term->tl_cursor_visible = TRUE;
358 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
359 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100360#ifdef FEAT_GUI
361 term->tl_system = (flags & TERM_START_SYSTEM);
362#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200363 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
364
365 vim_memset(&split_ea, 0, sizeof(split_ea));
366 if (opt->jo_curwin)
367 {
368 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100369 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200370 {
371 no_write_message();
372 vim_free(term);
373 return NULL;
374 }
375 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100376 ECMD_HIDE
377 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
378 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200379 {
380 vim_free(term);
381 return NULL;
382 }
383 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100384 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200385 {
386 buf_T *buf;
387
388 /* Create a new buffer without a window. Make it the current buffer for
389 * a moment to be able to do the initialisations. */
390 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
391 BLN_NEW | BLN_LISTED);
392 if (buf == NULL || ml_open(buf) == FAIL)
393 {
394 vim_free(term);
395 return NULL;
396 }
397 old_curbuf = curbuf;
398 --curbuf->b_nwindows;
399 curbuf = buf;
400 curwin->w_buffer = buf;
401 ++curbuf->b_nwindows;
402 }
403 else
404 {
405 /* Open a new window or tab. */
406 split_ea.cmdidx = CMD_new;
407 split_ea.cmd = (char_u *)"new";
408 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100409 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410 {
411 split_ea.line2 = opt->jo_term_rows;
412 split_ea.addr_count = 1;
413 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100414 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200415 {
416 split_ea.line2 = opt->jo_term_cols;
417 split_ea.addr_count = 1;
418 }
419
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100420 if (vertical)
421 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200422 ex_splitview(&split_ea);
423 if (curwin == old_curwin)
424 {
425 /* split failed */
426 vim_free(term);
427 return NULL;
428 }
429 }
430 term->tl_buffer = curbuf;
431 curbuf->b_term = term;
432
433 if (!opt->jo_hidden)
434 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100435 /* Only one size was taken care of with :new, do the other one. With
436 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100439 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440 win_setwidth(opt->jo_term_cols);
441 }
442
443 /* Link the new terminal in the list of active terminals. */
444 term->tl_next = first_term;
445 first_term = term;
446
447 if (opt->jo_term_name != NULL)
448 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100449 else if (argv != NULL)
450 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200451 else
452 {
453 int i;
454 size_t len;
455 char_u *cmd, *p;
456
457 if (argvar->v_type == VAR_STRING)
458 {
459 cmd = argvar->vval.v_string;
460 if (cmd == NULL)
461 cmd = (char_u *)"";
462 else if (STRCMP(cmd, "NONE") == 0)
463 cmd = (char_u *)"pty";
464 }
465 else if (argvar->v_type != VAR_LIST
466 || argvar->vval.v_list == NULL
467 || argvar->vval.v_list->lv_len < 1
468 || (cmd = get_tv_string_chk(
469 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
470 cmd = (char_u*)"";
471
472 len = STRLEN(cmd) + 10;
473 p = alloc((int)len);
474
475 for (i = 0; p != NULL; ++i)
476 {
477 /* Prepend a ! to the command name to avoid the buffer name equals
478 * the executable, otherwise ":w!" would overwrite it. */
479 if (i == 0)
480 vim_snprintf((char *)p, len, "!%s", cmd);
481 else
482 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
483 if (buflist_findname(p) == NULL)
484 {
485 vim_free(curbuf->b_ffname);
486 curbuf->b_ffname = p;
487 break;
488 }
489 }
490 }
491 curbuf->b_fname = curbuf->b_ffname;
492
493 if (opt->jo_term_opencmd != NULL)
494 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
495
496 if (opt->jo_eof_chars != NULL)
497 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
498
499 set_string_option_direct((char_u *)"buftype", -1,
500 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
501
502 /* Mark the buffer as not modifiable. It can only be made modifiable after
503 * the job finished. */
504 curbuf->b_p_ma = FALSE;
505
506 set_term_and_win_size(term);
507 setup_job_options(opt, term->tl_rows, term->tl_cols);
508
Bram Moolenaar13568252018-03-16 20:46:58 +0100509 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100510 return curbuf;
511
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100512#if defined(FEAT_SESSION)
513 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100514 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100515 {
516 term->tl_command = vim_strsave((char_u *)"NONE");
517 }
518 else if (argvar->v_type == VAR_STRING)
519 {
520 char_u *cmd = argvar->vval.v_string;
521
522 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
523 term->tl_command = vim_strsave(cmd);
524 }
525 else if (argvar->v_type == VAR_LIST
526 && argvar->vval.v_list != NULL
527 && argvar->vval.v_list->lv_len > 0)
528 {
529 garray_T ga;
530 listitem_T *item;
531
532 ga_init2(&ga, 1, 100);
533 for (item = argvar->vval.v_list->lv_first;
534 item != NULL; item = item->li_next)
535 {
536 char_u *s = get_tv_string_chk(&item->li_tv);
537 char_u *p;
538
539 if (s == NULL)
540 break;
541 p = vim_strsave_fnameescape(s, FALSE);
542 if (p == NULL)
543 break;
544 ga_concat(&ga, p);
545 vim_free(p);
546 ga_append(&ga, ' ');
547 }
548 if (item == NULL)
549 {
550 ga_append(&ga, NUL);
551 term->tl_command = ga.ga_data;
552 }
553 else
554 ga_clear(&ga);
555 }
556#endif
557
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100558 if (opt->jo_term_kill != NULL)
559 {
560 char_u *p = skiptowhite(opt->jo_term_kill);
561
562 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
563 }
564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100566 if (argv == NULL
567 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 && argvar->vval.v_string != NULL
569 && STRCMP(argvar->vval.v_string, "NONE") == 0)
570 res = create_pty_only(term, opt);
571 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100572 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200573
574 newbuf = curbuf;
575 if (res == OK)
576 {
577 /* Get and remember the size we ended up with. Update the pty. */
578 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
579 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100580#ifdef FEAT_GUI
581 if (term->tl_system)
582 {
583 /* display first line below typed command */
584 term->tl_toprow = msg_row + 1;
585 term->tl_dirty_row_end = 0;
586 }
587#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200588
589 /* Make sure we don't get stuck on sending keys to the job, it leads to
590 * a deadlock if the job is waiting for Vim to read. */
591 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
592
Bram Moolenaar13568252018-03-16 20:46:58 +0100593 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100594 {
595 ++curbuf->b_locked;
596 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
597 --curbuf->b_locked;
598 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100599 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200600 {
601 --curbuf->b_nwindows;
602 curbuf = old_curbuf;
603 curwin->w_buffer = curbuf;
604 ++curbuf->b_nwindows;
605 }
606 }
607 else
608 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100609 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200610 return NULL;
611 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100612
Bram Moolenaar13568252018-03-16 20:46:58 +0100613 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200614 return newbuf;
615}
616
617/*
618 * ":terminal": open a terminal window and execute a job in it.
619 */
620 void
621ex_terminal(exarg_T *eap)
622{
623 typval_T argvar[2];
624 jobopt_T opt;
625 char_u *cmd;
626 char_u *tofree = NULL;
627
628 init_job_options(&opt);
629
630 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100631 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200632 {
633 char_u *p, *ep;
634
635 cmd += 2;
636 p = skiptowhite(cmd);
637 ep = vim_strchr(cmd, '=');
638 if (ep != NULL && ep < p)
639 p = ep;
640
641 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
642 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100643 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
644 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
646 opt.jo_term_finish = 'o';
647 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
648 opt.jo_curwin = 1;
649 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
650 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100651 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
652 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100653 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
654 && ep != NULL)
655 {
656 opt.jo_set2 |= JO2_TERM_KILL;
657 opt.jo_term_kill = ep + 1;
658 p = skiptowhite(cmd);
659 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
661 && ep != NULL && isdigit(ep[1]))
662 {
663 opt.jo_set2 |= JO2_TERM_ROWS;
664 opt.jo_term_rows = atoi((char *)ep + 1);
665 p = skiptowhite(cmd);
666 }
667 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
668 && ep != NULL && isdigit(ep[1]))
669 {
670 opt.jo_set2 |= JO2_TERM_COLS;
671 opt.jo_term_cols = atoi((char *)ep + 1);
672 p = skiptowhite(cmd);
673 }
674 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
675 && ep != NULL)
676 {
677 char_u *buf = NULL;
678 char_u *keys;
679
680 p = skiptowhite(cmd);
681 *p = NUL;
682 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
683 opt.jo_set2 |= JO2_EOF_CHARS;
684 opt.jo_eof_chars = vim_strsave(keys);
685 vim_free(buf);
686 *p = ' ';
687 }
688 else
689 {
690 if (*p)
691 *p = NUL;
692 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100693 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200694 }
695 cmd = skipwhite(p);
696 }
697 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100698 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200699 /* Make a copy of 'shell', an autocommand may change the option. */
700 tofree = cmd = vim_strsave(p_sh);
701
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100702 /* default to close when the shell exits */
703 if (opt.jo_term_finish == NUL)
704 opt.jo_term_finish = 'c';
705 }
706
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 if (eap->addr_count > 0)
708 {
709 /* Write lines from current buffer to the job. */
710 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
711 opt.jo_io[PART_IN] = JIO_BUFFER;
712 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
713 opt.jo_in_top = eap->line1;
714 opt.jo_in_bot = eap->line2;
715 }
716
717 argvar[0].v_type = VAR_STRING;
718 argvar[0].vval.v_string = cmd;
719 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100720 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200721 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100722
723theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 vim_free(opt.jo_eof_chars);
725}
726
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100727#if defined(FEAT_SESSION) || defined(PROTO)
728/*
729 * Write a :terminal command to the session file to restore the terminal in
730 * window "wp".
731 * Return FAIL if writing fails.
732 */
733 int
734term_write_session(FILE *fd, win_T *wp)
735{
736 term_T *term = wp->w_buffer->b_term;
737
738 /* Create the terminal and run the command. This is not without
739 * risk, but let's assume the user only creates a session when this
740 * will be OK. */
741 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
742 term->tl_cols, term->tl_rows) < 0)
743 return FAIL;
744 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
745 return FAIL;
746
747 return put_eol(fd);
748}
749
750/*
751 * Return TRUE if "buf" has a terminal that should be restored.
752 */
753 int
754term_should_restore(buf_T *buf)
755{
756 term_T *term = buf->b_term;
757
758 return term != NULL && (term->tl_command == NULL
759 || STRCMP(term->tl_command, "NONE") != 0);
760}
761#endif
762
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200763/*
764 * Free the scrollback buffer for "term".
765 */
766 static void
767free_scrollback(term_T *term)
768{
769 int i;
770
771 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
772 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
773 ga_clear(&term->tl_scrollback);
774}
775
776/*
777 * Free a terminal and everything it refers to.
778 * Kills the job if there is one.
779 * Called when wiping out a buffer.
780 */
781 void
782free_terminal(buf_T *buf)
783{
784 term_T *term = buf->b_term;
785 term_T *tp;
786
787 if (term == NULL)
788 return;
789 if (first_term == term)
790 first_term = term->tl_next;
791 else
792 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
793 if (tp->tl_next == term)
794 {
795 tp->tl_next = term->tl_next;
796 break;
797 }
798
799 if (term->tl_job != NULL)
800 {
801 if (term->tl_job->jv_status != JOB_ENDED
802 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100803 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 job_stop(term->tl_job, NULL, "kill");
805 job_unref(term->tl_job);
806 }
807
808 free_scrollback(term);
809
810 term_free_vterm(term);
811 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100812#ifdef FEAT_SESSION
813 vim_free(term->tl_command);
814#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100815 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 vim_free(term->tl_status_text);
817 vim_free(term->tl_opencmd);
818 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100819 if (desired_cursor_color == term->tl_cursor_color)
820 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 vim_free(term->tl_cursor_color);
822 vim_free(term);
823 buf->b_term = NULL;
824 if (in_terminal_loop == term)
825 in_terminal_loop = NULL;
826}
827
828/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100829 * Get the part that is connected to the tty. Normally this is PART_IN, but
830 * when writing buffer lines to the job it can be another. This makes it
831 * possible to do "1,5term vim -".
832 */
833 static ch_part_T
834get_tty_part(term_T *term)
835{
836#ifdef UNIX
837 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
838 int i;
839
840 for (i = 0; i < 3; ++i)
841 {
842 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
843
844 if (isatty(fd))
845 return parts[i];
846 }
847#endif
848 return PART_IN;
849}
850
851/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200852 * Write job output "msg[len]" to the vterm.
853 */
854 static void
855term_write_job_output(term_T *term, char_u *msg, size_t len)
856{
857 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100858 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100860 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200861
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100862 /* flush vterm buffer when vterm responded to control sequence */
863 if (prevlen != vterm_output_get_buffer_current(vterm))
864 {
865 char buf[KEY_BUF_LEN];
866 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
867
868 if (curlen > 0)
869 channel_send(term->tl_job->jv_channel, get_tty_part(term),
870 (char_u *)buf, (int)curlen, NULL);
871 }
872
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 /* this invokes the damage callbacks */
874 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
875}
876
877 static void
878update_cursor(term_T *term, int redraw)
879{
880 if (term->tl_normal_mode)
881 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100882#ifdef FEAT_GUI
883 if (term->tl_system)
884 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
885 term->tl_cursor_pos.col);
886 else
887#endif
888 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889 if (redraw)
890 {
891 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
892 cursor_on();
893 out_flush();
894#ifdef FEAT_GUI
895 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100896 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200897 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100898 gui_mch_flush();
899 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200900#endif
901 }
902}
903
904/*
905 * Invoked when "msg" output from a job was received. Write it to the terminal
906 * of "buffer".
907 */
908 void
909write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
910{
911 size_t len = STRLEN(msg);
912 term_T *term = buffer->b_term;
913
914 if (term->tl_vterm == NULL)
915 {
916 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
917 return;
918 }
919 ch_log(channel, "writing %d bytes to terminal", (int)len);
920 term_write_job_output(term, msg, len);
921
Bram Moolenaar13568252018-03-16 20:46:58 +0100922#ifdef FEAT_GUI
923 if (term->tl_system)
924 {
925 /* show system output, scrolling up the screen as needed */
926 update_system_term(term);
927 update_cursor(term, TRUE);
928 }
929 else
930#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200931 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
932 * contents, thus no screen update is needed. */
933 if (!term->tl_normal_mode)
934 {
935 /* TODO: only update once in a while. */
936 ch_log(term->tl_job->jv_channel, "updating screen");
937 if (buffer == curbuf)
938 {
939 update_screen(0);
940 update_cursor(term, TRUE);
941 }
942 else
943 redraw_after_callback(TRUE);
944 }
945}
946
947/*
948 * Send a mouse position and click to the vterm
949 */
950 static int
951term_send_mouse(VTerm *vterm, int button, int pressed)
952{
953 VTermModifier mod = VTERM_MOD_NONE;
954
955 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200956 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100957 if (button != 0)
958 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200959 return TRUE;
960}
961
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100962static int enter_mouse_col = -1;
963static int enter_mouse_row = -1;
964
965/*
966 * Handle a mouse click, drag or release.
967 * Return TRUE when a mouse event is sent to the terminal.
968 */
969 static int
970term_mouse_click(VTerm *vterm, int key)
971{
972#if defined(FEAT_CLIPBOARD)
973 /* For modeless selection mouse drag and release events are ignored, unless
974 * they are preceded with a mouse down event */
975 static int ignore_drag_release = TRUE;
976 VTermMouseState mouse_state;
977
978 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
979 if (mouse_state.flags == 0)
980 {
981 /* Terminal is not using the mouse, use modeless selection. */
982 switch (key)
983 {
984 case K_LEFTDRAG:
985 case K_LEFTRELEASE:
986 case K_RIGHTDRAG:
987 case K_RIGHTRELEASE:
988 /* Ignore drag and release events when the button-down wasn't
989 * seen before. */
990 if (ignore_drag_release)
991 {
992 int save_mouse_col, save_mouse_row;
993
994 if (enter_mouse_col < 0)
995 break;
996
997 /* mouse click in the window gave us focus, handle that
998 * click now */
999 save_mouse_col = mouse_col;
1000 save_mouse_row = mouse_row;
1001 mouse_col = enter_mouse_col;
1002 mouse_row = enter_mouse_row;
1003 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1004 mouse_col = save_mouse_col;
1005 mouse_row = save_mouse_row;
1006 }
1007 /* FALLTHROUGH */
1008 case K_LEFTMOUSE:
1009 case K_RIGHTMOUSE:
1010 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1011 ignore_drag_release = TRUE;
1012 else
1013 ignore_drag_release = FALSE;
1014 /* Should we call mouse_has() here? */
1015 if (clip_star.available)
1016 {
1017 int button, is_click, is_drag;
1018
1019 button = get_mouse_button(KEY2TERMCAP1(key),
1020 &is_click, &is_drag);
1021 if (mouse_model_popup() && button == MOUSE_LEFT
1022 && (mod_mask & MOD_MASK_SHIFT))
1023 {
1024 /* Translate shift-left to right button. */
1025 button = MOUSE_RIGHT;
1026 mod_mask &= ~MOD_MASK_SHIFT;
1027 }
1028 clip_modeless(button, is_click, is_drag);
1029 }
1030 break;
1031
1032 case K_MIDDLEMOUSE:
1033 if (clip_star.available)
1034 insert_reg('*', TRUE);
1035 break;
1036 }
1037 enter_mouse_col = -1;
1038 return FALSE;
1039 }
1040#endif
1041 enter_mouse_col = -1;
1042
1043 switch (key)
1044 {
1045 case K_LEFTMOUSE:
1046 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1047 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1048 case K_LEFTRELEASE:
1049 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1050 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1051 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1052 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1053 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1054 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1055 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1056 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1057 }
1058 return TRUE;
1059}
1060
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001061/*
1062 * Convert typed key "c" into bytes to send to the job.
1063 * Return the number of bytes in "buf".
1064 */
1065 static int
1066term_convert_key(term_T *term, int c, char *buf)
1067{
1068 VTerm *vterm = term->tl_vterm;
1069 VTermKey key = VTERM_KEY_NONE;
1070 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001071 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001072
1073 switch (c)
1074 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001075 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1076
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001077 /* don't use VTERM_KEY_BACKSPACE, it always
1078 * becomes 0x7f DEL */
1079 case K_BS: c = term_backspace_char; break;
1080
1081 case ESC: key = VTERM_KEY_ESCAPE; break;
1082 case K_DEL: key = VTERM_KEY_DEL; break;
1083 case K_DOWN: key = VTERM_KEY_DOWN; break;
1084 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1085 key = VTERM_KEY_DOWN; break;
1086 case K_END: key = VTERM_KEY_END; break;
1087 case K_S_END: mod = VTERM_MOD_SHIFT;
1088 key = VTERM_KEY_END; break;
1089 case K_C_END: mod = VTERM_MOD_CTRL;
1090 key = VTERM_KEY_END; break;
1091 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1092 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1093 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1094 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1095 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1096 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1097 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1098 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1099 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1100 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1101 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1102 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1103 case K_HOME: key = VTERM_KEY_HOME; break;
1104 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1105 key = VTERM_KEY_HOME; break;
1106 case K_C_HOME: mod = VTERM_MOD_CTRL;
1107 key = VTERM_KEY_HOME; break;
1108 case K_INS: key = VTERM_KEY_INS; break;
1109 case K_K0: key = VTERM_KEY_KP_0; break;
1110 case K_K1: key = VTERM_KEY_KP_1; break;
1111 case K_K2: key = VTERM_KEY_KP_2; break;
1112 case K_K3: key = VTERM_KEY_KP_3; break;
1113 case K_K4: key = VTERM_KEY_KP_4; break;
1114 case K_K5: key = VTERM_KEY_KP_5; break;
1115 case K_K6: key = VTERM_KEY_KP_6; break;
1116 case K_K7: key = VTERM_KEY_KP_7; break;
1117 case K_K8: key = VTERM_KEY_KP_8; break;
1118 case K_K9: key = VTERM_KEY_KP_9; break;
1119 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1120 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1121 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1122 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1123 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1124 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1125 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1126 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1127 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1128 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1129 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1130 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1131 case K_LEFT: key = VTERM_KEY_LEFT; break;
1132 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1133 key = VTERM_KEY_LEFT; break;
1134 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1135 key = VTERM_KEY_LEFT; break;
1136 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1137 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1138 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1139 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1140 key = VTERM_KEY_RIGHT; break;
1141 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1142 key = VTERM_KEY_RIGHT; break;
1143 case K_UP: key = VTERM_KEY_UP; break;
1144 case K_S_UP: mod = VTERM_MOD_SHIFT;
1145 key = VTERM_KEY_UP; break;
1146 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001147 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1148 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001149
Bram Moolenaara42ad572017-11-16 13:08:04 +01001150 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1151 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001152 case K_MOUSELEFT: /* TODO */ return 0;
1153 case K_MOUSERIGHT: /* TODO */ return 0;
1154
1155 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001156 case K_LEFTMOUSE_NM:
1157 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001158 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001159 case K_LEFTRELEASE_NM:
1160 case K_MOUSEMOVE:
1161 case K_MIDDLEMOUSE:
1162 case K_MIDDLEDRAG:
1163 case K_MIDDLERELEASE:
1164 case K_RIGHTMOUSE:
1165 case K_RIGHTDRAG:
1166 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1167 return 0;
1168 other = TRUE;
1169 break;
1170
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001171 case K_X1MOUSE: /* TODO */ return 0;
1172 case K_X1DRAG: /* TODO */ return 0;
1173 case K_X1RELEASE: /* TODO */ return 0;
1174 case K_X2MOUSE: /* TODO */ return 0;
1175 case K_X2DRAG: /* TODO */ return 0;
1176 case K_X2RELEASE: /* TODO */ return 0;
1177
1178 case K_IGNORE: return 0;
1179 case K_NOP: return 0;
1180 case K_UNDO: return 0;
1181 case K_HELP: return 0;
1182 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1183 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1184 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1185 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1186 case K_SELECT: return 0;
1187#ifdef FEAT_GUI
1188 case K_VER_SCROLLBAR: return 0;
1189 case K_HOR_SCROLLBAR: return 0;
1190#endif
1191#ifdef FEAT_GUI_TABLINE
1192 case K_TABLINE: return 0;
1193 case K_TABMENU: return 0;
1194#endif
1195#ifdef FEAT_NETBEANS_INTG
1196 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1197#endif
1198#ifdef FEAT_DND
1199 case K_DROP: return 0;
1200#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001202 case K_PS: vterm_keyboard_start_paste(vterm);
1203 other = TRUE;
1204 break;
1205 case K_PE: vterm_keyboard_end_paste(vterm);
1206 other = TRUE;
1207 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001208 }
1209
1210 /*
1211 * Convert special keys to vterm keys:
1212 * - Write keys to vterm: vterm_keyboard_key()
1213 * - Write output to channel.
1214 * TODO: use mod_mask
1215 */
1216 if (key != VTERM_KEY_NONE)
1217 /* Special key, let vterm convert it. */
1218 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001219 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001220 /* Normal character, let vterm convert it. */
1221 vterm_keyboard_unichar(vterm, c, mod);
1222
1223 /* Read back the converted escape sequence. */
1224 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1225}
1226
1227/*
1228 * Return TRUE if the job for "term" is still running.
1229 */
1230 int
1231term_job_running(term_T *term)
1232{
1233 /* Also consider the job finished when the channel is closed, to avoid a
1234 * race condition when updating the title. */
1235 return term != NULL
1236 && term->tl_job != NULL
1237 && channel_is_open(term->tl_job->jv_channel)
1238 && (term->tl_job->jv_status == JOB_STARTED
1239 || term->tl_job->jv_channel->ch_keep_open);
1240}
1241
1242/*
1243 * Return TRUE if "term" has an active channel and used ":term NONE".
1244 */
1245 int
1246term_none_open(term_T *term)
1247{
1248 /* Also consider the job finished when the channel is closed, to avoid a
1249 * race condition when updating the title. */
1250 return term != NULL
1251 && term->tl_job != NULL
1252 && channel_is_open(term->tl_job->jv_channel)
1253 && term->tl_job->jv_channel->ch_keep_open;
1254}
1255
1256/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001257 * Used when exiting: kill the job in "buf" if so desired.
1258 * Return OK when the job finished.
1259 * Return FAIL when the job is still running.
1260 */
1261 int
1262term_try_stop_job(buf_T *buf)
1263{
1264 int count;
1265 char *how = (char *)buf->b_term->tl_kill;
1266
1267#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1268 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1269 {
1270 char_u buff[DIALOG_MSG_SIZE];
1271 int ret;
1272
1273 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1274 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1275 if (ret == VIM_YES)
1276 how = "kill";
1277 else if (ret == VIM_CANCEL)
1278 return FAIL;
1279 }
1280#endif
1281 if (how == NULL || *how == NUL)
1282 return FAIL;
1283
1284 job_stop(buf->b_term->tl_job, NULL, how);
1285
1286 /* wait for up to a second for the job to die */
1287 for (count = 0; count < 100; ++count)
1288 {
1289 /* buffer, terminal and job may be cleaned up while waiting */
1290 if (!buf_valid(buf)
1291 || buf->b_term == NULL
1292 || buf->b_term->tl_job == NULL)
1293 return OK;
1294
1295 /* call job_status() to update jv_status */
1296 job_status(buf->b_term->tl_job);
1297 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1298 return OK;
1299 ui_delay(10L, FALSE);
1300 mch_check_messages();
1301 parse_queued_messages();
1302 }
1303 return FAIL;
1304}
1305
1306/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001307 * Add the last line of the scrollback buffer to the buffer in the window.
1308 */
1309 static void
1310add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1311{
1312 buf_T *buf = term->tl_buffer;
1313 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1314 linenr_T lnum = buf->b_ml.ml_line_count;
1315
1316#ifdef WIN3264
1317 if (!enc_utf8 && enc_codepage > 0)
1318 {
1319 WCHAR *ret = NULL;
1320 int length = 0;
1321
1322 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1323 &ret, &length);
1324 if (ret != NULL)
1325 {
1326 WideCharToMultiByte_alloc(enc_codepage, 0,
1327 ret, length, (char **)&text, &len, 0, 0);
1328 vim_free(ret);
1329 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1330 vim_free(text);
1331 }
1332 }
1333 else
1334#endif
1335 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1336 if (empty)
1337 {
1338 /* Delete the empty line that was in the empty buffer. */
1339 curbuf = buf;
1340 ml_delete(1, FALSE);
1341 curbuf = curwin->w_buffer;
1342 }
1343}
1344
1345 static void
1346cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1347{
1348 attr->width = cell->width;
1349 attr->attrs = cell->attrs;
1350 attr->fg = cell->fg;
1351 attr->bg = cell->bg;
1352}
1353
1354 static int
1355equal_celattr(cellattr_T *a, cellattr_T *b)
1356{
1357 /* Comparing the colors should be sufficient. */
1358 return a->fg.red == b->fg.red
1359 && a->fg.green == b->fg.green
1360 && a->fg.blue == b->fg.blue
1361 && a->bg.red == b->bg.red
1362 && a->bg.green == b->bg.green
1363 && a->bg.blue == b->bg.blue;
1364}
1365
Bram Moolenaard96ff162018-02-18 22:13:29 +01001366/*
1367 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1368 * line at this position. Otherwise at the end.
1369 */
1370 static int
1371add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1372{
1373 if (ga_grow(&term->tl_scrollback, 1) == OK)
1374 {
1375 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1376 + term->tl_scrollback.ga_len;
1377
1378 if (lnum > 0)
1379 {
1380 int i;
1381
1382 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1383 {
1384 *line = *(line - 1);
1385 --line;
1386 }
1387 }
1388 line->sb_cols = 0;
1389 line->sb_cells = NULL;
1390 line->sb_fill_attr = *fill_attr;
1391 ++term->tl_scrollback.ga_len;
1392 return OK;
1393 }
1394 return FALSE;
1395}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001396
1397/*
1398 * Add the current lines of the terminal to scrollback and to the buffer.
1399 * Called after the job has ended and when switching to Terminal-Normal mode.
1400 */
1401 static void
1402move_terminal_to_buffer(term_T *term)
1403{
1404 win_T *wp;
1405 int len;
1406 int lines_skipped = 0;
1407 VTermPos pos;
1408 VTermScreenCell cell;
1409 cellattr_T fill_attr, new_fill_attr;
1410 cellattr_T *p;
1411 VTermScreen *screen;
1412
1413 if (term->tl_vterm == NULL)
1414 return;
1415 screen = vterm_obtain_screen(term->tl_vterm);
1416 fill_attr = new_fill_attr = term->tl_default_color;
1417
1418 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1419 {
1420 len = 0;
1421 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1422 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1423 && cell.chars[0] != NUL)
1424 {
1425 len = pos.col + 1;
1426 new_fill_attr = term->tl_default_color;
1427 }
1428 else
1429 /* Assume the last attr is the filler attr. */
1430 cell2cellattr(&cell, &new_fill_attr);
1431
1432 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1433 ++lines_skipped;
1434 else
1435 {
1436 while (lines_skipped > 0)
1437 {
1438 /* Line was skipped, add an empty line. */
1439 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001440 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001442 }
1443
1444 if (len == 0)
1445 p = NULL;
1446 else
1447 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1448 if ((p != NULL || len == 0)
1449 && ga_grow(&term->tl_scrollback, 1) == OK)
1450 {
1451 garray_T ga;
1452 int width;
1453 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1454 + term->tl_scrollback.ga_len;
1455
1456 ga_init2(&ga, 1, 100);
1457 for (pos.col = 0; pos.col < len; pos.col += width)
1458 {
1459 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1460 {
1461 width = 1;
1462 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1463 if (ga_grow(&ga, 1) == OK)
1464 ga.ga_len += utf_char2bytes(' ',
1465 (char_u *)ga.ga_data + ga.ga_len);
1466 }
1467 else
1468 {
1469 width = cell.width;
1470
1471 cell2cellattr(&cell, &p[pos.col]);
1472
1473 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1474 {
1475 int i;
1476 int c;
1477
1478 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1479 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1480 (char_u *)ga.ga_data + ga.ga_len);
1481 }
1482 }
1483 }
1484 line->sb_cols = len;
1485 line->sb_cells = p;
1486 line->sb_fill_attr = new_fill_attr;
1487 fill_attr = new_fill_attr;
1488 ++term->tl_scrollback.ga_len;
1489
1490 if (ga_grow(&ga, 1) == FAIL)
1491 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1492 else
1493 {
1494 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1495 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1496 }
1497 ga_clear(&ga);
1498 }
1499 else
1500 vim_free(p);
1501 }
1502 }
1503
1504 /* Obtain the current background color. */
1505 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1506 &term->tl_default_color.fg, &term->tl_default_color.bg);
1507
1508 FOR_ALL_WINDOWS(wp)
1509 {
1510 if (wp->w_buffer == term->tl_buffer)
1511 {
1512 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1513 wp->w_cursor.col = 0;
1514 wp->w_valid = 0;
1515 if (wp->w_cursor.lnum >= wp->w_height)
1516 {
1517 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1518
1519 if (wp->w_topline < min_topline)
1520 wp->w_topline = min_topline;
1521 }
1522 redraw_win_later(wp, NOT_VALID);
1523 }
1524 }
1525}
1526
1527 static void
1528set_terminal_mode(term_T *term, int normal_mode)
1529{
1530 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001531 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001532 if (term->tl_buffer == curbuf)
1533 maketitle();
1534}
1535
1536/*
1537 * Called after the job if finished and Terminal mode is not active:
1538 * Move the vterm contents into the scrollback buffer and free the vterm.
1539 */
1540 static void
1541cleanup_vterm(term_T *term)
1542{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001543 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001544 move_terminal_to_buffer(term);
1545 term_free_vterm(term);
1546 set_terminal_mode(term, FALSE);
1547}
1548
1549/*
1550 * Switch from Terminal-Job mode to Terminal-Normal mode.
1551 * Suspends updating the terminal window.
1552 */
1553 static void
1554term_enter_normal_mode(void)
1555{
1556 term_T *term = curbuf->b_term;
1557
1558 /* Append the current terminal contents to the buffer. */
1559 move_terminal_to_buffer(term);
1560
1561 set_terminal_mode(term, TRUE);
1562
1563 /* Move the window cursor to the position of the cursor in the
1564 * terminal. */
1565 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1566 + term->tl_cursor_pos.row + 1;
1567 check_cursor();
1568 coladvance(term->tl_cursor_pos.col);
1569
1570 /* Display the same lines as in the terminal. */
1571 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1572}
1573
1574/*
1575 * Returns TRUE if the current window contains a terminal and we are in
1576 * Terminal-Normal mode.
1577 */
1578 int
1579term_in_normal_mode(void)
1580{
1581 term_T *term = curbuf->b_term;
1582
1583 return term != NULL && term->tl_normal_mode;
1584}
1585
1586/*
1587 * Switch from Terminal-Normal mode to Terminal-Job mode.
1588 * Restores updating the terminal window.
1589 */
1590 void
1591term_enter_job_mode()
1592{
1593 term_T *term = curbuf->b_term;
1594 sb_line_T *line;
1595 garray_T *gap;
1596
1597 /* Remove the terminal contents from the scrollback and the buffer. */
1598 gap = &term->tl_scrollback;
1599 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1600 && gap->ga_len > 0)
1601 {
1602 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1603 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1604 vim_free(line->sb_cells);
1605 --gap->ga_len;
1606 }
1607 check_cursor();
1608
1609 set_terminal_mode(term, FALSE);
1610
1611 if (term->tl_channel_closed)
1612 cleanup_vterm(term);
1613 redraw_buf_and_status_later(curbuf, NOT_VALID);
1614}
1615
1616/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001617 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001618 * Note: while waiting a terminal may be closed and freed if the channel is
1619 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001620 */
1621 static int
1622term_vgetc()
1623{
1624 int c;
1625 int save_State = State;
1626
1627 State = TERMINAL;
1628 got_int = FALSE;
1629#ifdef WIN3264
1630 ctrl_break_was_pressed = FALSE;
1631#endif
1632 c = vgetc();
1633 got_int = FALSE;
1634 State = save_State;
1635 return c;
1636}
1637
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001638static int mouse_was_outside = FALSE;
1639
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001641 * Send keys to terminal.
1642 * Return FAIL when the key needs to be handled in Normal mode.
1643 * Return OK when the key was dropped or sent to the terminal.
1644 */
1645 int
1646send_keys_to_term(term_T *term, int c, int typed)
1647{
1648 char msg[KEY_BUF_LEN];
1649 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 int dragging_outside = FALSE;
1651
1652 /* Catch keys that need to be handled as in Normal mode. */
1653 switch (c)
1654 {
1655 case NUL:
1656 case K_ZERO:
1657 if (typed)
1658 stuffcharReadbuff(c);
1659 return FAIL;
1660
1661 case K_IGNORE:
1662 return FAIL;
1663
1664 case K_LEFTDRAG:
1665 case K_MIDDLEDRAG:
1666 case K_RIGHTDRAG:
1667 case K_X1DRAG:
1668 case K_X2DRAG:
1669 dragging_outside = mouse_was_outside;
1670 /* FALLTHROUGH */
1671 case K_LEFTMOUSE:
1672 case K_LEFTMOUSE_NM:
1673 case K_LEFTRELEASE:
1674 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001675 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 case K_MIDDLEMOUSE:
1677 case K_MIDDLERELEASE:
1678 case K_RIGHTMOUSE:
1679 case K_RIGHTRELEASE:
1680 case K_X1MOUSE:
1681 case K_X1RELEASE:
1682 case K_X2MOUSE:
1683 case K_X2RELEASE:
1684
1685 case K_MOUSEUP:
1686 case K_MOUSEDOWN:
1687 case K_MOUSELEFT:
1688 case K_MOUSERIGHT:
1689 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001690 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001691 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001692 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693 || dragging_outside)
1694 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001695 /* click or scroll outside the current window or on status line
1696 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 if (typed)
1698 {
1699 stuffcharReadbuff(c);
1700 mouse_was_outside = TRUE;
1701 }
1702 return FAIL;
1703 }
1704 }
1705 if (typed)
1706 mouse_was_outside = FALSE;
1707
1708 /* Convert the typed key to a sequence of bytes for the job. */
1709 len = term_convert_key(term, c, msg);
1710 if (len > 0)
1711 /* TODO: if FAIL is returned, stop? */
1712 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1713 (char_u *)msg, (int)len, NULL);
1714
1715 return OK;
1716}
1717
1718 static void
1719position_cursor(win_T *wp, VTermPos *pos)
1720{
1721 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1722 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1723 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1724}
1725
1726/*
1727 * Handle CTRL-W "": send register contents to the job.
1728 */
1729 static void
1730term_paste_register(int prev_c UNUSED)
1731{
1732 int c;
1733 list_T *l;
1734 listitem_T *item;
1735 long reglen = 0;
1736 int type;
1737
1738#ifdef FEAT_CMDL_INFO
1739 if (add_to_showcmd(prev_c))
1740 if (add_to_showcmd('"'))
1741 out_flush();
1742#endif
1743 c = term_vgetc();
1744#ifdef FEAT_CMDL_INFO
1745 clear_showcmd();
1746#endif
1747 if (!term_use_loop())
1748 /* job finished while waiting for a character */
1749 return;
1750
1751 /* CTRL-W "= prompt for expression to evaluate. */
1752 if (c == '=' && get_expr_register() != '=')
1753 return;
1754 if (!term_use_loop())
1755 /* job finished while waiting for a character */
1756 return;
1757
1758 l = (list_T *)get_reg_contents(c, GREG_LIST);
1759 if (l != NULL)
1760 {
1761 type = get_reg_type(c, &reglen);
1762 for (item = l->lv_first; item != NULL; item = item->li_next)
1763 {
1764 char_u *s = get_tv_string(&item->li_tv);
1765#ifdef WIN3264
1766 char_u *tmp = s;
1767
1768 if (!enc_utf8 && enc_codepage > 0)
1769 {
1770 WCHAR *ret = NULL;
1771 int length = 0;
1772
1773 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1774 (int)STRLEN(s), &ret, &length);
1775 if (ret != NULL)
1776 {
1777 WideCharToMultiByte_alloc(CP_UTF8, 0,
1778 ret, length, (char **)&s, &length, 0, 0);
1779 vim_free(ret);
1780 }
1781 }
1782#endif
1783 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1784 s, (int)STRLEN(s), NULL);
1785#ifdef WIN3264
1786 if (tmp != s)
1787 vim_free(s);
1788#endif
1789
1790 if (item->li_next != NULL || type == MLINE)
1791 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1792 (char_u *)"\r", 1, NULL);
1793 }
1794 list_free(l);
1795 }
1796}
1797
1798#if defined(FEAT_GUI) || defined(PROTO)
1799/*
1800 * Return TRUE when the cursor of the terminal should be displayed.
1801 */
1802 int
1803terminal_is_active()
1804{
1805 return in_terminal_loop != NULL;
1806}
1807
1808 cursorentry_T *
1809term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1810{
1811 term_T *term = in_terminal_loop;
1812 static cursorentry_T entry;
1813
1814 vim_memset(&entry, 0, sizeof(entry));
1815 entry.shape = entry.mshape =
1816 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1817 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1818 SHAPE_BLOCK;
1819 entry.percentage = 20;
1820 if (term->tl_cursor_blink)
1821 {
1822 entry.blinkwait = 700;
1823 entry.blinkon = 400;
1824 entry.blinkoff = 250;
1825 }
1826 *fg = gui.back_pixel;
1827 if (term->tl_cursor_color == NULL)
1828 *bg = gui.norm_pixel;
1829 else
1830 *bg = color_name2handle(term->tl_cursor_color);
1831 entry.name = "n";
1832 entry.used_for = SHAPE_CURSOR;
1833
1834 return &entry;
1835}
1836#endif
1837
Bram Moolenaard317b382018-02-08 22:33:31 +01001838 static void
1839may_output_cursor_props(void)
1840{
1841 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1842 || last_set_cursor_shape != desired_cursor_shape
1843 || last_set_cursor_blink != desired_cursor_blink)
1844 {
1845 last_set_cursor_color = desired_cursor_color;
1846 last_set_cursor_shape = desired_cursor_shape;
1847 last_set_cursor_blink = desired_cursor_blink;
1848 term_cursor_color(desired_cursor_color);
1849 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1850 /* this will restore the initial cursor style, if possible */
1851 ui_cursor_shape_forced(TRUE);
1852 else
1853 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1854 }
1855}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001856
Bram Moolenaard317b382018-02-08 22:33:31 +01001857/*
1858 * Set the cursor color and shape, if not last set to these.
1859 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 static void
1861may_set_cursor_props(term_T *term)
1862{
1863#ifdef FEAT_GUI
1864 /* For the GUI the cursor properties are obtained with
1865 * term_get_cursor_shape(). */
1866 if (gui.in_use)
1867 return;
1868#endif
1869 if (in_terminal_loop == term)
1870 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001871 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001872 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001874 desired_cursor_color = (char_u *)"";
1875 desired_cursor_shape = term->tl_cursor_shape;
1876 desired_cursor_blink = term->tl_cursor_blink;
1877 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 }
1879}
1880
Bram Moolenaard317b382018-02-08 22:33:31 +01001881/*
1882 * Reset the desired cursor properties and restore them when needed.
1883 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001885prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886{
1887#ifdef FEAT_GUI
1888 if (gui.in_use)
1889 return;
1890#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001891 desired_cursor_color = (char_u *)"";
1892 desired_cursor_shape = -1;
1893 desired_cursor_blink = -1;
1894 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001895}
1896
1897/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001898 * Called when entering a window with the mouse. If this is a terminal window
1899 * we may want to change state.
1900 */
1901 void
1902term_win_entered()
1903{
1904 term_T *term = curbuf->b_term;
1905
1906 if (term != NULL)
1907 {
1908 if (term_use_loop())
1909 {
1910 reset_VIsual_and_resel();
1911 if (State & INSERT)
1912 stop_insert_mode = TRUE;
1913 }
1914 mouse_was_outside = FALSE;
1915 enter_mouse_col = mouse_col;
1916 enter_mouse_row = mouse_row;
1917 }
1918}
1919
1920/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921 * Returns TRUE if the current window contains a terminal and we are sending
1922 * keys to the job.
1923 */
1924 int
1925term_use_loop(void)
1926{
1927 term_T *term = curbuf->b_term;
1928
1929 return term != NULL
1930 && !term->tl_normal_mode
1931 && term->tl_vterm != NULL
1932 && term_job_running(term);
1933}
1934
1935/*
1936 * Wait for input and send it to the job.
1937 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1938 * when there is no more typahead.
1939 * Return when the start of a CTRL-W command is typed or anything else that
1940 * should be handled as a Normal mode command.
1941 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1942 * the terminal was closed.
1943 */
1944 int
1945terminal_loop(int blocking)
1946{
1947 int c;
1948 int termkey = 0;
1949 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001950#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001951 int tty_fd = curbuf->b_term->tl_job->jv_channel
1952 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001953#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001954 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001955
1956 /* Remember the terminal we are sending keys to. However, the terminal
1957 * might be closed while waiting for a character, e.g. typing "exit" in a
1958 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1959 * stored reference. */
1960 in_terminal_loop = curbuf->b_term;
1961
1962 if (*curwin->w_p_tk != NUL)
1963 termkey = string_to_key(curwin->w_p_tk, TRUE);
1964 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1965 may_set_cursor_props(curbuf->b_term);
1966
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001967 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001968 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001969#ifdef FEAT_GUI
1970 if (!curbuf->b_term->tl_system)
1971#endif
1972 /* TODO: skip screen update when handling a sequence of keys. */
1973 /* Repeat redrawing in case a message is received while redrawing.
1974 */
1975 while (must_redraw != 0)
1976 if (update_screen(0) == FAIL)
1977 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001978 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001979 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001980
1981 c = term_vgetc();
1982 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001983 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001984 /* Job finished while waiting for a character. Push back the
1985 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001986 if (c != K_IGNORE)
1987 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001989 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 if (c == K_IGNORE)
1991 continue;
1992
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001993#ifdef UNIX
1994 /*
1995 * The shell or another program may change the tty settings. Getting
1996 * them for every typed character is a bit of overhead, but it's needed
1997 * for the first character typed, e.g. when Vim starts in a shell.
1998 */
1999 if (isatty(tty_fd))
2000 {
2001 ttyinfo_T info;
2002
2003 /* Get the current backspace character of the pty. */
2004 if (get_tty_info(tty_fd, &info) == OK)
2005 term_backspace_char = info.backspace;
2006 }
2007#endif
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009#ifdef WIN3264
2010 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2011 * Use CTRL-BREAK to kill the job. */
2012 if (ctrl_break_was_pressed)
2013 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2014#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002015 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2016 * Not in a system terminal. */
2017 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2018#ifdef FEAT_GUI
2019 && !curbuf->b_term->tl_system
2020#endif
2021 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 {
2023 int prev_c = c;
2024
2025#ifdef FEAT_CMDL_INFO
2026 if (add_to_showcmd(c))
2027 out_flush();
2028#endif
2029 c = term_vgetc();
2030#ifdef FEAT_CMDL_INFO
2031 clear_showcmd();
2032#endif
2033 if (!term_use_loop())
2034 /* job finished while waiting for a character */
2035 break;
2036
2037 if (prev_c == Ctrl_BSL)
2038 {
2039 if (c == Ctrl_N)
2040 {
2041 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2042 term_enter_normal_mode();
2043 ret = FAIL;
2044 goto theend;
2045 }
2046 /* Send both keys to the terminal. */
2047 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2048 }
2049 else if (c == Ctrl_C)
2050 {
2051 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2052 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2053 }
2054 else if (termkey == 0 && c == '.')
2055 {
2056 /* "CTRL-W .": send CTRL-W to the job */
2057 c = Ctrl_W;
2058 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002059 else if (termkey == 0 && c == Ctrl_BSL)
2060 {
2061 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2062 c = Ctrl_BSL;
2063 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002064 else if (c == 'N')
2065 {
2066 /* CTRL-W N : go to Terminal-Normal mode. */
2067 term_enter_normal_mode();
2068 ret = FAIL;
2069 goto theend;
2070 }
2071 else if (c == '"')
2072 {
2073 term_paste_register(prev_c);
2074 continue;
2075 }
2076 else if (termkey == 0 || c != termkey)
2077 {
2078 stuffcharReadbuff(Ctrl_W);
2079 stuffcharReadbuff(c);
2080 ret = OK;
2081 goto theend;
2082 }
2083 }
2084# ifdef WIN3264
2085 if (!enc_utf8 && has_mbyte && c >= 0x80)
2086 {
2087 WCHAR wc;
2088 char_u mb[3];
2089
2090 mb[0] = (unsigned)c >> 8;
2091 mb[1] = c;
2092 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2093 c = wc;
2094 }
2095# endif
2096 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2097 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002098 if (c == K_MOUSEMOVE)
2099 /* We are sure to come back here, don't reset the cursor color
2100 * and shape to avoid flickering. */
2101 restore_cursor = FALSE;
2102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002103 ret = OK;
2104 goto theend;
2105 }
2106 }
2107 ret = FAIL;
2108
2109theend:
2110 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002111 if (restore_cursor)
2112 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002113 return ret;
2114}
2115
2116/*
2117 * Called when a job has finished.
2118 * This updates the title and status, but does not close the vterm, because
2119 * there might still be pending output in the channel.
2120 */
2121 void
2122term_job_ended(job_T *job)
2123{
2124 term_T *term;
2125 int did_one = FALSE;
2126
2127 for (term = first_term; term != NULL; term = term->tl_next)
2128 if (term->tl_job == job)
2129 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002130 VIM_CLEAR(term->tl_title);
2131 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002132 redraw_buf_and_status_later(term->tl_buffer, VALID);
2133 did_one = TRUE;
2134 }
2135 if (did_one)
2136 redraw_statuslines();
2137 if (curbuf->b_term != NULL)
2138 {
2139 if (curbuf->b_term->tl_job == job)
2140 maketitle();
2141 update_cursor(curbuf->b_term, TRUE);
2142 }
2143}
2144
2145 static void
2146may_toggle_cursor(term_T *term)
2147{
2148 if (in_terminal_loop == term)
2149 {
2150 if (term->tl_cursor_visible)
2151 cursor_on();
2152 else
2153 cursor_off();
2154 }
2155}
2156
2157/*
2158 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002159 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 */
2161 static int
2162color2index(VTermColor *color, int fg, int *boldp)
2163{
2164 int red = color->red;
2165 int blue = color->blue;
2166 int green = color->green;
2167
Bram Moolenaar46359e12017-11-29 22:33:38 +01002168 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002170 /* First 16 colors and default: use the ANSI index, because these
2171 * colors can be redefined. */
2172 if (t_colors >= 16)
2173 return color->ansi_index;
2174 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002176 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002177 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002178 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2179 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2180 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002181 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002182 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2183 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2184 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2185 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2186 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2187 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2188 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2189 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2190 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2191 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2192 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193 }
2194 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002195
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002196 if (t_colors >= 256)
2197 {
2198 if (red == blue && red == green)
2199 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002200 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002202 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2203 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2204 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002205 int i;
2206
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002207 if (red < 5)
2208 return 17; /* 00/00/00 */
2209 if (red > 245) /* ff/ff/ff */
2210 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002211 for (i = 0; i < 23; ++i)
2212 if (red < cutoff[i])
2213 return i + 233;
2214 return 256;
2215 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002216 {
2217 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2218 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002220 /* 216-color cube */
2221 for (ri = 0; ri < 5; ++ri)
2222 if (red < cutoff[ri])
2223 break;
2224 for (gi = 0; gi < 5; ++gi)
2225 if (green < cutoff[gi])
2226 break;
2227 for (bi = 0; bi < 5; ++bi)
2228 if (blue < cutoff[bi])
2229 break;
2230 return 17 + ri * 36 + gi * 6 + bi;
2231 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 }
2233 return 0;
2234}
2235
2236/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002237 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 */
2239 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002240vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002241{
2242 int attr = 0;
2243
2244 if (cellattrs.bold)
2245 attr |= HL_BOLD;
2246 if (cellattrs.underline)
2247 attr |= HL_UNDERLINE;
2248 if (cellattrs.italic)
2249 attr |= HL_ITALIC;
2250 if (cellattrs.strike)
2251 attr |= HL_STRIKETHROUGH;
2252 if (cellattrs.reverse)
2253 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002254 return attr;
2255}
2256
2257/*
2258 * Store Vterm attributes in "cell" from highlight flags.
2259 */
2260 static void
2261hl2vtermAttr(int attr, cellattr_T *cell)
2262{
2263 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2264 if (attr & HL_BOLD)
2265 cell->attrs.bold = 1;
2266 if (attr & HL_UNDERLINE)
2267 cell->attrs.underline = 1;
2268 if (attr & HL_ITALIC)
2269 cell->attrs.italic = 1;
2270 if (attr & HL_STRIKETHROUGH)
2271 cell->attrs.strike = 1;
2272 if (attr & HL_INVERSE)
2273 cell->attrs.reverse = 1;
2274}
2275
2276/*
2277 * Convert the attributes of a vterm cell into an attribute index.
2278 */
2279 static int
2280cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2281{
2282 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002283
2284#ifdef FEAT_GUI
2285 if (gui.in_use)
2286 {
2287 guicolor_T fg, bg;
2288
2289 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2290 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2291 return get_gui_attr_idx(attr, fg, bg);
2292 }
2293 else
2294#endif
2295#ifdef FEAT_TERMGUICOLORS
2296 if (p_tgc)
2297 {
2298 guicolor_T fg, bg;
2299
2300 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2301 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2302
2303 return get_tgc_attr_idx(attr, fg, bg);
2304 }
2305 else
2306#endif
2307 {
2308 int bold = MAYBE;
2309 int fg = color2index(&cellfg, TRUE, &bold);
2310 int bg = color2index(&cellbg, FALSE, &bold);
2311
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002312 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002313 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002314 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002315 if (fg == 0 && term_default_cterm_fg >= 0)
2316 fg = term_default_cterm_fg + 1;
2317 if (bg == 0 && term_default_cterm_bg >= 0)
2318 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002319 }
2320
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002321 /* with 8 colors set the bold attribute to get a bright foreground */
2322 if (bold == TRUE)
2323 attr |= HL_BOLD;
2324 return get_cterm_attr_idx(attr, fg, bg);
2325 }
2326 return 0;
2327}
2328
2329 static int
2330handle_damage(VTermRect rect, void *user)
2331{
2332 term_T *term = (term_T *)user;
2333
2334 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2335 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2336 redraw_buf_later(term->tl_buffer, NOT_VALID);
2337 return 1;
2338}
2339
2340 static int
2341handle_moverect(VTermRect dest, VTermRect src, void *user)
2342{
2343 term_T *term = (term_T *)user;
2344
2345 /* Scrolling up is done much more efficiently by deleting lines instead of
2346 * redrawing the text. */
2347 if (dest.start_col == src.start_col
2348 && dest.end_col == src.end_col
2349 && dest.start_row < src.start_row)
2350 {
2351 win_T *wp;
2352 VTermColor fg, bg;
2353 VTermScreenCellAttrs attr;
2354 int clear_attr;
2355
2356 /* Set the color to clear lines with. */
2357 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2358 &fg, &bg);
2359 vim_memset(&attr, 0, sizeof(attr));
2360 clear_attr = cell2attr(attr, fg, bg);
2361
2362 FOR_ALL_WINDOWS(wp)
2363 {
2364 if (wp->w_buffer == term->tl_buffer)
2365 win_del_lines(wp, dest.start_row,
2366 src.start_row - dest.start_row, FALSE, FALSE,
2367 clear_attr);
2368 }
2369 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002370
2371 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2372 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2373
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 redraw_buf_later(term->tl_buffer, NOT_VALID);
2375 return 1;
2376}
2377
2378 static int
2379handle_movecursor(
2380 VTermPos pos,
2381 VTermPos oldpos UNUSED,
2382 int visible,
2383 void *user)
2384{
2385 term_T *term = (term_T *)user;
2386 win_T *wp;
2387
2388 term->tl_cursor_pos = pos;
2389 term->tl_cursor_visible = visible;
2390
2391 FOR_ALL_WINDOWS(wp)
2392 {
2393 if (wp->w_buffer == term->tl_buffer)
2394 position_cursor(wp, &pos);
2395 }
2396 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2397 {
2398 may_toggle_cursor(term);
2399 update_cursor(term, term->tl_cursor_visible);
2400 }
2401
2402 return 1;
2403}
2404
2405 static int
2406handle_settermprop(
2407 VTermProp prop,
2408 VTermValue *value,
2409 void *user)
2410{
2411 term_T *term = (term_T *)user;
2412
2413 switch (prop)
2414 {
2415 case VTERM_PROP_TITLE:
2416 vim_free(term->tl_title);
2417 /* a blank title isn't useful, make it empty, so that "running" is
2418 * displayed */
2419 if (*skipwhite((char_u *)value->string) == NUL)
2420 term->tl_title = NULL;
2421#ifdef WIN3264
2422 else if (!enc_utf8 && enc_codepage > 0)
2423 {
2424 WCHAR *ret = NULL;
2425 int length = 0;
2426
2427 MultiByteToWideChar_alloc(CP_UTF8, 0,
2428 (char*)value->string, (int)STRLEN(value->string),
2429 &ret, &length);
2430 if (ret != NULL)
2431 {
2432 WideCharToMultiByte_alloc(enc_codepage, 0,
2433 ret, length, (char**)&term->tl_title,
2434 &length, 0, 0);
2435 vim_free(ret);
2436 }
2437 }
2438#endif
2439 else
2440 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002441 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442 if (term == curbuf->b_term)
2443 maketitle();
2444 break;
2445
2446 case VTERM_PROP_CURSORVISIBLE:
2447 term->tl_cursor_visible = value->boolean;
2448 may_toggle_cursor(term);
2449 out_flush();
2450 break;
2451
2452 case VTERM_PROP_CURSORBLINK:
2453 term->tl_cursor_blink = value->boolean;
2454 may_set_cursor_props(term);
2455 break;
2456
2457 case VTERM_PROP_CURSORSHAPE:
2458 term->tl_cursor_shape = value->number;
2459 may_set_cursor_props(term);
2460 break;
2461
2462 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002463 if (desired_cursor_color == term->tl_cursor_color)
2464 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002465 vim_free(term->tl_cursor_color);
2466 if (*value->string == NUL)
2467 term->tl_cursor_color = NULL;
2468 else
2469 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2470 may_set_cursor_props(term);
2471 break;
2472
2473 case VTERM_PROP_ALTSCREEN:
2474 /* TODO: do anything else? */
2475 term->tl_using_altscreen = value->boolean;
2476 break;
2477
2478 default:
2479 break;
2480 }
2481 /* Always return 1, otherwise vterm doesn't store the value internally. */
2482 return 1;
2483}
2484
2485/*
2486 * The job running in the terminal resized the terminal.
2487 */
2488 static int
2489handle_resize(int rows, int cols, void *user)
2490{
2491 term_T *term = (term_T *)user;
2492 win_T *wp;
2493
2494 term->tl_rows = rows;
2495 term->tl_cols = cols;
2496 if (term->tl_vterm_size_changed)
2497 /* Size was set by vterm_set_size(), don't set the window size. */
2498 term->tl_vterm_size_changed = FALSE;
2499 else
2500 {
2501 FOR_ALL_WINDOWS(wp)
2502 {
2503 if (wp->w_buffer == term->tl_buffer)
2504 {
2505 win_setheight_win(rows, wp);
2506 win_setwidth_win(cols, wp);
2507 }
2508 }
2509 redraw_buf_later(term->tl_buffer, NOT_VALID);
2510 }
2511 return 1;
2512}
2513
2514/*
2515 * Handle a line that is pushed off the top of the screen.
2516 */
2517 static int
2518handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2519{
2520 term_T *term = (term_T *)user;
2521
2522 /* TODO: Limit the number of lines that are stored. */
2523 if (ga_grow(&term->tl_scrollback, 1) == OK)
2524 {
2525 cellattr_T *p = NULL;
2526 int len = 0;
2527 int i;
2528 int c;
2529 int col;
2530 sb_line_T *line;
2531 garray_T ga;
2532 cellattr_T fill_attr = term->tl_default_color;
2533
2534 /* do not store empty cells at the end */
2535 for (i = 0; i < cols; ++i)
2536 if (cells[i].chars[0] != 0)
2537 len = i + 1;
2538 else
2539 cell2cellattr(&cells[i], &fill_attr);
2540
2541 ga_init2(&ga, 1, 100);
2542 if (len > 0)
2543 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2544 if (p != NULL)
2545 {
2546 for (col = 0; col < len; col += cells[col].width)
2547 {
2548 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2549 {
2550 ga.ga_len = 0;
2551 break;
2552 }
2553 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2554 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2555 (char_u *)ga.ga_data + ga.ga_len);
2556 cell2cellattr(&cells[col], &p[col]);
2557 }
2558 }
2559 if (ga_grow(&ga, 1) == FAIL)
2560 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2561 else
2562 {
2563 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2564 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2565 }
2566 ga_clear(&ga);
2567
2568 line = (sb_line_T *)term->tl_scrollback.ga_data
2569 + term->tl_scrollback.ga_len;
2570 line->sb_cols = len;
2571 line->sb_cells = p;
2572 line->sb_fill_attr = fill_attr;
2573 ++term->tl_scrollback.ga_len;
2574 ++term->tl_scrollback_scrolled;
2575 }
2576 return 0; /* ignored */
2577}
2578
2579static VTermScreenCallbacks screen_callbacks = {
2580 handle_damage, /* damage */
2581 handle_moverect, /* moverect */
2582 handle_movecursor, /* movecursor */
2583 handle_settermprop, /* settermprop */
2584 NULL, /* bell */
2585 handle_resize, /* resize */
2586 handle_pushline, /* sb_pushline */
2587 NULL /* sb_popline */
2588};
2589
2590/*
2591 * Called when a channel has been closed.
2592 * If this was a channel for a terminal window then finish it up.
2593 */
2594 void
2595term_channel_closed(channel_T *ch)
2596{
2597 term_T *term;
2598 int did_one = FALSE;
2599
2600 for (term = first_term; term != NULL; term = term->tl_next)
2601 if (term->tl_job == ch->ch_job)
2602 {
2603 term->tl_channel_closed = TRUE;
2604 did_one = TRUE;
2605
Bram Moolenaard23a8232018-02-10 18:45:26 +01002606 VIM_CLEAR(term->tl_title);
2607 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002608
2609 /* Unless in Terminal-Normal mode: clear the vterm. */
2610 if (!term->tl_normal_mode)
2611 {
2612 int fnum = term->tl_buffer->b_fnum;
2613
2614 cleanup_vterm(term);
2615
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002616 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002617 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002618 aco_save_T aco;
2619
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002620 /* ++close or term_finish == "close" */
2621 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002622 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002624 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002625 break;
2626 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002627 if (term->tl_finish == TL_FINISH_OPEN
2628 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002629 {
2630 char buf[50];
2631
2632 /* TODO: use term_opencmd */
2633 ch_log(NULL, "terminal job finished, opening window");
2634 vim_snprintf(buf, sizeof(buf),
2635 term->tl_opencmd == NULL
2636 ? "botright sbuf %d"
2637 : (char *)term->tl_opencmd, fnum);
2638 do_cmdline_cmd((char_u *)buf);
2639 }
2640 else
2641 ch_log(NULL, "terminal job finished");
2642 }
2643
2644 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2645 }
2646 if (did_one)
2647 {
2648 redraw_statuslines();
2649
2650 /* Need to break out of vgetc(). */
2651 ins_char_typebuf(K_IGNORE);
2652 typebuf_was_filled = TRUE;
2653
2654 term = curbuf->b_term;
2655 if (term != NULL)
2656 {
2657 if (term->tl_job == ch->ch_job)
2658 maketitle();
2659 update_cursor(term, term->tl_cursor_visible);
2660 }
2661 }
2662}
2663
2664/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002665 * Fill one screen line from a line of the terminal.
2666 * Advances "pos" to past the last column.
2667 */
2668 static void
2669term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2670{
2671 int off = screen_get_current_line_off();
2672
2673 for (pos->col = 0; pos->col < max_col; )
2674 {
2675 VTermScreenCell cell;
2676 int c;
2677
2678 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2679 vim_memset(&cell, 0, sizeof(cell));
2680
2681 c = cell.chars[0];
2682 if (c == NUL)
2683 {
2684 ScreenLines[off] = ' ';
2685 if (enc_utf8)
2686 ScreenLinesUC[off] = NUL;
2687 }
2688 else
2689 {
2690 if (enc_utf8)
2691 {
2692 int i;
2693
2694 /* composing chars */
2695 for (i = 0; i < Screen_mco
2696 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2697 {
2698 ScreenLinesC[i][off] = cell.chars[i + 1];
2699 if (cell.chars[i + 1] == 0)
2700 break;
2701 }
2702 if (c >= 0x80 || (Screen_mco > 0
2703 && ScreenLinesC[0][off] != 0))
2704 {
2705 ScreenLines[off] = ' ';
2706 ScreenLinesUC[off] = c;
2707 }
2708 else
2709 {
2710 ScreenLines[off] = c;
2711 ScreenLinesUC[off] = NUL;
2712 }
2713 }
2714#ifdef WIN3264
2715 else if (has_mbyte && c >= 0x80)
2716 {
2717 char_u mb[MB_MAXBYTES+1];
2718 WCHAR wc = c;
2719
2720 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2721 (char*)mb, 2, 0, 0) > 1)
2722 {
2723 ScreenLines[off] = mb[0];
2724 ScreenLines[off + 1] = mb[1];
2725 cell.width = mb_ptr2cells(mb);
2726 }
2727 else
2728 ScreenLines[off] = c;
2729 }
2730#endif
2731 else
2732 ScreenLines[off] = c;
2733 }
2734 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2735
2736 ++pos->col;
2737 ++off;
2738 if (cell.width == 2)
2739 {
2740 if (enc_utf8)
2741 ScreenLinesUC[off] = NUL;
2742
2743 /* don't set the second byte to NUL for a DBCS encoding, it
2744 * has been set above */
2745 if (enc_utf8 || !has_mbyte)
2746 ScreenLines[off] = NUL;
2747
2748 ++pos->col;
2749 ++off;
2750 }
2751 }
2752}
2753
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002754#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002755 static void
2756update_system_term(term_T *term)
2757{
2758 VTermPos pos;
2759 VTermScreen *screen;
2760
2761 if (term->tl_vterm == NULL)
2762 return;
2763 screen = vterm_obtain_screen(term->tl_vterm);
2764
2765 /* Scroll up to make more room for terminal lines if needed. */
2766 while (term->tl_toprow > 0
2767 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2768 {
2769 int save_p_more = p_more;
2770
2771 p_more = FALSE;
2772 msg_row = Rows - 1;
2773 msg_puts((char_u *)"\n");
2774 p_more = save_p_more;
2775 --term->tl_toprow;
2776 }
2777
2778 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2779 && pos.row < Rows; ++pos.row)
2780 {
2781 if (pos.row < term->tl_rows)
2782 {
2783 int max_col = MIN(Columns, term->tl_cols);
2784
2785 term_line2screenline(screen, &pos, max_col);
2786 }
2787 else
2788 pos.col = 0;
2789
2790 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2791 }
2792
2793 term->tl_dirty_row_start = MAX_ROW;
2794 term->tl_dirty_row_end = 0;
2795 update_cursor(term, TRUE);
2796}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002797#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002798
2799/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002800 * Called to update a window that contains an active terminal.
2801 * Returns FAIL when there is no terminal running in this window or in
2802 * Terminal-Normal mode.
2803 */
2804 int
2805term_update_window(win_T *wp)
2806{
2807 term_T *term = wp->w_buffer->b_term;
2808 VTerm *vterm;
2809 VTermScreen *screen;
2810 VTermState *state;
2811 VTermPos pos;
2812
2813 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2814 return FAIL;
2815
2816 vterm = term->tl_vterm;
2817 screen = vterm_obtain_screen(vterm);
2818 state = vterm_obtain_state(vterm);
2819
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002820 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002821 {
2822 term->tl_dirty_row_start = 0;
2823 term->tl_dirty_row_end = MAX_ROW;
2824 }
2825
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 /*
2827 * If the window was resized a redraw will be triggered and we get here.
2828 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2829 */
2830 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2831 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2832 {
2833 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2834 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2835 win_T *twp;
2836
2837 FOR_ALL_WINDOWS(twp)
2838 {
2839 /* When more than one window shows the same terminal, use the
2840 * smallest size. */
2841 if (twp->w_buffer == term->tl_buffer)
2842 {
2843 if (!term->tl_rows_fixed && rows > twp->w_height)
2844 rows = twp->w_height;
2845 if (!term->tl_cols_fixed && cols > twp->w_width)
2846 cols = twp->w_width;
2847 }
2848 }
2849
2850 term->tl_vterm_size_changed = TRUE;
2851 vterm_set_size(vterm, rows, cols);
2852 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2853 rows);
2854 term_report_winsize(term, rows, cols);
2855 }
2856
2857 /* The cursor may have been moved when resizing. */
2858 vterm_state_get_cursorpos(state, &pos);
2859 position_cursor(wp, &pos);
2860
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002861 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2862 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002863 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002864 if (pos.row < term->tl_rows)
2865 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002866 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002867
Bram Moolenaar13568252018-03-16 20:46:58 +01002868 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002869 }
2870 else
2871 pos.col = 0;
2872
Bram Moolenaarf118d482018-03-13 13:14:00 +01002873 screen_line(wp->w_winrow + pos.row
2874#ifdef FEAT_MENU
2875 + winbar_height(wp)
2876#endif
2877 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002879 term->tl_dirty_row_start = MAX_ROW;
2880 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881
2882 return OK;
2883}
2884
2885/*
2886 * Return TRUE if "wp" is a terminal window where the job has finished.
2887 */
2888 int
2889term_is_finished(buf_T *buf)
2890{
2891 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2892}
2893
2894/*
2895 * Return TRUE if "wp" is a terminal window where the job has finished or we
2896 * are in Terminal-Normal mode, thus we show the buffer contents.
2897 */
2898 int
2899term_show_buffer(buf_T *buf)
2900{
2901 term_T *term = buf->b_term;
2902
2903 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2904}
2905
2906/*
2907 * The current buffer is going to be changed. If there is terminal
2908 * highlighting remove it now.
2909 */
2910 void
2911term_change_in_curbuf(void)
2912{
2913 term_T *term = curbuf->b_term;
2914
2915 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2916 {
2917 free_scrollback(term);
2918 redraw_buf_later(term->tl_buffer, NOT_VALID);
2919
2920 /* The buffer is now like a normal buffer, it cannot be easily
2921 * abandoned when changed. */
2922 set_string_option_direct((char_u *)"buftype", -1,
2923 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2924 }
2925}
2926
2927/*
2928 * Get the screen attribute for a position in the buffer.
2929 * Use a negative "col" to get the filler background color.
2930 */
2931 int
2932term_get_attr(buf_T *buf, linenr_T lnum, int col)
2933{
2934 term_T *term = buf->b_term;
2935 sb_line_T *line;
2936 cellattr_T *cellattr;
2937
2938 if (lnum > term->tl_scrollback.ga_len)
2939 cellattr = &term->tl_default_color;
2940 else
2941 {
2942 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2943 if (col < 0 || col >= line->sb_cols)
2944 cellattr = &line->sb_fill_attr;
2945 else
2946 cellattr = line->sb_cells + col;
2947 }
2948 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2949}
2950
2951static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002952 { 0, 0, 0, 1}, /* black */
2953 {224, 0, 0, 2}, /* dark red */
2954 { 0, 224, 0, 3}, /* dark green */
2955 {224, 224, 0, 4}, /* dark yellow / brown */
2956 { 0, 0, 224, 5}, /* dark blue */
2957 {224, 0, 224, 6}, /* dark magenta */
2958 { 0, 224, 224, 7}, /* dark cyan */
2959 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002960
Bram Moolenaar46359e12017-11-29 22:33:38 +01002961 {128, 128, 128, 9}, /* dark grey */
2962 {255, 64, 64, 10}, /* light red */
2963 { 64, 255, 64, 11}, /* light green */
2964 {255, 255, 64, 12}, /* yellow */
2965 { 64, 64, 255, 13}, /* light blue */
2966 {255, 64, 255, 14}, /* light magenta */
2967 { 64, 255, 255, 15}, /* light cyan */
2968 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969};
2970
2971static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002972 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973};
2974
2975static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002976 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2977 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978};
2979
2980/*
2981 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002982 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002983 */
2984 static void
2985cterm_color2rgb(int nr, VTermColor *rgb)
2986{
2987 int idx;
2988
2989 if (nr < 16)
2990 {
2991 *rgb = ansi_table[nr];
2992 }
2993 else if (nr < 232)
2994 {
2995 /* 216 color cube */
2996 idx = nr - 16;
2997 rgb->blue = cube_value[idx % 6];
2998 rgb->green = cube_value[idx / 6 % 6];
2999 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003000 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003001 }
3002 else if (nr < 256)
3003 {
3004 /* 24 grey scale ramp */
3005 idx = nr - 232;
3006 rgb->blue = grey_ramp[idx];
3007 rgb->green = grey_ramp[idx];
3008 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003009 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 }
3011}
3012
3013/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003014 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003015 */
3016 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003017init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003019 VTermColor *fg, *bg;
3020 int fgval, bgval;
3021 int id;
3022
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003023 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3024 term->tl_default_color.width = 1;
3025 fg = &term->tl_default_color.fg;
3026 bg = &term->tl_default_color.bg;
3027
3028 /* Vterm uses a default black background. Set it to white when
3029 * 'background' is "light". */
3030 if (*p_bg == 'l')
3031 {
3032 fgval = 0;
3033 bgval = 255;
3034 }
3035 else
3036 {
3037 fgval = 255;
3038 bgval = 0;
3039 }
3040 fg->red = fg->green = fg->blue = fgval;
3041 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003042 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003043
3044 /* The "Terminal" highlight group overrules the defaults. */
3045 id = syn_name2id((char_u *)"Terminal");
3046
Bram Moolenaar46359e12017-11-29 22:33:38 +01003047 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003048#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3049 if (0
3050# ifdef FEAT_GUI
3051 || gui.in_use
3052# endif
3053# ifdef FEAT_TERMGUICOLORS
3054 || p_tgc
3055# endif
3056 )
3057 {
3058 guicolor_T fg_rgb = INVALCOLOR;
3059 guicolor_T bg_rgb = INVALCOLOR;
3060
3061 if (id != 0)
3062 syn_id2colors(id, &fg_rgb, &bg_rgb);
3063
3064# ifdef FEAT_GUI
3065 if (gui.in_use)
3066 {
3067 if (fg_rgb == INVALCOLOR)
3068 fg_rgb = gui.norm_pixel;
3069 if (bg_rgb == INVALCOLOR)
3070 bg_rgb = gui.back_pixel;
3071 }
3072# ifdef FEAT_TERMGUICOLORS
3073 else
3074# endif
3075# endif
3076# ifdef FEAT_TERMGUICOLORS
3077 {
3078 if (fg_rgb == INVALCOLOR)
3079 fg_rgb = cterm_normal_fg_gui_color;
3080 if (bg_rgb == INVALCOLOR)
3081 bg_rgb = cterm_normal_bg_gui_color;
3082 }
3083# endif
3084 if (fg_rgb != INVALCOLOR)
3085 {
3086 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3087
3088 fg->red = (unsigned)(rgb >> 16);
3089 fg->green = (unsigned)(rgb >> 8) & 255;
3090 fg->blue = (unsigned)rgb & 255;
3091 }
3092 if (bg_rgb != INVALCOLOR)
3093 {
3094 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3095
3096 bg->red = (unsigned)(rgb >> 16);
3097 bg->green = (unsigned)(rgb >> 8) & 255;
3098 bg->blue = (unsigned)rgb & 255;
3099 }
3100 }
3101 else
3102#endif
3103 if (id != 0 && t_colors >= 16)
3104 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003105 if (term_default_cterm_fg >= 0)
3106 cterm_color2rgb(term_default_cterm_fg, fg);
3107 if (term_default_cterm_bg >= 0)
3108 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110 else
3111 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003112#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003113 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003114#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003115
3116 /* In an MS-Windows console we know the normal colors. */
3117 if (cterm_normal_fg_color > 0)
3118 {
3119 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003120# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003121 tmp = fg->red;
3122 fg->red = fg->blue;
3123 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003124# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003125 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003126# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003127 else
3128 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003129# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003130
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131 if (cterm_normal_bg_color > 0)
3132 {
3133 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003134# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003135 tmp = bg->red;
3136 bg->red = bg->blue;
3137 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003138# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003140# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003141 else
3142 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003143# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003144 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003145}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003146
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003147#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3148/*
3149 * Set the 16 ANSI colors from array of RGB values
3150 */
3151 static void
3152set_vterm_palette(VTerm *vterm, long_u *rgb)
3153{
3154 int index = 0;
3155 VTermState *state = vterm_obtain_state(vterm);
3156 for (; index < 16; index++)
3157 {
3158 VTermColor color;
3159 color.red = (unsigned)(rgb[index] >> 16);
3160 color.green = (unsigned)(rgb[index] >> 8) & 255;
3161 color.blue = (unsigned)rgb[index] & 255;
3162 vterm_state_set_palette_color(state, index, &color);
3163 }
3164}
3165
3166/*
3167 * Set the ANSI color palette from a list of colors
3168 */
3169 static int
3170set_ansi_colors_list(VTerm *vterm, list_T *list)
3171{
3172 int n = 0;
3173 long_u rgb[16];
3174 listitem_T *li = list->lv_first;
3175
3176 for (; li != NULL && n < 16; li = li->li_next, n++)
3177 {
3178 char_u *color_name;
3179 guicolor_T guicolor;
3180
3181 color_name = get_tv_string_chk(&li->li_tv);
3182 if (color_name == NULL)
3183 return FAIL;
3184
3185 guicolor = GUI_GET_COLOR(color_name);
3186 if (guicolor == INVALCOLOR)
3187 return FAIL;
3188
3189 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3190 }
3191
3192 if (n != 16 || li != NULL)
3193 return FAIL;
3194
3195 set_vterm_palette(vterm, rgb);
3196
3197 return OK;
3198}
3199
3200/*
3201 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3202 */
3203 static void
3204init_vterm_ansi_colors(VTerm *vterm)
3205{
3206 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3207
3208 if (var != NULL
3209 && (var->di_tv.v_type != VAR_LIST
3210 || var->di_tv.vval.v_list == NULL
3211 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3212 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3213}
3214#endif
3215
Bram Moolenaar52acb112018-03-18 19:20:22 +01003216/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003217 * Handles a "drop" command from the job in the terminal.
3218 * "item" is the file name, "item->li_next" may have options.
3219 */
3220 static void
3221handle_drop_command(listitem_T *item)
3222{
3223 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003224 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003225 int bufnr;
3226 win_T *wp;
3227 tabpage_T *tp;
3228 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003229 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003230
3231 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3232 FOR_ALL_TAB_WINDOWS(tp, wp)
3233 {
3234 if (wp->w_buffer->b_fnum == bufnr)
3235 {
3236 /* buffer is in a window already, go there */
3237 goto_tabpage_win(tp, wp);
3238 return;
3239 }
3240 }
3241
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003242 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003243
3244 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3245 && opt_item->li_tv.vval.v_dict != NULL)
3246 {
3247 dict_T *dict = opt_item->li_tv.vval.v_dict;
3248 char_u *p;
3249
3250 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3251 if (p == NULL)
3252 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3253 if (p != NULL)
3254 {
3255 if (check_ff_value(p) == FAIL)
3256 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3257 else
3258 ea.force_ff = *p;
3259 }
3260 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3261 if (p == NULL)
3262 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3263 if (p != NULL)
3264 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003265 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003266 if (ea.cmd != NULL)
3267 {
3268 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3269 ea.force_enc = 11;
3270 tofree = ea.cmd;
3271 }
3272 }
3273
3274 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3275 if (p != NULL)
3276 get_bad_opt(p, &ea);
3277
3278 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3279 ea.force_bin = FORCE_BIN;
3280 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3281 ea.force_bin = FORCE_BIN;
3282 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3283 ea.force_bin = FORCE_NOBIN;
3284 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3285 ea.force_bin = FORCE_NOBIN;
3286 }
3287
3288 /* open in new window, like ":split fname" */
3289 if (ea.cmd == NULL)
3290 ea.cmd = (char_u *)"split";
3291 ea.arg = fname;
3292 ea.cmdidx = CMD_split;
3293 ex_splitview(&ea);
3294
3295 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003296}
3297
3298/*
3299 * Handles a function call from the job running in a terminal.
3300 * "item" is the function name, "item->li_next" has the arguments.
3301 */
3302 static void
3303handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3304{
3305 char_u *func;
3306 typval_T argvars[2];
3307 typval_T rettv;
3308 int doesrange;
3309
3310 if (item->li_next == NULL)
3311 {
3312 ch_log(channel, "Missing function arguments for call");
3313 return;
3314 }
3315 func = get_tv_string(&item->li_tv);
3316
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003317 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003318 {
3319 ch_log(channel, "Invalid function name: %s", func);
3320 return;
3321 }
3322
3323 argvars[0].v_type = VAR_NUMBER;
3324 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3325 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003326 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003327 2, argvars, /* argv_func */ NULL,
3328 /* firstline */ 1, /* lastline */ 1,
3329 &doesrange, /* evaluate */ TRUE,
3330 /* partial */ NULL, /* selfdict */ NULL) == OK)
3331 {
3332 clear_tv(&rettv);
3333 ch_log(channel, "Function %s called", func);
3334 }
3335 else
3336 ch_log(channel, "Calling function %s failed", func);
3337}
3338
3339/*
3340 * Called by libvterm when it cannot recognize an OSC sequence.
3341 * We recognize a terminal API command.
3342 */
3343 static int
3344parse_osc(const char *command, size_t cmdlen, void *user)
3345{
3346 term_T *term = (term_T *)user;
3347 js_read_T reader;
3348 typval_T tv;
3349 channel_T *channel = term->tl_job == NULL ? NULL
3350 : term->tl_job->jv_channel;
3351
3352 /* We recognize only OSC 5 1 ; {command} */
3353 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3354 return 0; /* not handled */
3355
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003356 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003357 if (reader.js_buf == NULL)
3358 return 1;
3359 reader.js_fill = NULL;
3360 reader.js_used = 0;
3361 if (json_decode(&reader, &tv, 0) == OK
3362 && tv.v_type == VAR_LIST
3363 && tv.vval.v_list != NULL)
3364 {
3365 listitem_T *item = tv.vval.v_list->lv_first;
3366
3367 if (item == NULL)
3368 ch_log(channel, "Missing command");
3369 else
3370 {
3371 char_u *cmd = get_tv_string(&item->li_tv);
3372
3373 item = item->li_next;
3374 if (item == NULL)
3375 ch_log(channel, "Missing argument for %s", cmd);
3376 else if (STRCMP(cmd, "drop") == 0)
3377 handle_drop_command(item);
3378 else if (STRCMP(cmd, "call") == 0)
3379 handle_call_command(term, channel, item);
3380 else
3381 ch_log(channel, "Invalid command received: %s", cmd);
3382 }
3383 }
3384 else
3385 ch_log(channel, "Invalid JSON received");
3386
3387 vim_free(reader.js_buf);
3388 clear_tv(&tv);
3389 return 1;
3390}
3391
3392static VTermParserCallbacks parser_fallbacks = {
3393 NULL, /* text */
3394 NULL, /* control */
3395 NULL, /* escape */
3396 NULL, /* csi */
3397 parse_osc, /* osc */
3398 NULL, /* dcs */
3399 NULL /* resize */
3400};
3401
3402/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003403 * Use Vim's allocation functions for vterm so profiling works.
3404 */
3405 static void *
3406vterm_malloc(size_t size, void *data UNUSED)
3407{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003408 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003409}
3410
3411 static void
3412vterm_memfree(void *ptr, void *data UNUSED)
3413{
3414 vim_free(ptr);
3415}
3416
3417static VTermAllocatorFunctions vterm_allocator = {
3418 &vterm_malloc,
3419 &vterm_memfree
3420};
3421
3422/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003423 * Create a new vterm and initialize it.
3424 */
3425 static void
3426create_vterm(term_T *term, int rows, int cols)
3427{
3428 VTerm *vterm;
3429 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003430 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003431 VTermValue value;
3432
Bram Moolenaar756ef112018-04-10 12:04:27 +02003433 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003434 term->tl_vterm = vterm;
3435 screen = vterm_obtain_screen(vterm);
3436 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3437 /* TODO: depends on 'encoding'. */
3438 vterm_set_utf8(vterm, 1);
3439
3440 init_default_colors(term);
3441
3442 vterm_state_set_default_colors(
3443 vterm_obtain_state(vterm),
3444 &term->tl_default_color.fg,
3445 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003446
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003447 if (t_colors >= 16)
3448 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3449
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003450 /* Required to initialize most things. */
3451 vterm_screen_reset(screen, 1 /* hard */);
3452
3453 /* Allow using alternate screen. */
3454 vterm_screen_enable_altscreen(screen, 1);
3455
3456 /* For unix do not use a blinking cursor. In an xterm this causes the
3457 * cursor to blink if it's blinking in the xterm.
3458 * For Windows we respect the system wide setting. */
3459#ifdef WIN3264
3460 if (GetCaretBlinkTime() == INFINITE)
3461 value.boolean = 0;
3462 else
3463 value.boolean = 1;
3464#else
3465 value.boolean = 0;
3466#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003467 state = vterm_obtain_state(vterm);
3468 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3469 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003470}
3471
3472/*
3473 * Return the text to show for the buffer name and status.
3474 */
3475 char_u *
3476term_get_status_text(term_T *term)
3477{
3478 if (term->tl_status_text == NULL)
3479 {
3480 char_u *txt;
3481 size_t len;
3482
3483 if (term->tl_normal_mode)
3484 {
3485 if (term_job_running(term))
3486 txt = (char_u *)_("Terminal");
3487 else
3488 txt = (char_u *)_("Terminal-finished");
3489 }
3490 else if (term->tl_title != NULL)
3491 txt = term->tl_title;
3492 else if (term_none_open(term))
3493 txt = (char_u *)_("active");
3494 else if (term_job_running(term))
3495 txt = (char_u *)_("running");
3496 else
3497 txt = (char_u *)_("finished");
3498 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3499 term->tl_status_text = alloc((int)len);
3500 if (term->tl_status_text != NULL)
3501 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3502 term->tl_buffer->b_fname, txt);
3503 }
3504 return term->tl_status_text;
3505}
3506
3507/*
3508 * Mark references in jobs of terminals.
3509 */
3510 int
3511set_ref_in_term(int copyID)
3512{
3513 int abort = FALSE;
3514 term_T *term;
3515 typval_T tv;
3516
3517 for (term = first_term; term != NULL; term = term->tl_next)
3518 if (term->tl_job != NULL)
3519 {
3520 tv.v_type = VAR_JOB;
3521 tv.vval.v_job = term->tl_job;
3522 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3523 }
3524 return abort;
3525}
3526
3527/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003528 * Cache "Terminal" highlight group colors.
3529 */
3530 void
3531set_terminal_default_colors(int cterm_fg, int cterm_bg)
3532{
3533 term_default_cterm_fg = cterm_fg - 1;
3534 term_default_cterm_bg = cterm_bg - 1;
3535}
3536
3537/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003538 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003539 * Returns NULL when the buffer is not for a terminal window and logs a message
3540 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003541 */
3542 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003543term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003544{
3545 buf_T *buf;
3546
3547 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3548 ++emsg_off;
3549 buf = get_buf_tv(&argvars[0], FALSE);
3550 --emsg_off;
3551 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003552 {
3553 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003554 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003555 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003556 return buf;
3557}
3558
Bram Moolenaard96ff162018-02-18 22:13:29 +01003559 static int
3560same_color(VTermColor *a, VTermColor *b)
3561{
3562 return a->red == b->red
3563 && a->green == b->green
3564 && a->blue == b->blue
3565 && a->ansi_index == b->ansi_index;
3566}
3567
3568 static void
3569dump_term_color(FILE *fd, VTermColor *color)
3570{
3571 fprintf(fd, "%02x%02x%02x%d",
3572 (int)color->red, (int)color->green, (int)color->blue,
3573 (int)color->ansi_index);
3574}
3575
3576/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003577 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003578 *
3579 * Each screen cell in full is:
3580 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3581 * {characters} is a space for an empty cell
3582 * For a double-width character "+" is changed to "*" and the next cell is
3583 * skipped.
3584 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3585 * when "&" use the same as the previous cell.
3586 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3587 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3588 * {color-idx} is a number from 0 to 255
3589 *
3590 * Screen cell with same width, attributes and color as the previous one:
3591 * |{characters}
3592 *
3593 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3594 *
3595 * Repeating the previous screen cell:
3596 * @{count}
3597 */
3598 void
3599f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3600{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003601 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003602 term_T *term;
3603 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003604 int max_height = 0;
3605 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003606 stat_T st;
3607 FILE *fd;
3608 VTermPos pos;
3609 VTermScreen *screen;
3610 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003611 VTermState *state;
3612 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003613
3614 if (check_restricted() || check_secure())
3615 return;
3616 if (buf == NULL)
3617 return;
3618 term = buf->b_term;
3619
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003620 if (argvars[2].v_type != VAR_UNKNOWN)
3621 {
3622 dict_T *d;
3623
3624 if (argvars[2].v_type != VAR_DICT)
3625 {
3626 EMSG(_(e_dictreq));
3627 return;
3628 }
3629 d = argvars[2].vval.v_dict;
3630 if (d != NULL)
3631 {
3632 max_height = get_dict_number(d, (char_u *)"rows");
3633 max_width = get_dict_number(d, (char_u *)"columns");
3634 }
3635 }
3636
Bram Moolenaard96ff162018-02-18 22:13:29 +01003637 fname = get_tv_string_chk(&argvars[1]);
3638 if (fname == NULL)
3639 return;
3640 if (mch_stat((char *)fname, &st) >= 0)
3641 {
3642 EMSG2(_("E953: File exists: %s"), fname);
3643 return;
3644 }
3645
Bram Moolenaard96ff162018-02-18 22:13:29 +01003646 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3647 {
3648 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3649 return;
3650 }
3651
3652 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3653
3654 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003655 state = vterm_obtain_state(term->tl_vterm);
3656 vterm_state_get_cursorpos(state, &cursor_pos);
3657
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003658 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3659 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003660 {
3661 int repeat = 0;
3662
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003663 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3664 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003665 {
3666 VTermScreenCell cell;
3667 int same_attr;
3668 int same_chars = TRUE;
3669 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003670 int is_cursor_pos = (pos.col == cursor_pos.col
3671 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003672
3673 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3674 vim_memset(&cell, 0, sizeof(cell));
3675
3676 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3677 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003678 int c = cell.chars[i];
3679 int pc = prev_cell.chars[i];
3680
3681 /* For the first character NUL is the same as space. */
3682 if (i == 0)
3683 {
3684 c = (c == NUL) ? ' ' : c;
3685 pc = (pc == NUL) ? ' ' : pc;
3686 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003687 if (cell.chars[i] != prev_cell.chars[i])
3688 same_chars = FALSE;
3689 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3690 break;
3691 }
3692 same_attr = vtermAttr2hl(cell.attrs)
3693 == vtermAttr2hl(prev_cell.attrs)
3694 && same_color(&cell.fg, &prev_cell.fg)
3695 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003696 if (same_chars && cell.width == prev_cell.width && same_attr
3697 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003698 {
3699 ++repeat;
3700 }
3701 else
3702 {
3703 if (repeat > 0)
3704 {
3705 fprintf(fd, "@%d", repeat);
3706 repeat = 0;
3707 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003708 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003709
3710 if (cell.chars[0] == NUL)
3711 fputs(" ", fd);
3712 else
3713 {
3714 char_u charbuf[10];
3715 int len;
3716
3717 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3718 && cell.chars[i] != NUL; ++i)
3719 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003720 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003721 fwrite(charbuf, len, 1, fd);
3722 }
3723 }
3724
3725 /* When only the characters differ we don't write anything, the
3726 * following "|", "@" or NL will indicate using the same
3727 * attributes. */
3728 if (cell.width != prev_cell.width || !same_attr)
3729 {
3730 if (cell.width == 2)
3731 {
3732 fputs("*", fd);
3733 ++pos.col;
3734 }
3735 else
3736 fputs("+", fd);
3737
3738 if (same_attr)
3739 {
3740 fputs("&", fd);
3741 }
3742 else
3743 {
3744 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3745 if (same_color(&cell.fg, &prev_cell.fg))
3746 fputs("&", fd);
3747 else
3748 {
3749 fputs("#", fd);
3750 dump_term_color(fd, &cell.fg);
3751 }
3752 if (same_color(&cell.bg, &prev_cell.bg))
3753 fputs("&", fd);
3754 else
3755 {
3756 fputs("#", fd);
3757 dump_term_color(fd, &cell.bg);
3758 }
3759 }
3760 }
3761
3762 prev_cell = cell;
3763 }
3764 }
3765 if (repeat > 0)
3766 fprintf(fd, "@%d", repeat);
3767 fputs("\n", fd);
3768 }
3769
3770 fclose(fd);
3771}
3772
3773/*
3774 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3775 */
3776 static void
3777dump_is_corrupt(garray_T *gap)
3778{
3779 ga_concat(gap, (char_u *)"CORRUPT");
3780}
3781
3782 static void
3783append_cell(garray_T *gap, cellattr_T *cell)
3784{
3785 if (ga_grow(gap, 1) == OK)
3786 {
3787 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3788 ++gap->ga_len;
3789 }
3790}
3791
3792/*
3793 * Read the dump file from "fd" and append lines to the current buffer.
3794 * Return the cell width of the longest line.
3795 */
3796 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003797read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003798{
3799 int c;
3800 garray_T ga_text;
3801 garray_T ga_cell;
3802 char_u *prev_char = NULL;
3803 int attr = 0;
3804 cellattr_T cell;
3805 term_T *term = curbuf->b_term;
3806 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003807 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003808
3809 ga_init2(&ga_text, 1, 90);
3810 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3811 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003812 cursor_pos->row = -1;
3813 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003814
3815 c = fgetc(fd);
3816 for (;;)
3817 {
3818 if (c == EOF)
3819 break;
3820 if (c == '\n')
3821 {
3822 /* End of a line: append it to the buffer. */
3823 if (ga_text.ga_data == NULL)
3824 dump_is_corrupt(&ga_text);
3825 if (ga_grow(&term->tl_scrollback, 1) == OK)
3826 {
3827 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3828 + term->tl_scrollback.ga_len;
3829
3830 if (max_cells < ga_cell.ga_len)
3831 max_cells = ga_cell.ga_len;
3832 line->sb_cols = ga_cell.ga_len;
3833 line->sb_cells = ga_cell.ga_data;
3834 line->sb_fill_attr = term->tl_default_color;
3835 ++term->tl_scrollback.ga_len;
3836 ga_init(&ga_cell);
3837
3838 ga_append(&ga_text, NUL);
3839 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3840 ga_text.ga_len, FALSE);
3841 }
3842 else
3843 ga_clear(&ga_cell);
3844 ga_text.ga_len = 0;
3845
3846 c = fgetc(fd);
3847 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003848 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003849 {
3850 int prev_len = ga_text.ga_len;
3851
Bram Moolenaar9271d052018-02-25 21:39:46 +01003852 if (c == '>')
3853 {
3854 if (cursor_pos->row != -1)
3855 dump_is_corrupt(&ga_text); /* duplicate cursor */
3856 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3857 cursor_pos->col = ga_cell.ga_len;
3858 }
3859
Bram Moolenaard96ff162018-02-18 22:13:29 +01003860 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3861 c = fgetc(fd);
3862 if (c != EOF)
3863 ga_append(&ga_text, c);
3864 for (;;)
3865 {
3866 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003867 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003868 || c == EOF || c == '\n')
3869 break;
3870 ga_append(&ga_text, c);
3871 }
3872
3873 /* save the character for repeating it */
3874 vim_free(prev_char);
3875 if (ga_text.ga_data != NULL)
3876 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3877 ga_text.ga_len - prev_len);
3878
Bram Moolenaar9271d052018-02-25 21:39:46 +01003879 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003880 {
3881 /* use all attributes from previous cell */
3882 }
3883 else if (c == '+' || c == '*')
3884 {
3885 int is_bg;
3886
3887 cell.width = c == '+' ? 1 : 2;
3888
3889 c = fgetc(fd);
3890 if (c == '&')
3891 {
3892 /* use same attr as previous cell */
3893 c = fgetc(fd);
3894 }
3895 else if (isdigit(c))
3896 {
3897 /* get the decimal attribute */
3898 attr = 0;
3899 while (isdigit(c))
3900 {
3901 attr = attr * 10 + (c - '0');
3902 c = fgetc(fd);
3903 }
3904 hl2vtermAttr(attr, &cell);
3905 }
3906 else
3907 dump_is_corrupt(&ga_text);
3908
3909 /* is_bg == 0: fg, is_bg == 1: bg */
3910 for (is_bg = 0; is_bg <= 1; ++is_bg)
3911 {
3912 if (c == '&')
3913 {
3914 /* use same color as previous cell */
3915 c = fgetc(fd);
3916 }
3917 else if (c == '#')
3918 {
3919 int red, green, blue, index = 0;
3920
3921 c = fgetc(fd);
3922 red = hex2nr(c);
3923 c = fgetc(fd);
3924 red = (red << 4) + hex2nr(c);
3925 c = fgetc(fd);
3926 green = hex2nr(c);
3927 c = fgetc(fd);
3928 green = (green << 4) + hex2nr(c);
3929 c = fgetc(fd);
3930 blue = hex2nr(c);
3931 c = fgetc(fd);
3932 blue = (blue << 4) + hex2nr(c);
3933 c = fgetc(fd);
3934 if (!isdigit(c))
3935 dump_is_corrupt(&ga_text);
3936 while (isdigit(c))
3937 {
3938 index = index * 10 + (c - '0');
3939 c = fgetc(fd);
3940 }
3941
3942 if (is_bg)
3943 {
3944 cell.bg.red = red;
3945 cell.bg.green = green;
3946 cell.bg.blue = blue;
3947 cell.bg.ansi_index = index;
3948 }
3949 else
3950 {
3951 cell.fg.red = red;
3952 cell.fg.green = green;
3953 cell.fg.blue = blue;
3954 cell.fg.ansi_index = index;
3955 }
3956 }
3957 else
3958 dump_is_corrupt(&ga_text);
3959 }
3960 }
3961 else
3962 dump_is_corrupt(&ga_text);
3963
3964 append_cell(&ga_cell, &cell);
3965 }
3966 else if (c == '@')
3967 {
3968 if (prev_char == NULL)
3969 dump_is_corrupt(&ga_text);
3970 else
3971 {
3972 int count = 0;
3973
3974 /* repeat previous character, get the count */
3975 for (;;)
3976 {
3977 c = fgetc(fd);
3978 if (!isdigit(c))
3979 break;
3980 count = count * 10 + (c - '0');
3981 }
3982
3983 while (count-- > 0)
3984 {
3985 ga_concat(&ga_text, prev_char);
3986 append_cell(&ga_cell, &cell);
3987 }
3988 }
3989 }
3990 else
3991 {
3992 dump_is_corrupt(&ga_text);
3993 c = fgetc(fd);
3994 }
3995 }
3996
3997 if (ga_text.ga_len > 0)
3998 {
3999 /* trailing characters after last NL */
4000 dump_is_corrupt(&ga_text);
4001 ga_append(&ga_text, NUL);
4002 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4003 ga_text.ga_len, FALSE);
4004 }
4005
4006 ga_clear(&ga_text);
4007 vim_free(prev_char);
4008
4009 return max_cells;
4010}
4011
4012/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004013 * Return an allocated string with at least "text_width" "=" characters and
4014 * "fname" inserted in the middle.
4015 */
4016 static char_u *
4017get_separator(int text_width, char_u *fname)
4018{
4019 int width = MAX(text_width, curwin->w_width);
4020 char_u *textline;
4021 int fname_size;
4022 char_u *p = fname;
4023 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004024 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004025
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004026 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004027 if (textline == NULL)
4028 return NULL;
4029
4030 fname_size = vim_strsize(fname);
4031 if (fname_size < width - 8)
4032 {
4033 /* enough room, don't use the full window width */
4034 width = MAX(text_width, fname_size + 8);
4035 }
4036 else if (fname_size > width - 8)
4037 {
4038 /* full name doesn't fit, use only the tail */
4039 p = gettail(fname);
4040 fname_size = vim_strsize(p);
4041 }
4042 /* skip characters until the name fits */
4043 while (fname_size > width - 8)
4044 {
4045 p += (*mb_ptr2len)(p);
4046 fname_size = vim_strsize(p);
4047 }
4048
4049 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4050 textline[i] = '=';
4051 textline[i++] = ' ';
4052
4053 STRCPY(textline + i, p);
4054 off = STRLEN(textline);
4055 textline[off] = ' ';
4056 for (i = 1; i < (width - fname_size) / 2; ++i)
4057 textline[off + i] = '=';
4058 textline[off + i] = NUL;
4059
4060 return textline;
4061}
4062
4063/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004064 * Common for "term_dumpdiff()" and "term_dumpload()".
4065 */
4066 static void
4067term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4068{
4069 jobopt_T opt;
4070 buf_T *buf;
4071 char_u buf1[NUMBUFLEN];
4072 char_u buf2[NUMBUFLEN];
4073 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004074 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004075 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004076 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004077 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004078 char_u *textline = NULL;
4079
4080 /* First open the files. If this fails bail out. */
4081 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4082 if (do_diff)
4083 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4084 if (fname1 == NULL || (do_diff && fname2 == NULL))
4085 {
4086 EMSG(_(e_invarg));
4087 return;
4088 }
4089 fd1 = mch_fopen((char *)fname1, READBIN);
4090 if (fd1 == NULL)
4091 {
4092 EMSG2(_(e_notread), fname1);
4093 return;
4094 }
4095 if (do_diff)
4096 {
4097 fd2 = mch_fopen((char *)fname2, READBIN);
4098 if (fd2 == NULL)
4099 {
4100 fclose(fd1);
4101 EMSG2(_(e_notread), fname2);
4102 return;
4103 }
4104 }
4105
4106 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004107 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4108 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4109 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4110 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4111 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004112
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004113 if (opt.jo_term_name == NULL)
4114 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004115 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004116
Bram Moolenaarb571c632018-03-21 22:27:59 +01004117 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004118 if (fname_tofree != NULL)
4119 {
4120 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4121 opt.jo_term_name = fname_tofree;
4122 }
4123 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004124
Bram Moolenaar13568252018-03-16 20:46:58 +01004125 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004126 if (buf != NULL && buf->b_term != NULL)
4127 {
4128 int i;
4129 linenr_T bot_lnum;
4130 linenr_T lnum;
4131 term_T *term = buf->b_term;
4132 int width;
4133 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004134 VTermPos cursor_pos1;
4135 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004136
Bram Moolenaar52acb112018-03-18 19:20:22 +01004137 init_default_colors(term);
4138
Bram Moolenaard96ff162018-02-18 22:13:29 +01004139 rettv->vval.v_number = buf->b_fnum;
4140
4141 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004142 width = read_dump_file(fd1, &cursor_pos1);
4143
4144 /* position the cursor */
4145 if (cursor_pos1.row >= 0)
4146 {
4147 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4148 coladvance(cursor_pos1.col);
4149 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004150
4151 /* Delete the empty line that was in the empty buffer. */
4152 ml_delete(1, FALSE);
4153
4154 /* For term_dumpload() we are done here. */
4155 if (!do_diff)
4156 goto theend;
4157
4158 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4159
Bram Moolenaar4a696342018-04-05 18:45:26 +02004160 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004161 if (textline == NULL)
4162 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004163 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4164 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4165 vim_free(textline);
4166
4167 textline = get_separator(width, fname2);
4168 if (textline == NULL)
4169 goto theend;
4170 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4171 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004172 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004173
4174 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004175 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004176 if (width2 > width)
4177 {
4178 vim_free(textline);
4179 textline = alloc(width2 + 1);
4180 if (textline == NULL)
4181 goto theend;
4182 width = width2;
4183 textline[width] = NUL;
4184 }
4185 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4186
4187 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4188 {
4189 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4190 {
4191 /* bottom part has fewer rows, fill with "-" */
4192 for (i = 0; i < width; ++i)
4193 textline[i] = '-';
4194 }
4195 else
4196 {
4197 char_u *line1;
4198 char_u *line2;
4199 char_u *p1;
4200 char_u *p2;
4201 int col;
4202 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4203 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4204 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4205 ->sb_cells;
4206
4207 /* Make a copy, getting the second line will invalidate it. */
4208 line1 = vim_strsave(ml_get(lnum));
4209 if (line1 == NULL)
4210 break;
4211 p1 = line1;
4212
4213 line2 = ml_get(lnum + bot_lnum);
4214 p2 = line2;
4215 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4216 {
4217 int len1 = utfc_ptr2len(p1);
4218 int len2 = utfc_ptr2len(p2);
4219
4220 textline[col] = ' ';
4221 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004222 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004223 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004224 else if (lnum == cursor_pos1.row + 1
4225 && col == cursor_pos1.col
4226 && (cursor_pos1.row != cursor_pos2.row
4227 || cursor_pos1.col != cursor_pos2.col))
4228 /* cursor in first but not in second */
4229 textline[col] = '>';
4230 else if (lnum == cursor_pos2.row + 1
4231 && col == cursor_pos2.col
4232 && (cursor_pos1.row != cursor_pos2.row
4233 || cursor_pos1.col != cursor_pos2.col))
4234 /* cursor in second but not in first */
4235 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004236 else if (cellattr1 != NULL && cellattr2 != NULL)
4237 {
4238 if ((cellattr1 + col)->width
4239 != (cellattr2 + col)->width)
4240 textline[col] = 'w';
4241 else if (!same_color(&(cellattr1 + col)->fg,
4242 &(cellattr2 + col)->fg))
4243 textline[col] = 'f';
4244 else if (!same_color(&(cellattr1 + col)->bg,
4245 &(cellattr2 + col)->bg))
4246 textline[col] = 'b';
4247 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4248 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4249 textline[col] = 'a';
4250 }
4251 p1 += len1;
4252 p2 += len2;
4253 /* TODO: handle different width */
4254 }
4255 vim_free(line1);
4256
4257 while (col < width)
4258 {
4259 if (*p1 == NUL && *p2 == NUL)
4260 textline[col] = '?';
4261 else if (*p1 == NUL)
4262 {
4263 textline[col] = '+';
4264 p2 += utfc_ptr2len(p2);
4265 }
4266 else
4267 {
4268 textline[col] = '-';
4269 p1 += utfc_ptr2len(p1);
4270 }
4271 ++col;
4272 }
4273 }
4274 if (add_empty_scrollback(term, &term->tl_default_color,
4275 term->tl_top_diff_rows) == OK)
4276 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4277 ++bot_lnum;
4278 }
4279
4280 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4281 {
4282 /* bottom part has more rows, fill with "+" */
4283 for (i = 0; i < width; ++i)
4284 textline[i] = '+';
4285 if (add_empty_scrollback(term, &term->tl_default_color,
4286 term->tl_top_diff_rows) == OK)
4287 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4288 ++lnum;
4289 ++bot_lnum;
4290 }
4291
4292 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004293
4294 /* looks better without wrapping */
4295 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004296 }
4297
4298theend:
4299 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004300 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004301 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004302 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004303 fclose(fd2);
4304}
4305
4306/*
4307 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4308 * bottom files.
4309 * Return FAIL when this is not possible.
4310 */
4311 int
4312term_swap_diff()
4313{
4314 term_T *term = curbuf->b_term;
4315 linenr_T line_count;
4316 linenr_T top_rows;
4317 linenr_T bot_rows;
4318 linenr_T bot_start;
4319 linenr_T lnum;
4320 char_u *p;
4321 sb_line_T *sb_line;
4322
4323 if (term == NULL
4324 || !term_is_finished(curbuf)
4325 || term->tl_top_diff_rows == 0
4326 || term->tl_scrollback.ga_len == 0)
4327 return FAIL;
4328
4329 line_count = curbuf->b_ml.ml_line_count;
4330 top_rows = term->tl_top_diff_rows;
4331 bot_rows = term->tl_bot_diff_rows;
4332 bot_start = line_count - bot_rows;
4333 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4334
4335 /* move lines from top to above the bottom part */
4336 for (lnum = 1; lnum <= top_rows; ++lnum)
4337 {
4338 p = vim_strsave(ml_get(1));
4339 if (p == NULL)
4340 return OK;
4341 ml_append(bot_start, p, 0, FALSE);
4342 ml_delete(1, FALSE);
4343 vim_free(p);
4344 }
4345
4346 /* move lines from bottom to the top */
4347 for (lnum = 1; lnum <= bot_rows; ++lnum)
4348 {
4349 p = vim_strsave(ml_get(bot_start + lnum));
4350 if (p == NULL)
4351 return OK;
4352 ml_delete(bot_start + lnum, FALSE);
4353 ml_append(lnum - 1, p, 0, FALSE);
4354 vim_free(p);
4355 }
4356
4357 if (top_rows == bot_rows)
4358 {
4359 /* rows counts are equal, can swap cell properties */
4360 for (lnum = 0; lnum < top_rows; ++lnum)
4361 {
4362 sb_line_T temp;
4363
4364 temp = *(sb_line + lnum);
4365 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4366 *(sb_line + bot_start + lnum) = temp;
4367 }
4368 }
4369 else
4370 {
4371 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4372 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4373
4374 /* need to copy cell properties into temp memory */
4375 if (temp != NULL)
4376 {
4377 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4378 mch_memmove(term->tl_scrollback.ga_data,
4379 temp + bot_start,
4380 sizeof(sb_line_T) * bot_rows);
4381 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4382 temp + top_rows,
4383 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4384 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4385 + line_count - top_rows,
4386 temp,
4387 sizeof(sb_line_T) * top_rows);
4388 vim_free(temp);
4389 }
4390 }
4391
4392 term->tl_top_diff_rows = bot_rows;
4393 term->tl_bot_diff_rows = top_rows;
4394
4395 update_screen(NOT_VALID);
4396 return OK;
4397}
4398
4399/*
4400 * "term_dumpdiff(filename, filename, options)" function
4401 */
4402 void
4403f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4404{
4405 term_load_dump(argvars, rettv, TRUE);
4406}
4407
4408/*
4409 * "term_dumpload(filename, options)" function
4410 */
4411 void
4412f_term_dumpload(typval_T *argvars, typval_T *rettv)
4413{
4414 term_load_dump(argvars, rettv, FALSE);
4415}
4416
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004417/*
4418 * "term_getaltscreen(buf)" function
4419 */
4420 void
4421f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4422{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004423 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004424
4425 if (buf == NULL)
4426 return;
4427 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4428}
4429
4430/*
4431 * "term_getattr(attr, name)" function
4432 */
4433 void
4434f_term_getattr(typval_T *argvars, typval_T *rettv)
4435{
4436 int attr;
4437 size_t i;
4438 char_u *name;
4439
4440 static struct {
4441 char *name;
4442 int attr;
4443 } attrs[] = {
4444 {"bold", HL_BOLD},
4445 {"italic", HL_ITALIC},
4446 {"underline", HL_UNDERLINE},
4447 {"strike", HL_STRIKETHROUGH},
4448 {"reverse", HL_INVERSE},
4449 };
4450
4451 attr = get_tv_number(&argvars[0]);
4452 name = get_tv_string_chk(&argvars[1]);
4453 if (name == NULL)
4454 return;
4455
4456 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4457 if (STRCMP(name, attrs[i].name) == 0)
4458 {
4459 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4460 break;
4461 }
4462}
4463
4464/*
4465 * "term_getcursor(buf)" function
4466 */
4467 void
4468f_term_getcursor(typval_T *argvars, typval_T *rettv)
4469{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004470 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004471 term_T *term;
4472 list_T *l;
4473 dict_T *d;
4474
4475 if (rettv_list_alloc(rettv) == FAIL)
4476 return;
4477 if (buf == NULL)
4478 return;
4479 term = buf->b_term;
4480
4481 l = rettv->vval.v_list;
4482 list_append_number(l, term->tl_cursor_pos.row + 1);
4483 list_append_number(l, term->tl_cursor_pos.col + 1);
4484
4485 d = dict_alloc();
4486 if (d != NULL)
4487 {
4488 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4489 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4490 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4491 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4492 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4493 ? (char_u *)"" : term->tl_cursor_color);
4494 list_append_dict(l, d);
4495 }
4496}
4497
4498/*
4499 * "term_getjob(buf)" function
4500 */
4501 void
4502f_term_getjob(typval_T *argvars, typval_T *rettv)
4503{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004504 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004505
4506 rettv->v_type = VAR_JOB;
4507 rettv->vval.v_job = NULL;
4508 if (buf == NULL)
4509 return;
4510
4511 rettv->vval.v_job = buf->b_term->tl_job;
4512 if (rettv->vval.v_job != NULL)
4513 ++rettv->vval.v_job->jv_refcount;
4514}
4515
4516 static int
4517get_row_number(typval_T *tv, term_T *term)
4518{
4519 if (tv->v_type == VAR_STRING
4520 && tv->vval.v_string != NULL
4521 && STRCMP(tv->vval.v_string, ".") == 0)
4522 return term->tl_cursor_pos.row;
4523 return (int)get_tv_number(tv) - 1;
4524}
4525
4526/*
4527 * "term_getline(buf, row)" function
4528 */
4529 void
4530f_term_getline(typval_T *argvars, typval_T *rettv)
4531{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004532 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004533 term_T *term;
4534 int row;
4535
4536 rettv->v_type = VAR_STRING;
4537 if (buf == NULL)
4538 return;
4539 term = buf->b_term;
4540 row = get_row_number(&argvars[1], term);
4541
4542 if (term->tl_vterm == NULL)
4543 {
4544 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4545
4546 /* vterm is finished, get the text from the buffer */
4547 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4548 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4549 }
4550 else
4551 {
4552 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4553 VTermRect rect;
4554 int len;
4555 char_u *p;
4556
4557 if (row < 0 || row >= term->tl_rows)
4558 return;
4559 len = term->tl_cols * MB_MAXBYTES + 1;
4560 p = alloc(len);
4561 if (p == NULL)
4562 return;
4563 rettv->vval.v_string = p;
4564
4565 rect.start_col = 0;
4566 rect.end_col = term->tl_cols;
4567 rect.start_row = row;
4568 rect.end_row = row + 1;
4569 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4570 }
4571}
4572
4573/*
4574 * "term_getscrolled(buf)" function
4575 */
4576 void
4577f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4578{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004579 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004580
4581 if (buf == NULL)
4582 return;
4583 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4584}
4585
4586/*
4587 * "term_getsize(buf)" function
4588 */
4589 void
4590f_term_getsize(typval_T *argvars, typval_T *rettv)
4591{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004592 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004593 list_T *l;
4594
4595 if (rettv_list_alloc(rettv) == FAIL)
4596 return;
4597 if (buf == NULL)
4598 return;
4599
4600 l = rettv->vval.v_list;
4601 list_append_number(l, buf->b_term->tl_rows);
4602 list_append_number(l, buf->b_term->tl_cols);
4603}
4604
4605/*
4606 * "term_getstatus(buf)" function
4607 */
4608 void
4609f_term_getstatus(typval_T *argvars, typval_T *rettv)
4610{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004611 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004612 term_T *term;
4613 char_u val[100];
4614
4615 rettv->v_type = VAR_STRING;
4616 if (buf == NULL)
4617 return;
4618 term = buf->b_term;
4619
4620 if (term_job_running(term))
4621 STRCPY(val, "running");
4622 else
4623 STRCPY(val, "finished");
4624 if (term->tl_normal_mode)
4625 STRCAT(val, ",normal");
4626 rettv->vval.v_string = vim_strsave(val);
4627}
4628
4629/*
4630 * "term_gettitle(buf)" function
4631 */
4632 void
4633f_term_gettitle(typval_T *argvars, typval_T *rettv)
4634{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004635 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004636
4637 rettv->v_type = VAR_STRING;
4638 if (buf == NULL)
4639 return;
4640
4641 if (buf->b_term->tl_title != NULL)
4642 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4643}
4644
4645/*
4646 * "term_gettty(buf)" function
4647 */
4648 void
4649f_term_gettty(typval_T *argvars, typval_T *rettv)
4650{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004651 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004652 char_u *p;
4653 int num = 0;
4654
4655 rettv->v_type = VAR_STRING;
4656 if (buf == NULL)
4657 return;
4658 if (argvars[1].v_type != VAR_UNKNOWN)
4659 num = get_tv_number(&argvars[1]);
4660
4661 switch (num)
4662 {
4663 case 0:
4664 if (buf->b_term->tl_job != NULL)
4665 p = buf->b_term->tl_job->jv_tty_out;
4666 else
4667 p = buf->b_term->tl_tty_out;
4668 break;
4669 case 1:
4670 if (buf->b_term->tl_job != NULL)
4671 p = buf->b_term->tl_job->jv_tty_in;
4672 else
4673 p = buf->b_term->tl_tty_in;
4674 break;
4675 default:
4676 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4677 return;
4678 }
4679 if (p != NULL)
4680 rettv->vval.v_string = vim_strsave(p);
4681}
4682
4683/*
4684 * "term_list()" function
4685 */
4686 void
4687f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4688{
4689 term_T *tp;
4690 list_T *l;
4691
4692 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4693 return;
4694
4695 l = rettv->vval.v_list;
4696 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4697 if (tp != NULL && tp->tl_buffer != NULL)
4698 if (list_append_number(l,
4699 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4700 return;
4701}
4702
4703/*
4704 * "term_scrape(buf, row)" function
4705 */
4706 void
4707f_term_scrape(typval_T *argvars, typval_T *rettv)
4708{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004709 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004710 VTermScreen *screen = NULL;
4711 VTermPos pos;
4712 list_T *l;
4713 term_T *term;
4714 char_u *p;
4715 sb_line_T *line;
4716
4717 if (rettv_list_alloc(rettv) == FAIL)
4718 return;
4719 if (buf == NULL)
4720 return;
4721 term = buf->b_term;
4722
4723 l = rettv->vval.v_list;
4724 pos.row = get_row_number(&argvars[1], term);
4725
4726 if (term->tl_vterm != NULL)
4727 {
4728 screen = vterm_obtain_screen(term->tl_vterm);
4729 p = NULL;
4730 line = NULL;
4731 }
4732 else
4733 {
4734 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4735
4736 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4737 return;
4738 p = ml_get_buf(buf, lnum + 1, FALSE);
4739 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4740 }
4741
4742 for (pos.col = 0; pos.col < term->tl_cols; )
4743 {
4744 dict_T *dcell;
4745 int width;
4746 VTermScreenCellAttrs attrs;
4747 VTermColor fg, bg;
4748 char_u rgb[8];
4749 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4750 int off = 0;
4751 int i;
4752
4753 if (screen == NULL)
4754 {
4755 cellattr_T *cellattr;
4756 int len;
4757
4758 /* vterm has finished, get the cell from scrollback */
4759 if (pos.col >= line->sb_cols)
4760 break;
4761 cellattr = line->sb_cells + pos.col;
4762 width = cellattr->width;
4763 attrs = cellattr->attrs;
4764 fg = cellattr->fg;
4765 bg = cellattr->bg;
4766 len = MB_PTR2LEN(p);
4767 mch_memmove(mbs, p, len);
4768 mbs[len] = NUL;
4769 p += len;
4770 }
4771 else
4772 {
4773 VTermScreenCell cell;
4774 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4775 break;
4776 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4777 {
4778 if (cell.chars[i] == 0)
4779 break;
4780 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4781 }
4782 mbs[off] = NUL;
4783 width = cell.width;
4784 attrs = cell.attrs;
4785 fg = cell.fg;
4786 bg = cell.bg;
4787 }
4788 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004789 if (dcell == NULL)
4790 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004791 list_append_dict(l, dcell);
4792
4793 dict_add_nr_str(dcell, "chars", 0, mbs);
4794
4795 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4796 fg.red, fg.green, fg.blue);
4797 dict_add_nr_str(dcell, "fg", 0, rgb);
4798 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4799 bg.red, bg.green, bg.blue);
4800 dict_add_nr_str(dcell, "bg", 0, rgb);
4801
4802 dict_add_nr_str(dcell, "attr",
4803 cell2attr(attrs, fg, bg), NULL);
4804 dict_add_nr_str(dcell, "width", width, NULL);
4805
4806 ++pos.col;
4807 if (width == 2)
4808 ++pos.col;
4809 }
4810}
4811
4812/*
4813 * "term_sendkeys(buf, keys)" function
4814 */
4815 void
4816f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4817{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004818 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004819 char_u *msg;
4820 term_T *term;
4821
4822 rettv->v_type = VAR_UNKNOWN;
4823 if (buf == NULL)
4824 return;
4825
4826 msg = get_tv_string_chk(&argvars[1]);
4827 if (msg == NULL)
4828 return;
4829 term = buf->b_term;
4830 if (term->tl_vterm == NULL)
4831 return;
4832
4833 while (*msg != NUL)
4834 {
4835 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004836 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004837 }
4838}
4839
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004840#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4841/*
4842 * "term_getansicolors(buf)" function
4843 */
4844 void
4845f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4846{
4847 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4848 term_T *term;
4849 VTermState *state;
4850 VTermColor color;
4851 char_u hexbuf[10];
4852 int index;
4853 list_T *list;
4854
4855 if (rettv_list_alloc(rettv) == FAIL)
4856 return;
4857
4858 if (buf == NULL)
4859 return;
4860 term = buf->b_term;
4861 if (term->tl_vterm == NULL)
4862 return;
4863
4864 list = rettv->vval.v_list;
4865 state = vterm_obtain_state(term->tl_vterm);
4866 for (index = 0; index < 16; index++)
4867 {
4868 vterm_state_get_palette_color(state, index, &color);
4869 sprintf((char *)hexbuf, "#%02x%02x%02x",
4870 color.red, color.green, color.blue);
4871 if (list_append_string(list, hexbuf, 7) == FAIL)
4872 return;
4873 }
4874}
4875
4876/*
4877 * "term_setansicolors(buf, list)" function
4878 */
4879 void
4880f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4881{
4882 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4883 term_T *term;
4884
4885 if (buf == NULL)
4886 return;
4887 term = buf->b_term;
4888 if (term->tl_vterm == NULL)
4889 return;
4890
4891 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4892 {
4893 EMSG(_(e_listreq));
4894 return;
4895 }
4896
4897 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4898 EMSG(_(e_invarg));
4899}
4900#endif
4901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004902/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004903 * "term_setrestore(buf, command)" function
4904 */
4905 void
4906f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4907{
4908#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004909 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004910 term_T *term;
4911 char_u *cmd;
4912
4913 if (buf == NULL)
4914 return;
4915 term = buf->b_term;
4916 vim_free(term->tl_command);
4917 cmd = get_tv_string_chk(&argvars[1]);
4918 if (cmd != NULL)
4919 term->tl_command = vim_strsave(cmd);
4920 else
4921 term->tl_command = NULL;
4922#endif
4923}
4924
4925/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004926 * "term_setkill(buf, how)" function
4927 */
4928 void
4929f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4930{
4931 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4932 term_T *term;
4933 char_u *how;
4934
4935 if (buf == NULL)
4936 return;
4937 term = buf->b_term;
4938 vim_free(term->tl_kill);
4939 how = get_tv_string_chk(&argvars[1]);
4940 if (how != NULL)
4941 term->tl_kill = vim_strsave(how);
4942 else
4943 term->tl_kill = NULL;
4944}
4945
4946/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004947 * "term_start(command, options)" function
4948 */
4949 void
4950f_term_start(typval_T *argvars, typval_T *rettv)
4951{
4952 jobopt_T opt;
4953 buf_T *buf;
4954
4955 init_job_options(&opt);
4956 if (argvars[1].v_type != VAR_UNKNOWN
4957 && get_job_options(&argvars[1], &opt,
4958 JO_TIMEOUT_ALL + JO_STOPONEXIT
4959 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4960 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4961 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4962 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004963 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004964 + JO2_NORESTORE + JO2_TERM_KILL
4965 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004966 return;
4967
Bram Moolenaar13568252018-03-16 20:46:58 +01004968 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004969
4970 if (buf != NULL && buf->b_term != NULL)
4971 rettv->vval.v_number = buf->b_fnum;
4972}
4973
4974/*
4975 * "term_wait" function
4976 */
4977 void
4978f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4979{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004980 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004981
4982 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004983 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004984 if (buf->b_term->tl_job == NULL)
4985 {
4986 ch_log(NULL, "term_wait(): no job to wait for");
4987 return;
4988 }
4989 if (buf->b_term->tl_job->jv_channel == NULL)
4990 /* channel is closed, nothing to do */
4991 return;
4992
4993 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004994 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004995 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4996 {
4997 /* The job is dead, keep reading channel I/O until the channel is
4998 * closed. buf->b_term may become NULL if the terminal was closed while
4999 * waiting. */
5000 ch_log(NULL, "term_wait(): waiting for channel to close");
5001 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5002 {
5003 mch_check_messages();
5004 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005005 if (!buf_valid(buf))
5006 /* If the terminal is closed when the channel is closed the
5007 * buffer disappears. */
5008 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005009 ui_delay(10L, FALSE);
5010 }
5011 mch_check_messages();
5012 parse_queued_messages();
5013 }
5014 else
5015 {
5016 long wait = 10L;
5017
5018 mch_check_messages();
5019 parse_queued_messages();
5020
5021 /* Wait for some time for any channel I/O. */
5022 if (argvars[1].v_type != VAR_UNKNOWN)
5023 wait = get_tv_number(&argvars[1]);
5024 ui_delay(wait, TRUE);
5025 mch_check_messages();
5026
5027 /* Flushing messages on channels is hopefully sufficient.
5028 * TODO: is there a better way? */
5029 parse_queued_messages();
5030 }
5031}
5032
5033/*
5034 * Called when a channel has sent all the lines to a terminal.
5035 * Send a CTRL-D to mark the end of the text.
5036 */
5037 void
5038term_send_eof(channel_T *ch)
5039{
5040 term_T *term;
5041
5042 for (term = first_term; term != NULL; term = term->tl_next)
5043 if (term->tl_job == ch->ch_job)
5044 {
5045 if (term->tl_eof_chars != NULL)
5046 {
5047 channel_send(ch, PART_IN, term->tl_eof_chars,
5048 (int)STRLEN(term->tl_eof_chars), NULL);
5049 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5050 }
5051# ifdef WIN3264
5052 else
5053 /* Default: CTRL-D */
5054 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5055# endif
5056 }
5057}
5058
5059# if defined(WIN3264) || defined(PROTO)
5060
5061/**************************************
5062 * 2. MS-Windows implementation.
5063 */
5064
5065# ifndef PROTO
5066
5067#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5068#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005069#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005070
5071void* (*winpty_config_new)(UINT64, void*);
5072void* (*winpty_open)(void*, void*);
5073void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5074BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5075void (*winpty_config_set_mouse_mode)(void*, int);
5076void (*winpty_config_set_initial_size)(void*, int, int);
5077LPCWSTR (*winpty_conin_name)(void*);
5078LPCWSTR (*winpty_conout_name)(void*);
5079LPCWSTR (*winpty_conerr_name)(void*);
5080void (*winpty_free)(void*);
5081void (*winpty_config_free)(void*);
5082void (*winpty_spawn_config_free)(void*);
5083void (*winpty_error_free)(void*);
5084LPCWSTR (*winpty_error_msg)(void*);
5085BOOL (*winpty_set_size)(void*, int, int, void*);
5086HANDLE (*winpty_agent_process)(void*);
5087
5088#define WINPTY_DLL "winpty.dll"
5089
5090static HINSTANCE hWinPtyDLL = NULL;
5091# endif
5092
5093 static int
5094dyn_winpty_init(int verbose)
5095{
5096 int i;
5097 static struct
5098 {
5099 char *name;
5100 FARPROC *ptr;
5101 } winpty_entry[] =
5102 {
5103 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5104 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5105 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5106 {"winpty_config_set_mouse_mode",
5107 (FARPROC*)&winpty_config_set_mouse_mode},
5108 {"winpty_config_set_initial_size",
5109 (FARPROC*)&winpty_config_set_initial_size},
5110 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5111 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5112 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5113 {"winpty_free", (FARPROC*)&winpty_free},
5114 {"winpty_open", (FARPROC*)&winpty_open},
5115 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5116 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5117 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5118 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5119 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5120 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5121 {NULL, NULL}
5122 };
5123
5124 /* No need to initialize twice. */
5125 if (hWinPtyDLL)
5126 return OK;
5127 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5128 * winpty.dll. */
5129 if (*p_winptydll != NUL)
5130 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5131 if (!hWinPtyDLL)
5132 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5133 if (!hWinPtyDLL)
5134 {
5135 if (verbose)
5136 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5137 : (char_u *)WINPTY_DLL);
5138 return FAIL;
5139 }
5140 for (i = 0; winpty_entry[i].name != NULL
5141 && winpty_entry[i].ptr != NULL; ++i)
5142 {
5143 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5144 winpty_entry[i].name)) == NULL)
5145 {
5146 if (verbose)
5147 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5148 return FAIL;
5149 }
5150 }
5151
5152 return OK;
5153}
5154
5155/*
5156 * Create a new terminal of "rows" by "cols" cells.
5157 * Store a reference in "term".
5158 * Return OK or FAIL.
5159 */
5160 static int
5161term_and_job_init(
5162 term_T *term,
5163 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005164 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005165 jobopt_T *opt)
5166{
5167 WCHAR *cmd_wchar = NULL;
5168 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005169 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005170 channel_T *channel = NULL;
5171 job_T *job = NULL;
5172 DWORD error;
5173 HANDLE jo = NULL;
5174 HANDLE child_process_handle;
5175 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005176 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005177 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005178 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005179 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005180
5181 if (dyn_winpty_init(TRUE) == FAIL)
5182 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005183 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5184 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005185
5186 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005187 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005188 cmd = argvar->vval.v_string;
5189 }
5190 else if (argvar->v_type == VAR_LIST)
5191 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005192 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005193 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005194 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005195 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005196 if (cmd == NULL || *cmd == NUL)
5197 {
5198 EMSG(_(e_invarg));
5199 goto failed;
5200 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005201
5202 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005203 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005204 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005205 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005206 if (opt->jo_cwd != NULL)
5207 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005208
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005209 win32_build_env(opt->jo_env, &ga_env, TRUE);
5210 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005211
5212 job = job_alloc();
5213 if (job == NULL)
5214 goto failed;
5215
5216 channel = add_channel();
5217 if (channel == NULL)
5218 goto failed;
5219
5220 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5221 if (term->tl_winpty_config == NULL)
5222 goto failed;
5223
5224 winpty_config_set_mouse_mode(term->tl_winpty_config,
5225 WINPTY_MOUSE_MODE_FORCE);
5226 winpty_config_set_initial_size(term->tl_winpty_config,
5227 term->tl_cols, term->tl_rows);
5228 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5229 if (term->tl_winpty == NULL)
5230 goto failed;
5231
5232 spawn_config = winpty_spawn_config_new(
5233 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5234 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5235 NULL,
5236 cmd_wchar,
5237 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005238 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005239 &winpty_err);
5240 if (spawn_config == NULL)
5241 goto failed;
5242
5243 channel = add_channel();
5244 if (channel == NULL)
5245 goto failed;
5246
5247 job = job_alloc();
5248 if (job == NULL)
5249 goto failed;
5250
5251 if (opt->jo_set & JO_IN_BUF)
5252 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5253
5254 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5255 &child_thread_handle, &error, &winpty_err))
5256 goto failed;
5257
5258 channel_set_pipes(channel,
5259 (sock_T)CreateFileW(
5260 winpty_conin_name(term->tl_winpty),
5261 GENERIC_WRITE, 0, NULL,
5262 OPEN_EXISTING, 0, NULL),
5263 (sock_T)CreateFileW(
5264 winpty_conout_name(term->tl_winpty),
5265 GENERIC_READ, 0, NULL,
5266 OPEN_EXISTING, 0, NULL),
5267 (sock_T)CreateFileW(
5268 winpty_conerr_name(term->tl_winpty),
5269 GENERIC_READ, 0, NULL,
5270 OPEN_EXISTING, 0, NULL));
5271
5272 /* Write lines with CR instead of NL. */
5273 channel->ch_write_text_mode = TRUE;
5274
5275 jo = CreateJobObject(NULL, NULL);
5276 if (jo == NULL)
5277 goto failed;
5278
5279 if (!AssignProcessToJobObject(jo, child_process_handle))
5280 {
5281 /* Failed, switch the way to terminate process with TerminateProcess. */
5282 CloseHandle(jo);
5283 jo = NULL;
5284 }
5285
5286 winpty_spawn_config_free(spawn_config);
5287 vim_free(cmd_wchar);
5288 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005289 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005290
5291 create_vterm(term, term->tl_rows, term->tl_cols);
5292
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005293#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5294 if (opt->jo_set2 & JO2_ANSI_COLORS)
5295 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5296 else
5297 init_vterm_ansi_colors(term->tl_vterm);
5298#endif
5299
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005300 channel_set_job(channel, job, opt);
5301 job_set_options(job, opt);
5302
5303 job->jv_channel = channel;
5304 job->jv_proc_info.hProcess = child_process_handle;
5305 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5306 job->jv_job_object = jo;
5307 job->jv_status = JOB_STARTED;
5308 job->jv_tty_in = utf16_to_enc(
5309 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5310 job->jv_tty_out = utf16_to_enc(
5311 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5312 ++job->jv_refcount;
5313 term->tl_job = job;
5314
5315 return OK;
5316
5317failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005318 ga_clear(&ga_cmd);
5319 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005320 vim_free(cmd_wchar);
5321 vim_free(cwd_wchar);
5322 if (spawn_config != NULL)
5323 winpty_spawn_config_free(spawn_config);
5324 if (channel != NULL)
5325 channel_clear(channel);
5326 if (job != NULL)
5327 {
5328 job->jv_channel = NULL;
5329 job_cleanup(job);
5330 }
5331 term->tl_job = NULL;
5332 if (jo != NULL)
5333 CloseHandle(jo);
5334 if (term->tl_winpty != NULL)
5335 winpty_free(term->tl_winpty);
5336 term->tl_winpty = NULL;
5337 if (term->tl_winpty_config != NULL)
5338 winpty_config_free(term->tl_winpty_config);
5339 term->tl_winpty_config = NULL;
5340 if (winpty_err != NULL)
5341 {
5342 char_u *msg = utf16_to_enc(
5343 (short_u *)winpty_error_msg(winpty_err), NULL);
5344
5345 EMSG(msg);
5346 winpty_error_free(winpty_err);
5347 }
5348 return FAIL;
5349}
5350
5351 static int
5352create_pty_only(term_T *term, jobopt_T *options)
5353{
5354 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5355 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5356 char in_name[80], out_name[80];
5357 channel_T *channel = NULL;
5358
5359 create_vterm(term, term->tl_rows, term->tl_cols);
5360
5361 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5362 GetCurrentProcessId(),
5363 curbuf->b_fnum);
5364 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5365 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5366 PIPE_UNLIMITED_INSTANCES,
5367 0, 0, NMPWAIT_NOWAIT, NULL);
5368 if (hPipeIn == INVALID_HANDLE_VALUE)
5369 goto failed;
5370
5371 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5372 GetCurrentProcessId(),
5373 curbuf->b_fnum);
5374 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5375 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5376 PIPE_UNLIMITED_INSTANCES,
5377 0, 0, 0, NULL);
5378 if (hPipeOut == INVALID_HANDLE_VALUE)
5379 goto failed;
5380
5381 ConnectNamedPipe(hPipeIn, NULL);
5382 ConnectNamedPipe(hPipeOut, NULL);
5383
5384 term->tl_job = job_alloc();
5385 if (term->tl_job == NULL)
5386 goto failed;
5387 ++term->tl_job->jv_refcount;
5388
5389 /* behave like the job is already finished */
5390 term->tl_job->jv_status = JOB_FINISHED;
5391
5392 channel = add_channel();
5393 if (channel == NULL)
5394 goto failed;
5395 term->tl_job->jv_channel = channel;
5396 channel->ch_keep_open = TRUE;
5397 channel->ch_named_pipe = TRUE;
5398
5399 channel_set_pipes(channel,
5400 (sock_T)hPipeIn,
5401 (sock_T)hPipeOut,
5402 (sock_T)hPipeOut);
5403 channel_set_job(channel, term->tl_job, options);
5404 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5405 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5406
5407 return OK;
5408
5409failed:
5410 if (hPipeIn != NULL)
5411 CloseHandle(hPipeIn);
5412 if (hPipeOut != NULL)
5413 CloseHandle(hPipeOut);
5414 return FAIL;
5415}
5416
5417/*
5418 * Free the terminal emulator part of "term".
5419 */
5420 static void
5421term_free_vterm(term_T *term)
5422{
5423 if (term->tl_winpty != NULL)
5424 winpty_free(term->tl_winpty);
5425 term->tl_winpty = NULL;
5426 if (term->tl_winpty_config != NULL)
5427 winpty_config_free(term->tl_winpty_config);
5428 term->tl_winpty_config = NULL;
5429 if (term->tl_vterm != NULL)
5430 vterm_free(term->tl_vterm);
5431 term->tl_vterm = NULL;
5432}
5433
5434/*
5435 * Request size to terminal.
5436 */
5437 static void
5438term_report_winsize(term_T *term, int rows, int cols)
5439{
5440 if (term->tl_winpty)
5441 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5442}
5443
5444 int
5445terminal_enabled(void)
5446{
5447 return dyn_winpty_init(FALSE) == OK;
5448}
5449
5450# else
5451
5452/**************************************
5453 * 3. Unix-like implementation.
5454 */
5455
5456/*
5457 * Create a new terminal of "rows" by "cols" cells.
5458 * Start job for "cmd".
5459 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005460 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005461 * Return OK or FAIL.
5462 */
5463 static int
5464term_and_job_init(
5465 term_T *term,
5466 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005467 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005468 jobopt_T *opt)
5469{
5470 create_vterm(term, term->tl_rows, term->tl_cols);
5471
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005472#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5473 if (opt->jo_set2 & JO2_ANSI_COLORS)
5474 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5475 else
5476 init_vterm_ansi_colors(term->tl_vterm);
5477#endif
5478
Bram Moolenaar13568252018-03-16 20:46:58 +01005479 /* This may change a string in "argvar". */
5480 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005481 if (term->tl_job != NULL)
5482 ++term->tl_job->jv_refcount;
5483
5484 return term->tl_job != NULL
5485 && term->tl_job->jv_channel != NULL
5486 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5487}
5488
5489 static int
5490create_pty_only(term_T *term, jobopt_T *opt)
5491{
5492 create_vterm(term, term->tl_rows, term->tl_cols);
5493
5494 term->tl_job = job_alloc();
5495 if (term->tl_job == NULL)
5496 return FAIL;
5497 ++term->tl_job->jv_refcount;
5498
5499 /* behave like the job is already finished */
5500 term->tl_job->jv_status = JOB_FINISHED;
5501
5502 return mch_create_pty_channel(term->tl_job, opt);
5503}
5504
5505/*
5506 * Free the terminal emulator part of "term".
5507 */
5508 static void
5509term_free_vterm(term_T *term)
5510{
5511 if (term->tl_vterm != NULL)
5512 vterm_free(term->tl_vterm);
5513 term->tl_vterm = NULL;
5514}
5515
5516/*
5517 * Request size to terminal.
5518 */
5519 static void
5520term_report_winsize(term_T *term, int rows, int cols)
5521{
5522 /* Use an ioctl() to report the new window size to the job. */
5523 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5524 {
5525 int fd = -1;
5526 int part;
5527
5528 for (part = PART_OUT; part < PART_COUNT; ++part)
5529 {
5530 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5531 if (isatty(fd))
5532 break;
5533 }
5534 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5535 mch_signal_job(term->tl_job, (char_u *)"winch");
5536 }
5537}
5538
5539# endif
5540
5541#endif /* FEAT_TERMINAL */