blob: 87530af2eff46f143b7e3eb847a148208b9d16c9 [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.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
54/* This is VTermScreenCell without the characters, thus much smaller. */
55typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
63 int sb_cols; /* can differ per line */
64 cellattr_T *sb_cells; /* allocated */
65 cellattr_T sb_fill_attr; /* for short line */
66} sb_line_T;
67
68/* typedef term_T in structs.h */
69struct terminal_S {
70 term_T *tl_next;
71
72 VTerm *tl_vterm;
73 job_T *tl_job;
74 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010075#if defined(FEAT_GUI)
76 int tl_system; /* when non-zero used for :!cmd output */
77 int tl_toprow; /* row with first line of system terminal */
78#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020079
80 /* Set when setting the size of a vterm, reset after redrawing. */
81 int tl_vterm_size_changed;
82
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020083 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
84 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +020085 int tl_channel_recently_closed; // still need to handle tl_finish
86
Bram Moolenaar1dd98332018-03-16 22:54:53 +010087 int tl_finish;
88#define TL_FINISH_UNSET NUL
89#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
90#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
91#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020092 char_u *tl_opencmd;
93 char_u *tl_eof_chars;
94
95#ifdef WIN3264
96 void *tl_winpty_config;
97 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +020098
99 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200100#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100101#if defined(FEAT_SESSION)
102 char_u *tl_command;
103#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100104 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200105
106 /* last known vterm size */
107 int tl_rows;
108 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200109
110 char_u *tl_title; /* NULL or allocated */
111 char_u *tl_status_text; /* NULL or allocated */
112
113 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200114 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200115 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200116 int tl_dirty_snapshot; /* text updated after making snapshot */
117#ifdef FEAT_TIMERS
118 int tl_timer_set;
119 proftime_T tl_timer_due;
120#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200121 int tl_postponed_scroll; /* to be scrolled up */
122
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123 garray_T tl_scrollback;
124 int tl_scrollback_scrolled;
125 cellattr_T tl_default_color;
126
Bram Moolenaard96ff162018-02-18 22:13:29 +0100127 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
128 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130 VTermPos tl_cursor_pos;
131 int tl_cursor_visible;
132 int tl_cursor_blink;
133 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
134 char_u *tl_cursor_color; /* NULL or allocated */
135
136 int tl_using_altscreen;
137};
138
139#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
140#define TMODE_LOOP 2 /* CTRL-W N used */
141
142/*
143 * List of all active terminals.
144 */
145static term_T *first_term = NULL;
146
147/* Terminal active in terminal_loop(). */
148static term_T *in_terminal_loop = NULL;
149
150#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
151#define KEY_BUF_LEN 200
152
153/*
154 * Functions with separate implementation for MS-Windows and Unix-like systems.
155 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200156static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200157static int create_pty_only(term_T *term, jobopt_T *opt);
158static void term_report_winsize(term_T *term, int rows, int cols);
159static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100160#ifdef FEAT_GUI
161static void update_system_term(term_T *term);
162#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200163
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100164/* The character that we know (or assume) that the terminal expects for the
165 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200166static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100168/* "Terminal" highlight group colors. */
169static int term_default_cterm_fg = -1;
170static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200171
Bram Moolenaard317b382018-02-08 22:33:31 +0100172/* Store the last set and the desired cursor properties, so that we only update
173 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200174static char_u *last_set_cursor_color = NULL;
175static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100176static int last_set_cursor_shape = -1;
177static int desired_cursor_shape = -1;
178static int last_set_cursor_blink = -1;
179static int desired_cursor_blink = -1;
180
181
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182/**************************************
183 * 1. Generic code for all systems.
184 */
185
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200186 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200187cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
188{
189 if (lhs_color != NULL && rhs_color != NULL)
190 return STRCMP(lhs_color, rhs_color) == 0;
191 return lhs_color == NULL && rhs_color == NULL;
192}
193
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200194 static void
195cursor_color_copy(char_u **to_color, char_u *from_color)
196{
197 // Avoid a free & alloc if the value is already right.
198 if (cursor_color_equal(*to_color, from_color))
199 return;
200 vim_free(*to_color);
201 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
202}
203
204 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200205cursor_color_get(char_u *color)
206{
207 return (color == NULL) ? (char_u *)"" : color;
208}
209
210
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200211/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200212 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200213 * current window.
214 * Sets "rows" and/or "cols" to zero when it should follow the window size.
215 * Return TRUE if the size is the minimum size: "24*80".
216 */
217 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200218parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200219{
220 int minsize = FALSE;
221
222 *rows = 0;
223 *cols = 0;
224
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200225 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200226 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200227 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200228
229 /* Syntax of value was already checked when it's set. */
230 if (p == NULL)
231 {
232 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200233 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200234 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200235 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200236 *cols = atoi((char *)p + 1);
237 }
238 return minsize;
239}
240
241/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200242 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243 */
244 static void
245set_term_and_win_size(term_T *term)
246{
Bram Moolenaar13568252018-03-16 20:46:58 +0100247#ifdef FEAT_GUI
248 if (term->tl_system)
249 {
250 /* Use the whole screen for the system command. However, it will start
251 * at the command line and scroll up as needed, using tl_toprow. */
252 term->tl_rows = Rows;
253 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200254 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100255 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100256#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200257 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200258 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200259 if (term->tl_rows != 0)
260 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
261 if (term->tl_cols != 0)
262 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200263 }
264 if (term->tl_rows == 0)
265 term->tl_rows = curwin->w_height;
266 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200267 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268 if (term->tl_cols == 0)
269 term->tl_cols = curwin->w_width;
270 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200271 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200272}
273
274/*
275 * Initialize job options for a terminal job.
276 * Caller may overrule some of them.
277 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100278 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200279init_job_options(jobopt_T *opt)
280{
281 clear_job_options(opt);
282
283 opt->jo_mode = MODE_RAW;
284 opt->jo_out_mode = MODE_RAW;
285 opt->jo_err_mode = MODE_RAW;
286 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
287}
288
289/*
290 * Set job options mandatory for a terminal job.
291 */
292 static void
293setup_job_options(jobopt_T *opt, int rows, int cols)
294{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200295#ifndef WIN3264
296 /* Win32: Redirecting the job output won't work, thus always connect stdout
297 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200298 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200299#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 {
301 /* Connect stdout to the terminal. */
302 opt->jo_io[PART_OUT] = JIO_BUFFER;
303 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
304 opt->jo_modifiable[PART_OUT] = 0;
305 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
306 }
307
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200308#ifndef WIN3264
309 /* Win32: Redirecting the job output won't work, thus always connect stderr
310 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200312#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200313 {
314 /* Connect stderr to the terminal. */
315 opt->jo_io[PART_ERR] = JIO_BUFFER;
316 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
317 opt->jo_modifiable[PART_ERR] = 0;
318 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
319 }
320
321 opt->jo_pty = TRUE;
322 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
323 opt->jo_term_rows = rows;
324 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
325 opt->jo_term_cols = cols;
326}
327
328/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100329 * Close a terminal buffer (and its window). Used when creating the terminal
330 * fails.
331 */
332 static void
333term_close_buffer(buf_T *buf, buf_T *old_curbuf)
334{
335 free_terminal(buf);
336 if (old_curbuf != NULL)
337 {
338 --curbuf->b_nwindows;
339 curbuf = old_curbuf;
340 curwin->w_buffer = curbuf;
341 ++curbuf->b_nwindows;
342 }
343
344 /* Wiping out the buffer will also close the window and call
345 * free_terminal(). */
346 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
347}
348
349/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200350 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100351 * Use either "argvar" or "argv", the other must be NULL.
352 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
353 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200354 * Returns NULL when failed.
355 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100356 buf_T *
357term_start(
358 typval_T *argvar,
359 char **argv,
360 jobopt_T *opt,
361 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200362{
363 exarg_T split_ea;
364 win_T *old_curwin = curwin;
365 term_T *term;
366 buf_T *old_curbuf = NULL;
367 int res;
368 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100369 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200370 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200371
372 if (check_restricted() || check_secure())
373 return NULL;
374
375 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
376 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
377 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
378 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
379 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100380 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200381 return NULL;
382 }
383
384 term = (term_T *)alloc_clear(sizeof(term_T));
385 if (term == NULL)
386 return NULL;
387 term->tl_dirty_row_end = MAX_ROW;
388 term->tl_cursor_visible = TRUE;
389 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
390 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100391#ifdef FEAT_GUI
392 term->tl_system = (flags & TERM_START_SYSTEM);
393#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200394 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
395
396 vim_memset(&split_ea, 0, sizeof(split_ea));
397 if (opt->jo_curwin)
398 {
399 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100400 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200401 {
402 no_write_message();
403 vim_free(term);
404 return NULL;
405 }
406 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100407 ECMD_HIDE
408 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
409 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410 {
411 vim_free(term);
412 return NULL;
413 }
414 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100415 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200416 {
417 buf_T *buf;
418
419 /* Create a new buffer without a window. Make it the current buffer for
420 * a moment to be able to do the initialisations. */
421 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
422 BLN_NEW | BLN_LISTED);
423 if (buf == NULL || ml_open(buf) == FAIL)
424 {
425 vim_free(term);
426 return NULL;
427 }
428 old_curbuf = curbuf;
429 --curbuf->b_nwindows;
430 curbuf = buf;
431 curwin->w_buffer = buf;
432 ++curbuf->b_nwindows;
433 }
434 else
435 {
436 /* Open a new window or tab. */
437 split_ea.cmdidx = CMD_new;
438 split_ea.cmd = (char_u *)"new";
439 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100440 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200441 {
442 split_ea.line2 = opt->jo_term_rows;
443 split_ea.addr_count = 1;
444 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100445 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200446 {
447 split_ea.line2 = opt->jo_term_cols;
448 split_ea.addr_count = 1;
449 }
450
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100451 if (vertical)
452 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200453 ex_splitview(&split_ea);
454 if (curwin == old_curwin)
455 {
456 /* split failed */
457 vim_free(term);
458 return NULL;
459 }
460 }
461 term->tl_buffer = curbuf;
462 curbuf->b_term = term;
463
464 if (!opt->jo_hidden)
465 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100466 /* Only one size was taken care of with :new, do the other one. With
467 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100468 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100470 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200471 win_setwidth(opt->jo_term_cols);
472 }
473
474 /* Link the new terminal in the list of active terminals. */
475 term->tl_next = first_term;
476 first_term = term;
477
478 if (opt->jo_term_name != NULL)
479 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100480 else if (argv != NULL)
481 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 else
483 {
484 int i;
485 size_t len;
486 char_u *cmd, *p;
487
488 if (argvar->v_type == VAR_STRING)
489 {
490 cmd = argvar->vval.v_string;
491 if (cmd == NULL)
492 cmd = (char_u *)"";
493 else if (STRCMP(cmd, "NONE") == 0)
494 cmd = (char_u *)"pty";
495 }
496 else if (argvar->v_type != VAR_LIST
497 || argvar->vval.v_list == NULL
498 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100499 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
501 cmd = (char_u*)"";
502
503 len = STRLEN(cmd) + 10;
504 p = alloc((int)len);
505
506 for (i = 0; p != NULL; ++i)
507 {
508 /* Prepend a ! to the command name to avoid the buffer name equals
509 * the executable, otherwise ":w!" would overwrite it. */
510 if (i == 0)
511 vim_snprintf((char *)p, len, "!%s", cmd);
512 else
513 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
514 if (buflist_findname(p) == NULL)
515 {
516 vim_free(curbuf->b_ffname);
517 curbuf->b_ffname = p;
518 break;
519 }
520 }
521 }
522 curbuf->b_fname = curbuf->b_ffname;
523
524 if (opt->jo_term_opencmd != NULL)
525 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
526
527 if (opt->jo_eof_chars != NULL)
528 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
529
530 set_string_option_direct((char_u *)"buftype", -1,
531 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200532 // Avoid that 'buftype' is reset when this buffer is entered.
533 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200534
535 /* Mark the buffer as not modifiable. It can only be made modifiable after
536 * the job finished. */
537 curbuf->b_p_ma = FALSE;
538
539 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200540#ifdef WIN3264
541 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
542#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 setup_job_options(opt, term->tl_rows, term->tl_cols);
544
Bram Moolenaar13568252018-03-16 20:46:58 +0100545 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100546 return curbuf;
547
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100548#if defined(FEAT_SESSION)
549 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100550 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100551 {
552 term->tl_command = vim_strsave((char_u *)"NONE");
553 }
554 else if (argvar->v_type == VAR_STRING)
555 {
556 char_u *cmd = argvar->vval.v_string;
557
558 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
559 term->tl_command = vim_strsave(cmd);
560 }
561 else if (argvar->v_type == VAR_LIST
562 && argvar->vval.v_list != NULL
563 && argvar->vval.v_list->lv_len > 0)
564 {
565 garray_T ga;
566 listitem_T *item;
567
568 ga_init2(&ga, 1, 100);
569 for (item = argvar->vval.v_list->lv_first;
570 item != NULL; item = item->li_next)
571 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100572 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100573 char_u *p;
574
575 if (s == NULL)
576 break;
577 p = vim_strsave_fnameescape(s, FALSE);
578 if (p == NULL)
579 break;
580 ga_concat(&ga, p);
581 vim_free(p);
582 ga_append(&ga, ' ');
583 }
584 if (item == NULL)
585 {
586 ga_append(&ga, NUL);
587 term->tl_command = ga.ga_data;
588 }
589 else
590 ga_clear(&ga);
591 }
592#endif
593
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100594 if (opt->jo_term_kill != NULL)
595 {
596 char_u *p = skiptowhite(opt->jo_term_kill);
597
598 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
599 }
600
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100602 if (argv == NULL
603 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 && argvar->vval.v_string != NULL
605 && STRCMP(argvar->vval.v_string, "NONE") == 0)
606 res = create_pty_only(term, opt);
607 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200608 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200609
610 newbuf = curbuf;
611 if (res == OK)
612 {
613 /* Get and remember the size we ended up with. Update the pty. */
614 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
615 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100616#ifdef FEAT_GUI
617 if (term->tl_system)
618 {
619 /* display first line below typed command */
620 term->tl_toprow = msg_row + 1;
621 term->tl_dirty_row_end = 0;
622 }
623#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624
625 /* Make sure we don't get stuck on sending keys to the job, it leads to
626 * a deadlock if the job is waiting for Vim to read. */
627 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
628
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200629 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200630 {
631 --curbuf->b_nwindows;
632 curbuf = old_curbuf;
633 curwin->w_buffer = curbuf;
634 ++curbuf->b_nwindows;
635 }
636 }
637 else
638 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100639 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200640 return NULL;
641 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100642
Bram Moolenaar13568252018-03-16 20:46:58 +0100643 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 return newbuf;
645}
646
647/*
648 * ":terminal": open a terminal window and execute a job in it.
649 */
650 void
651ex_terminal(exarg_T *eap)
652{
653 typval_T argvar[2];
654 jobopt_T opt;
655 char_u *cmd;
656 char_u *tofree = NULL;
657
658 init_job_options(&opt);
659
660 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100661 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200662 {
663 char_u *p, *ep;
664
665 cmd += 2;
666 p = skiptowhite(cmd);
667 ep = vim_strchr(cmd, '=');
668 if (ep != NULL && ep < p)
669 p = ep;
670
671 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
672 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100673 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
674 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200675 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
676 opt.jo_term_finish = 'o';
677 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
678 opt.jo_curwin = 1;
679 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
680 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
682 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100683 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
684 && ep != NULL)
685 {
686 opt.jo_set2 |= JO2_TERM_KILL;
687 opt.jo_term_kill = ep + 1;
688 p = skiptowhite(cmd);
689 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200690 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
691 && ep != NULL && isdigit(ep[1]))
692 {
693 opt.jo_set2 |= JO2_TERM_ROWS;
694 opt.jo_term_rows = atoi((char *)ep + 1);
695 p = skiptowhite(cmd);
696 }
697 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
698 && ep != NULL && isdigit(ep[1]))
699 {
700 opt.jo_set2 |= JO2_TERM_COLS;
701 opt.jo_term_cols = atoi((char *)ep + 1);
702 p = skiptowhite(cmd);
703 }
704 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
705 && ep != NULL)
706 {
707 char_u *buf = NULL;
708 char_u *keys;
709
710 p = skiptowhite(cmd);
711 *p = NUL;
712 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
713 opt.jo_set2 |= JO2_EOF_CHARS;
714 opt.jo_eof_chars = vim_strsave(keys);
715 vim_free(buf);
716 *p = ' ';
717 }
718 else
719 {
720 if (*p)
721 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100722 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100723 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 }
725 cmd = skipwhite(p);
726 }
727 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100728 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200729 /* Make a copy of 'shell', an autocommand may change the option. */
730 tofree = cmd = vim_strsave(p_sh);
731
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100732 /* default to close when the shell exits */
733 if (opt.jo_term_finish == NUL)
734 opt.jo_term_finish = 'c';
735 }
736
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 if (eap->addr_count > 0)
738 {
739 /* Write lines from current buffer to the job. */
740 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
741 opt.jo_io[PART_IN] = JIO_BUFFER;
742 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
743 opt.jo_in_top = eap->line1;
744 opt.jo_in_bot = eap->line2;
745 }
746
747 argvar[0].v_type = VAR_STRING;
748 argvar[0].vval.v_string = cmd;
749 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100750 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200751 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100752
753theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200754 vim_free(opt.jo_eof_chars);
755}
756
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100757#if defined(FEAT_SESSION) || defined(PROTO)
758/*
759 * Write a :terminal command to the session file to restore the terminal in
760 * window "wp".
761 * Return FAIL if writing fails.
762 */
763 int
764term_write_session(FILE *fd, win_T *wp)
765{
766 term_T *term = wp->w_buffer->b_term;
767
768 /* Create the terminal and run the command. This is not without
769 * risk, but let's assume the user only creates a session when this
770 * will be OK. */
771 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
772 term->tl_cols, term->tl_rows) < 0)
773 return FAIL;
774 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
775 return FAIL;
776
777 return put_eol(fd);
778}
779
780/*
781 * Return TRUE if "buf" has a terminal that should be restored.
782 */
783 int
784term_should_restore(buf_T *buf)
785{
786 term_T *term = buf->b_term;
787
788 return term != NULL && (term->tl_command == NULL
789 || STRCMP(term->tl_command, "NONE") != 0);
790}
791#endif
792
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200793/*
794 * Free the scrollback buffer for "term".
795 */
796 static void
797free_scrollback(term_T *term)
798{
799 int i;
800
801 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
802 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
803 ga_clear(&term->tl_scrollback);
804}
805
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100806
807// Terminals that need to be freed soon.
808term_T *terminals_to_free = NULL;
809
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810/*
811 * Free a terminal and everything it refers to.
812 * Kills the job if there is one.
813 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100814 * The actual terminal structure is freed later in free_unused_terminals(),
815 * because callbacks may wipe out a buffer while the terminal is still
816 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 */
818 void
819free_terminal(buf_T *buf)
820{
821 term_T *term = buf->b_term;
822 term_T *tp;
823
824 if (term == NULL)
825 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100826
827 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 if (first_term == term)
829 first_term = term->tl_next;
830 else
831 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
832 if (tp->tl_next == term)
833 {
834 tp->tl_next = term->tl_next;
835 break;
836 }
837
838 if (term->tl_job != NULL)
839 {
840 if (term->tl_job->jv_status != JOB_ENDED
841 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100842 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200843 job_stop(term->tl_job, NULL, "kill");
844 job_unref(term->tl_job);
845 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100846 term->tl_next = terminals_to_free;
847 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200848
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200849 buf->b_term = NULL;
850 if (in_terminal_loop == term)
851 in_terminal_loop = NULL;
852}
853
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100854 void
855free_unused_terminals()
856{
857 while (terminals_to_free != NULL)
858 {
859 term_T *term = terminals_to_free;
860
861 terminals_to_free = term->tl_next;
862
863 free_scrollback(term);
864
865 term_free_vterm(term);
866 vim_free(term->tl_title);
867#ifdef FEAT_SESSION
868 vim_free(term->tl_command);
869#endif
870 vim_free(term->tl_kill);
871 vim_free(term->tl_status_text);
872 vim_free(term->tl_opencmd);
873 vim_free(term->tl_eof_chars);
874#ifdef WIN3264
875 if (term->tl_out_fd != NULL)
876 fclose(term->tl_out_fd);
877#endif
878 vim_free(term->tl_cursor_color);
879 vim_free(term);
880 }
881}
882
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200883/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100884 * Get the part that is connected to the tty. Normally this is PART_IN, but
885 * when writing buffer lines to the job it can be another. This makes it
886 * possible to do "1,5term vim -".
887 */
888 static ch_part_T
889get_tty_part(term_T *term)
890{
891#ifdef UNIX
892 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
893 int i;
894
895 for (i = 0; i < 3; ++i)
896 {
897 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
898
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100899 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100900 return parts[i];
901 }
902#endif
903 return PART_IN;
904}
905
906/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200907 * Write job output "msg[len]" to the vterm.
908 */
909 static void
910term_write_job_output(term_T *term, char_u *msg, size_t len)
911{
912 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100913 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200914
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100915 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100917 /* flush vterm buffer when vterm responded to control sequence */
918 if (prevlen != vterm_output_get_buffer_current(vterm))
919 {
920 char buf[KEY_BUF_LEN];
921 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
922
923 if (curlen > 0)
924 channel_send(term->tl_job->jv_channel, get_tty_part(term),
925 (char_u *)buf, (int)curlen, NULL);
926 }
927
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200928 /* this invokes the damage callbacks */
929 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
930}
931
932 static void
933update_cursor(term_T *term, int redraw)
934{
935 if (term->tl_normal_mode)
936 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100937#ifdef FEAT_GUI
938 if (term->tl_system)
939 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
940 term->tl_cursor_pos.col);
941 else
942#endif
943 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944 if (redraw)
945 {
946 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
947 cursor_on();
948 out_flush();
949#ifdef FEAT_GUI
950 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100951 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200952 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100953 gui_mch_flush();
954 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200955#endif
956 }
957}
958
959/*
960 * Invoked when "msg" output from a job was received. Write it to the terminal
961 * of "buffer".
962 */
963 void
964write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
965{
966 size_t len = STRLEN(msg);
967 term_T *term = buffer->b_term;
968
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200969#ifdef WIN3264
970 /* Win32: Cannot redirect output of the job, intercept it here and write to
971 * the file. */
972 if (term->tl_out_fd != NULL)
973 {
974 ch_log(channel, "Writing %d bytes to output file", (int)len);
975 fwrite(msg, len, 1, term->tl_out_fd);
976 return;
977 }
978#endif
979
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200980 if (term->tl_vterm == NULL)
981 {
982 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
983 return;
984 }
985 ch_log(channel, "writing %d bytes to terminal", (int)len);
986 term_write_job_output(term, msg, len);
987
Bram Moolenaar13568252018-03-16 20:46:58 +0100988#ifdef FEAT_GUI
989 if (term->tl_system)
990 {
991 /* show system output, scrolling up the screen as needed */
992 update_system_term(term);
993 update_cursor(term, TRUE);
994 }
995 else
996#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200997 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
998 * contents, thus no screen update is needed. */
999 if (!term->tl_normal_mode)
1000 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001001 // Don't use update_screen() when editing the command line, it gets
1002 // cleared.
1003 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001004 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001005 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001006 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001007 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001008 /* update_screen() can be slow, check the terminal wasn't closed
1009 * already */
1010 if (buffer == curbuf && curbuf->b_term != NULL)
1011 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001012 }
1013 else
1014 redraw_after_callback(TRUE);
1015 }
1016}
1017
1018/*
1019 * Send a mouse position and click to the vterm
1020 */
1021 static int
1022term_send_mouse(VTerm *vterm, int button, int pressed)
1023{
1024 VTermModifier mod = VTERM_MOD_NONE;
1025
1026 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001027 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001028 if (button != 0)
1029 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001030 return TRUE;
1031}
1032
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001033static int enter_mouse_col = -1;
1034static int enter_mouse_row = -1;
1035
1036/*
1037 * Handle a mouse click, drag or release.
1038 * Return TRUE when a mouse event is sent to the terminal.
1039 */
1040 static int
1041term_mouse_click(VTerm *vterm, int key)
1042{
1043#if defined(FEAT_CLIPBOARD)
1044 /* For modeless selection mouse drag and release events are ignored, unless
1045 * they are preceded with a mouse down event */
1046 static int ignore_drag_release = TRUE;
1047 VTermMouseState mouse_state;
1048
1049 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1050 if (mouse_state.flags == 0)
1051 {
1052 /* Terminal is not using the mouse, use modeless selection. */
1053 switch (key)
1054 {
1055 case K_LEFTDRAG:
1056 case K_LEFTRELEASE:
1057 case K_RIGHTDRAG:
1058 case K_RIGHTRELEASE:
1059 /* Ignore drag and release events when the button-down wasn't
1060 * seen before. */
1061 if (ignore_drag_release)
1062 {
1063 int save_mouse_col, save_mouse_row;
1064
1065 if (enter_mouse_col < 0)
1066 break;
1067
1068 /* mouse click in the window gave us focus, handle that
1069 * click now */
1070 save_mouse_col = mouse_col;
1071 save_mouse_row = mouse_row;
1072 mouse_col = enter_mouse_col;
1073 mouse_row = enter_mouse_row;
1074 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1075 mouse_col = save_mouse_col;
1076 mouse_row = save_mouse_row;
1077 }
1078 /* FALLTHROUGH */
1079 case K_LEFTMOUSE:
1080 case K_RIGHTMOUSE:
1081 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1082 ignore_drag_release = TRUE;
1083 else
1084 ignore_drag_release = FALSE;
1085 /* Should we call mouse_has() here? */
1086 if (clip_star.available)
1087 {
1088 int button, is_click, is_drag;
1089
1090 button = get_mouse_button(KEY2TERMCAP1(key),
1091 &is_click, &is_drag);
1092 if (mouse_model_popup() && button == MOUSE_LEFT
1093 && (mod_mask & MOD_MASK_SHIFT))
1094 {
1095 /* Translate shift-left to right button. */
1096 button = MOUSE_RIGHT;
1097 mod_mask &= ~MOD_MASK_SHIFT;
1098 }
1099 clip_modeless(button, is_click, is_drag);
1100 }
1101 break;
1102
1103 case K_MIDDLEMOUSE:
1104 if (clip_star.available)
1105 insert_reg('*', TRUE);
1106 break;
1107 }
1108 enter_mouse_col = -1;
1109 return FALSE;
1110 }
1111#endif
1112 enter_mouse_col = -1;
1113
1114 switch (key)
1115 {
1116 case K_LEFTMOUSE:
1117 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1118 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1119 case K_LEFTRELEASE:
1120 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1121 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1122 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1123 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1124 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1125 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1126 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1127 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1128 }
1129 return TRUE;
1130}
1131
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001132/*
1133 * Convert typed key "c" into bytes to send to the job.
1134 * Return the number of bytes in "buf".
1135 */
1136 static int
1137term_convert_key(term_T *term, int c, char *buf)
1138{
1139 VTerm *vterm = term->tl_vterm;
1140 VTermKey key = VTERM_KEY_NONE;
1141 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001142 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001143
1144 switch (c)
1145 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001146 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148 /* don't use VTERM_KEY_BACKSPACE, it always
1149 * becomes 0x7f DEL */
1150 case K_BS: c = term_backspace_char; break;
1151
1152 case ESC: key = VTERM_KEY_ESCAPE; break;
1153 case K_DEL: key = VTERM_KEY_DEL; break;
1154 case K_DOWN: key = VTERM_KEY_DOWN; break;
1155 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1156 key = VTERM_KEY_DOWN; break;
1157 case K_END: key = VTERM_KEY_END; break;
1158 case K_S_END: mod = VTERM_MOD_SHIFT;
1159 key = VTERM_KEY_END; break;
1160 case K_C_END: mod = VTERM_MOD_CTRL;
1161 key = VTERM_KEY_END; break;
1162 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1163 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1164 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1165 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1166 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1167 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1168 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1169 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1170 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1171 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1172 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1173 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1174 case K_HOME: key = VTERM_KEY_HOME; break;
1175 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1176 key = VTERM_KEY_HOME; break;
1177 case K_C_HOME: mod = VTERM_MOD_CTRL;
1178 key = VTERM_KEY_HOME; break;
1179 case K_INS: key = VTERM_KEY_INS; break;
1180 case K_K0: key = VTERM_KEY_KP_0; break;
1181 case K_K1: key = VTERM_KEY_KP_1; break;
1182 case K_K2: key = VTERM_KEY_KP_2; break;
1183 case K_K3: key = VTERM_KEY_KP_3; break;
1184 case K_K4: key = VTERM_KEY_KP_4; break;
1185 case K_K5: key = VTERM_KEY_KP_5; break;
1186 case K_K6: key = VTERM_KEY_KP_6; break;
1187 case K_K7: key = VTERM_KEY_KP_7; break;
1188 case K_K8: key = VTERM_KEY_KP_8; break;
1189 case K_K9: key = VTERM_KEY_KP_9; break;
1190 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1191 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1192 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1193 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1194 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1195 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1196 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1197 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1198 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1199 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1200 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1201 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1202 case K_LEFT: key = VTERM_KEY_LEFT; break;
1203 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1204 key = VTERM_KEY_LEFT; break;
1205 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1206 key = VTERM_KEY_LEFT; break;
1207 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1208 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1209 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1210 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1211 key = VTERM_KEY_RIGHT; break;
1212 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1213 key = VTERM_KEY_RIGHT; break;
1214 case K_UP: key = VTERM_KEY_UP; break;
1215 case K_S_UP: mod = VTERM_MOD_SHIFT;
1216 key = VTERM_KEY_UP; break;
1217 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001218 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1219 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001220
Bram Moolenaara42ad572017-11-16 13:08:04 +01001221 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1222 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001223 case K_MOUSELEFT: /* TODO */ return 0;
1224 case K_MOUSERIGHT: /* TODO */ return 0;
1225
1226 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001227 case K_LEFTMOUSE_NM:
1228 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001229 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001230 case K_LEFTRELEASE_NM:
1231 case K_MOUSEMOVE:
1232 case K_MIDDLEMOUSE:
1233 case K_MIDDLEDRAG:
1234 case K_MIDDLERELEASE:
1235 case K_RIGHTMOUSE:
1236 case K_RIGHTDRAG:
1237 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1238 return 0;
1239 other = TRUE;
1240 break;
1241
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001242 case K_X1MOUSE: /* TODO */ return 0;
1243 case K_X1DRAG: /* TODO */ return 0;
1244 case K_X1RELEASE: /* TODO */ return 0;
1245 case K_X2MOUSE: /* TODO */ return 0;
1246 case K_X2DRAG: /* TODO */ return 0;
1247 case K_X2RELEASE: /* TODO */ return 0;
1248
1249 case K_IGNORE: return 0;
1250 case K_NOP: return 0;
1251 case K_UNDO: return 0;
1252 case K_HELP: return 0;
1253 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1254 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1255 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1256 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1257 case K_SELECT: return 0;
1258#ifdef FEAT_GUI
1259 case K_VER_SCROLLBAR: return 0;
1260 case K_HOR_SCROLLBAR: return 0;
1261#endif
1262#ifdef FEAT_GUI_TABLINE
1263 case K_TABLINE: return 0;
1264 case K_TABMENU: return 0;
1265#endif
1266#ifdef FEAT_NETBEANS_INTG
1267 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1268#endif
1269#ifdef FEAT_DND
1270 case K_DROP: return 0;
1271#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001272 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001273 case K_PS: vterm_keyboard_start_paste(vterm);
1274 other = TRUE;
1275 break;
1276 case K_PE: vterm_keyboard_end_paste(vterm);
1277 other = TRUE;
1278 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279 }
1280
1281 /*
1282 * Convert special keys to vterm keys:
1283 * - Write keys to vterm: vterm_keyboard_key()
1284 * - Write output to channel.
1285 * TODO: use mod_mask
1286 */
1287 if (key != VTERM_KEY_NONE)
1288 /* Special key, let vterm convert it. */
1289 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001290 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291 /* Normal character, let vterm convert it. */
1292 vterm_keyboard_unichar(vterm, c, mod);
1293
1294 /* Read back the converted escape sequence. */
1295 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1296}
1297
1298/*
1299 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001300 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001301 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001302 */
1303 static int
1304term_job_running_check(term_T *term, int check_job_status)
1305{
1306 /* Also consider the job finished when the channel is closed, to avoid a
1307 * race condition when updating the title. */
1308 if (term != NULL
1309 && term->tl_job != NULL
1310 && channel_is_open(term->tl_job->jv_channel))
1311 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001312 job_T *job = term->tl_job;
1313
1314 // Careful: Checking the job status may invoked callbacks, which close
1315 // the buffer and terminate "term". However, "job" will not be freed
1316 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001317 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001318 job_status(job);
1319 return (job->jv_status == JOB_STARTED
1320 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001321 }
1322 return FALSE;
1323}
1324
1325/*
1326 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001327 */
1328 int
1329term_job_running(term_T *term)
1330{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001331 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001332}
1333
1334/*
1335 * Return TRUE if "term" has an active channel and used ":term NONE".
1336 */
1337 int
1338term_none_open(term_T *term)
1339{
1340 /* Also consider the job finished when the channel is closed, to avoid a
1341 * race condition when updating the title. */
1342 return term != NULL
1343 && term->tl_job != NULL
1344 && channel_is_open(term->tl_job->jv_channel)
1345 && term->tl_job->jv_channel->ch_keep_open;
1346}
1347
1348/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001349 * Used when exiting: kill the job in "buf" if so desired.
1350 * Return OK when the job finished.
1351 * Return FAIL when the job is still running.
1352 */
1353 int
1354term_try_stop_job(buf_T *buf)
1355{
1356 int count;
1357 char *how = (char *)buf->b_term->tl_kill;
1358
1359#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1360 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1361 {
1362 char_u buff[DIALOG_MSG_SIZE];
1363 int ret;
1364
1365 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1366 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1367 if (ret == VIM_YES)
1368 how = "kill";
1369 else if (ret == VIM_CANCEL)
1370 return FAIL;
1371 }
1372#endif
1373 if (how == NULL || *how == NUL)
1374 return FAIL;
1375
1376 job_stop(buf->b_term->tl_job, NULL, how);
1377
1378 /* wait for up to a second for the job to die */
1379 for (count = 0; count < 100; ++count)
1380 {
1381 /* buffer, terminal and job may be cleaned up while waiting */
1382 if (!buf_valid(buf)
1383 || buf->b_term == NULL
1384 || buf->b_term->tl_job == NULL)
1385 return OK;
1386
1387 /* call job_status() to update jv_status */
1388 job_status(buf->b_term->tl_job);
1389 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1390 return OK;
1391 ui_delay(10L, FALSE);
1392 mch_check_messages();
1393 parse_queued_messages();
1394 }
1395 return FAIL;
1396}
1397
1398/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001399 * Add the last line of the scrollback buffer to the buffer in the window.
1400 */
1401 static void
1402add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1403{
1404 buf_T *buf = term->tl_buffer;
1405 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1406 linenr_T lnum = buf->b_ml.ml_line_count;
1407
1408#ifdef WIN3264
1409 if (!enc_utf8 && enc_codepage > 0)
1410 {
1411 WCHAR *ret = NULL;
1412 int length = 0;
1413
1414 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1415 &ret, &length);
1416 if (ret != NULL)
1417 {
1418 WideCharToMultiByte_alloc(enc_codepage, 0,
1419 ret, length, (char **)&text, &len, 0, 0);
1420 vim_free(ret);
1421 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1422 vim_free(text);
1423 }
1424 }
1425 else
1426#endif
1427 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1428 if (empty)
1429 {
1430 /* Delete the empty line that was in the empty buffer. */
1431 curbuf = buf;
1432 ml_delete(1, FALSE);
1433 curbuf = curwin->w_buffer;
1434 }
1435}
1436
1437 static void
1438cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1439{
1440 attr->width = cell->width;
1441 attr->attrs = cell->attrs;
1442 attr->fg = cell->fg;
1443 attr->bg = cell->bg;
1444}
1445
1446 static int
1447equal_celattr(cellattr_T *a, cellattr_T *b)
1448{
1449 /* Comparing the colors should be sufficient. */
1450 return a->fg.red == b->fg.red
1451 && a->fg.green == b->fg.green
1452 && a->fg.blue == b->fg.blue
1453 && a->bg.red == b->bg.red
1454 && a->bg.green == b->bg.green
1455 && a->bg.blue == b->bg.blue;
1456}
1457
Bram Moolenaard96ff162018-02-18 22:13:29 +01001458/*
1459 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1460 * line at this position. Otherwise at the end.
1461 */
1462 static int
1463add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1464{
1465 if (ga_grow(&term->tl_scrollback, 1) == OK)
1466 {
1467 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1468 + term->tl_scrollback.ga_len;
1469
1470 if (lnum > 0)
1471 {
1472 int i;
1473
1474 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1475 {
1476 *line = *(line - 1);
1477 --line;
1478 }
1479 }
1480 line->sb_cols = 0;
1481 line->sb_cells = NULL;
1482 line->sb_fill_attr = *fill_attr;
1483 ++term->tl_scrollback.ga_len;
1484 return OK;
1485 }
1486 return FALSE;
1487}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001488
1489/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001490 * Remove the terminal contents from the scrollback and the buffer.
1491 * Used before adding a new scrollback line or updating the buffer for lines
1492 * displayed in the terminal.
1493 */
1494 static void
1495cleanup_scrollback(term_T *term)
1496{
1497 sb_line_T *line;
1498 garray_T *gap;
1499
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001500 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001501 gap = &term->tl_scrollback;
1502 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1503 && gap->ga_len > 0)
1504 {
1505 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1506 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1507 vim_free(line->sb_cells);
1508 --gap->ga_len;
1509 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001510 curbuf = curwin->w_buffer;
1511 if (curbuf == term->tl_buffer)
1512 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001513}
1514
1515/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001516 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001517 */
1518 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001519update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001520{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001521 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001522 int len;
1523 int lines_skipped = 0;
1524 VTermPos pos;
1525 VTermScreenCell cell;
1526 cellattr_T fill_attr, new_fill_attr;
1527 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001528
1529 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1530 "Adding terminal window snapshot to buffer");
1531
1532 /* First remove the lines that were appended before, they might be
1533 * outdated. */
1534 cleanup_scrollback(term);
1535
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001536 screen = vterm_obtain_screen(term->tl_vterm);
1537 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001538 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1539 {
1540 len = 0;
1541 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1542 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1543 && cell.chars[0] != NUL)
1544 {
1545 len = pos.col + 1;
1546 new_fill_attr = term->tl_default_color;
1547 }
1548 else
1549 /* Assume the last attr is the filler attr. */
1550 cell2cellattr(&cell, &new_fill_attr);
1551
1552 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1553 ++lines_skipped;
1554 else
1555 {
1556 while (lines_skipped > 0)
1557 {
1558 /* Line was skipped, add an empty line. */
1559 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001560 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001561 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562 }
1563
1564 if (len == 0)
1565 p = NULL;
1566 else
1567 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1568 if ((p != NULL || len == 0)
1569 && ga_grow(&term->tl_scrollback, 1) == OK)
1570 {
1571 garray_T ga;
1572 int width;
1573 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1574 + term->tl_scrollback.ga_len;
1575
1576 ga_init2(&ga, 1, 100);
1577 for (pos.col = 0; pos.col < len; pos.col += width)
1578 {
1579 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1580 {
1581 width = 1;
1582 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1583 if (ga_grow(&ga, 1) == OK)
1584 ga.ga_len += utf_char2bytes(' ',
1585 (char_u *)ga.ga_data + ga.ga_len);
1586 }
1587 else
1588 {
1589 width = cell.width;
1590
1591 cell2cellattr(&cell, &p[pos.col]);
1592
Bram Moolenaara79fd562018-12-20 20:47:32 +01001593 // Each character can be up to 6 bytes.
1594 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595 {
1596 int i;
1597 int c;
1598
1599 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1600 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1601 (char_u *)ga.ga_data + ga.ga_len);
1602 }
1603 }
1604 }
1605 line->sb_cols = len;
1606 line->sb_cells = p;
1607 line->sb_fill_attr = new_fill_attr;
1608 fill_attr = new_fill_attr;
1609 ++term->tl_scrollback.ga_len;
1610
1611 if (ga_grow(&ga, 1) == FAIL)
1612 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1613 else
1614 {
1615 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1616 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1617 }
1618 ga_clear(&ga);
1619 }
1620 else
1621 vim_free(p);
1622 }
1623 }
1624
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001625 // Add trailing empty lines.
1626 for (pos.row = term->tl_scrollback.ga_len;
1627 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1628 ++pos.row)
1629 {
1630 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1631 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1632 }
1633
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001634 term->tl_dirty_snapshot = FALSE;
1635#ifdef FEAT_TIMERS
1636 term->tl_timer_set = FALSE;
1637#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001638}
1639
1640/*
1641 * If needed, add the current lines of the terminal to scrollback and to the
1642 * buffer. Called after the job has ended and when switching to
1643 * Terminal-Normal mode.
1644 * When "redraw" is TRUE redraw the windows that show the terminal.
1645 */
1646 static void
1647may_move_terminal_to_buffer(term_T *term, int redraw)
1648{
1649 win_T *wp;
1650
1651 if (term->tl_vterm == NULL)
1652 return;
1653
1654 /* Update the snapshot only if something changes or the buffer does not
1655 * have all the lines. */
1656 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1657 <= term->tl_scrollback_scrolled)
1658 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001659
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 /* Obtain the current background color. */
1661 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1662 &term->tl_default_color.fg, &term->tl_default_color.bg);
1663
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001664 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001665 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001666 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001667 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001668 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001669 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1670 wp->w_cursor.col = 0;
1671 wp->w_valid = 0;
1672 if (wp->w_cursor.lnum >= wp->w_height)
1673 {
1674 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001676 if (wp->w_topline < min_topline)
1677 wp->w_topline = min_topline;
1678 }
1679 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001681 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001682}
1683
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001684#if defined(FEAT_TIMERS) || defined(PROTO)
1685/*
1686 * Check if any terminal timer expired. If so, copy text from the terminal to
1687 * the buffer.
1688 * Return the time until the next timer will expire.
1689 */
1690 int
1691term_check_timers(int next_due_arg, proftime_T *now)
1692{
1693 term_T *term;
1694 int next_due = next_due_arg;
1695
1696 for (term = first_term; term != NULL; term = term->tl_next)
1697 {
1698 if (term->tl_timer_set && !term->tl_normal_mode)
1699 {
1700 long this_due = proftime_time_left(&term->tl_timer_due, now);
1701
1702 if (this_due <= 1)
1703 {
1704 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001705 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001706 }
1707 else if (next_due == -1 || next_due > this_due)
1708 next_due = this_due;
1709 }
1710 }
1711
1712 return next_due;
1713}
1714#endif
1715
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001716 static void
1717set_terminal_mode(term_T *term, int normal_mode)
1718{
1719 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001720 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001721 if (term->tl_buffer == curbuf)
1722 maketitle();
1723}
1724
1725/*
1726 * Called after the job if finished and Terminal mode is not active:
1727 * Move the vterm contents into the scrollback buffer and free the vterm.
1728 */
1729 static void
1730cleanup_vterm(term_T *term)
1731{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001732 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001733 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 term_free_vterm(term);
1735 set_terminal_mode(term, FALSE);
1736}
1737
1738/*
1739 * Switch from Terminal-Job mode to Terminal-Normal mode.
1740 * Suspends updating the terminal window.
1741 */
1742 static void
1743term_enter_normal_mode(void)
1744{
1745 term_T *term = curbuf->b_term;
1746
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001747 set_terminal_mode(term, TRUE);
1748
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001749 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001750 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001752 /* Move the window cursor to the position of the cursor in the
1753 * terminal. */
1754 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1755 + term->tl_cursor_pos.row + 1;
1756 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001757 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1758 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001759
1760 /* Display the same lines as in the terminal. */
1761 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1762}
1763
1764/*
1765 * Returns TRUE if the current window contains a terminal and we are in
1766 * Terminal-Normal mode.
1767 */
1768 int
1769term_in_normal_mode(void)
1770{
1771 term_T *term = curbuf->b_term;
1772
1773 return term != NULL && term->tl_normal_mode;
1774}
1775
1776/*
1777 * Switch from Terminal-Normal mode to Terminal-Job mode.
1778 * Restores updating the terminal window.
1779 */
1780 void
1781term_enter_job_mode()
1782{
1783 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001784
1785 set_terminal_mode(term, FALSE);
1786
1787 if (term->tl_channel_closed)
1788 cleanup_vterm(term);
1789 redraw_buf_and_status_later(curbuf, NOT_VALID);
1790}
1791
1792/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001793 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001794 * Note: while waiting a terminal may be closed and freed if the channel is
1795 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 */
1797 static int
1798term_vgetc()
1799{
1800 int c;
1801 int save_State = State;
1802
1803 State = TERMINAL;
1804 got_int = FALSE;
1805#ifdef WIN3264
1806 ctrl_break_was_pressed = FALSE;
1807#endif
1808 c = vgetc();
1809 got_int = FALSE;
1810 State = save_State;
1811 return c;
1812}
1813
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001814static int mouse_was_outside = FALSE;
1815
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817 * Send keys to terminal.
1818 * Return FAIL when the key needs to be handled in Normal mode.
1819 * Return OK when the key was dropped or sent to the terminal.
1820 */
1821 int
1822send_keys_to_term(term_T *term, int c, int typed)
1823{
1824 char msg[KEY_BUF_LEN];
1825 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001826 int dragging_outside = FALSE;
1827
1828 /* Catch keys that need to be handled as in Normal mode. */
1829 switch (c)
1830 {
1831 case NUL:
1832 case K_ZERO:
1833 if (typed)
1834 stuffcharReadbuff(c);
1835 return FAIL;
1836
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001837 case K_TABLINE:
1838 stuffcharReadbuff(c);
1839 return FAIL;
1840
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001841 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001842 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001843 return FAIL;
1844
1845 case K_LEFTDRAG:
1846 case K_MIDDLEDRAG:
1847 case K_RIGHTDRAG:
1848 case K_X1DRAG:
1849 case K_X2DRAG:
1850 dragging_outside = mouse_was_outside;
1851 /* FALLTHROUGH */
1852 case K_LEFTMOUSE:
1853 case K_LEFTMOUSE_NM:
1854 case K_LEFTRELEASE:
1855 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001856 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857 case K_MIDDLEMOUSE:
1858 case K_MIDDLERELEASE:
1859 case K_RIGHTMOUSE:
1860 case K_RIGHTRELEASE:
1861 case K_X1MOUSE:
1862 case K_X1RELEASE:
1863 case K_X2MOUSE:
1864 case K_X2RELEASE:
1865
1866 case K_MOUSEUP:
1867 case K_MOUSEDOWN:
1868 case K_MOUSELEFT:
1869 case K_MOUSERIGHT:
1870 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001871 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001872 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001873 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001874 || dragging_outside)
1875 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001876 /* click or scroll outside the current window or on status line
1877 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 if (typed)
1879 {
1880 stuffcharReadbuff(c);
1881 mouse_was_outside = TRUE;
1882 }
1883 return FAIL;
1884 }
1885 }
1886 if (typed)
1887 mouse_was_outside = FALSE;
1888
1889 /* Convert the typed key to a sequence of bytes for the job. */
1890 len = term_convert_key(term, c, msg);
1891 if (len > 0)
1892 /* TODO: if FAIL is returned, stop? */
1893 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1894 (char_u *)msg, (int)len, NULL);
1895
1896 return OK;
1897}
1898
1899 static void
1900position_cursor(win_T *wp, VTermPos *pos)
1901{
1902 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1903 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1904 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1905}
1906
1907/*
1908 * Handle CTRL-W "": send register contents to the job.
1909 */
1910 static void
1911term_paste_register(int prev_c UNUSED)
1912{
1913 int c;
1914 list_T *l;
1915 listitem_T *item;
1916 long reglen = 0;
1917 int type;
1918
1919#ifdef FEAT_CMDL_INFO
1920 if (add_to_showcmd(prev_c))
1921 if (add_to_showcmd('"'))
1922 out_flush();
1923#endif
1924 c = term_vgetc();
1925#ifdef FEAT_CMDL_INFO
1926 clear_showcmd();
1927#endif
1928 if (!term_use_loop())
1929 /* job finished while waiting for a character */
1930 return;
1931
1932 /* CTRL-W "= prompt for expression to evaluate. */
1933 if (c == '=' && get_expr_register() != '=')
1934 return;
1935 if (!term_use_loop())
1936 /* job finished while waiting for a character */
1937 return;
1938
1939 l = (list_T *)get_reg_contents(c, GREG_LIST);
1940 if (l != NULL)
1941 {
1942 type = get_reg_type(c, &reglen);
1943 for (item = l->lv_first; item != NULL; item = item->li_next)
1944 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01001945 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946#ifdef WIN3264
1947 char_u *tmp = s;
1948
1949 if (!enc_utf8 && enc_codepage > 0)
1950 {
1951 WCHAR *ret = NULL;
1952 int length = 0;
1953
1954 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1955 (int)STRLEN(s), &ret, &length);
1956 if (ret != NULL)
1957 {
1958 WideCharToMultiByte_alloc(CP_UTF8, 0,
1959 ret, length, (char **)&s, &length, 0, 0);
1960 vim_free(ret);
1961 }
1962 }
1963#endif
1964 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1965 s, (int)STRLEN(s), NULL);
1966#ifdef WIN3264
1967 if (tmp != s)
1968 vim_free(s);
1969#endif
1970
1971 if (item->li_next != NULL || type == MLINE)
1972 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1973 (char_u *)"\r", 1, NULL);
1974 }
1975 list_free(l);
1976 }
1977}
1978
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001980 * Return TRUE when waiting for a character in the terminal, the cursor of the
1981 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 */
1983 int
1984terminal_is_active()
1985{
1986 return in_terminal_loop != NULL;
1987}
1988
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001989#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 cursorentry_T *
1991term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1992{
1993 term_T *term = in_terminal_loop;
1994 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02001995 int id;
1996 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997
1998 vim_memset(&entry, 0, sizeof(entry));
1999 entry.shape = entry.mshape =
2000 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2001 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2002 SHAPE_BLOCK;
2003 entry.percentage = 20;
2004 if (term->tl_cursor_blink)
2005 {
2006 entry.blinkwait = 700;
2007 entry.blinkon = 400;
2008 entry.blinkoff = 250;
2009 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002010
2011 /* The "Terminal" highlight group overrules the defaults. */
2012 id = syn_name2id((char_u *)"Terminal");
2013 if (id != 0)
2014 {
2015 syn_id2colors(id, &term_fg, &term_bg);
2016 *fg = term_bg;
2017 }
2018 else
2019 *fg = gui.back_pixel;
2020
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002022 {
2023 if (id != 0)
2024 *bg = term_fg;
2025 else
2026 *bg = gui.norm_pixel;
2027 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 else
2029 *bg = color_name2handle(term->tl_cursor_color);
2030 entry.name = "n";
2031 entry.used_for = SHAPE_CURSOR;
2032
2033 return &entry;
2034}
2035#endif
2036
Bram Moolenaard317b382018-02-08 22:33:31 +01002037 static void
2038may_output_cursor_props(void)
2039{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002040 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002041 || last_set_cursor_shape != desired_cursor_shape
2042 || last_set_cursor_blink != desired_cursor_blink)
2043 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002044 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002045 last_set_cursor_shape = desired_cursor_shape;
2046 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002047 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002048 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2049 /* this will restore the initial cursor style, if possible */
2050 ui_cursor_shape_forced(TRUE);
2051 else
2052 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2053 }
2054}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002055
Bram Moolenaard317b382018-02-08 22:33:31 +01002056/*
2057 * Set the cursor color and shape, if not last set to these.
2058 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 static void
2060may_set_cursor_props(term_T *term)
2061{
2062#ifdef FEAT_GUI
2063 /* For the GUI the cursor properties are obtained with
2064 * term_get_cursor_shape(). */
2065 if (gui.in_use)
2066 return;
2067#endif
2068 if (in_terminal_loop == term)
2069 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002070 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002071 desired_cursor_shape = term->tl_cursor_shape;
2072 desired_cursor_blink = term->tl_cursor_blink;
2073 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002074 }
2075}
2076
Bram Moolenaard317b382018-02-08 22:33:31 +01002077/*
2078 * Reset the desired cursor properties and restore them when needed.
2079 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002080 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002081prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002082{
2083#ifdef FEAT_GUI
2084 if (gui.in_use)
2085 return;
2086#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002087 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002088 desired_cursor_shape = -1;
2089 desired_cursor_blink = -1;
2090 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002091}
2092
2093/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002094 * Returns TRUE if the current window contains a terminal and we are sending
2095 * keys to the job.
2096 * If "check_job_status" is TRUE update the job status.
2097 */
2098 static int
2099term_use_loop_check(int check_job_status)
2100{
2101 term_T *term = curbuf->b_term;
2102
2103 return term != NULL
2104 && !term->tl_normal_mode
2105 && term->tl_vterm != NULL
2106 && term_job_running_check(term, check_job_status);
2107}
2108
2109/*
2110 * Returns TRUE if the current window contains a terminal and we are sending
2111 * keys to the job.
2112 */
2113 int
2114term_use_loop(void)
2115{
2116 return term_use_loop_check(FALSE);
2117}
2118
2119/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002120 * Called when entering a window with the mouse. If this is a terminal window
2121 * we may want to change state.
2122 */
2123 void
2124term_win_entered()
2125{
2126 term_T *term = curbuf->b_term;
2127
2128 if (term != NULL)
2129 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002130 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002131 {
2132 reset_VIsual_and_resel();
2133 if (State & INSERT)
2134 stop_insert_mode = TRUE;
2135 }
2136 mouse_was_outside = FALSE;
2137 enter_mouse_col = mouse_col;
2138 enter_mouse_row = mouse_row;
2139 }
2140}
2141
2142/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002143 * Wait for input and send it to the job.
2144 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2145 * when there is no more typahead.
2146 * Return when the start of a CTRL-W command is typed or anything else that
2147 * should be handled as a Normal mode command.
2148 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2149 * the terminal was closed.
2150 */
2151 int
2152terminal_loop(int blocking)
2153{
2154 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002155 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002157#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002158 int tty_fd = curbuf->b_term->tl_job->jv_channel
2159 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002160#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002161 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162
2163 /* Remember the terminal we are sending keys to. However, the terminal
2164 * might be closed while waiting for a character, e.g. typing "exit" in a
2165 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2166 * stored reference. */
2167 in_terminal_loop = curbuf->b_term;
2168
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002169 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002170 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002171 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002172 if (termwinkey == Ctrl_W)
2173 termwinkey = 0;
2174 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2176 may_set_cursor_props(curbuf->b_term);
2177
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002178 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002180#ifdef FEAT_GUI
2181 if (!curbuf->b_term->tl_system)
2182#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002183 // TODO: skip screen update when handling a sequence of keys.
2184 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002185 while (must_redraw != 0)
2186 if (update_screen(0) == FAIL)
2187 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002188 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002189 /* job finished while redrawing */
2190 break;
2191
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002192 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002193 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002194
2195 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002196 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002197 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002198 /* Job finished while waiting for a character. Push back the
2199 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002200 if (c != K_IGNORE)
2201 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002203 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 if (c == K_IGNORE)
2205 continue;
2206
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002207#ifdef UNIX
2208 /*
2209 * The shell or another program may change the tty settings. Getting
2210 * them for every typed character is a bit of overhead, but it's needed
2211 * for the first character typed, e.g. when Vim starts in a shell.
2212 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002213 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002214 {
2215 ttyinfo_T info;
2216
2217 /* Get the current backspace character of the pty. */
2218 if (get_tty_info(tty_fd, &info) == OK)
2219 term_backspace_char = info.backspace;
2220 }
2221#endif
2222
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002223#ifdef WIN3264
2224 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2225 * Use CTRL-BREAK to kill the job. */
2226 if (ctrl_break_was_pressed)
2227 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2228#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002229 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002230 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002231 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002232#ifdef FEAT_GUI
2233 && !curbuf->b_term->tl_system
2234#endif
2235 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 {
2237 int prev_c = c;
2238
2239#ifdef FEAT_CMDL_INFO
2240 if (add_to_showcmd(c))
2241 out_flush();
2242#endif
2243 c = term_vgetc();
2244#ifdef FEAT_CMDL_INFO
2245 clear_showcmd();
2246#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002247 if (!term_use_loop_check(TRUE)
2248 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002249 /* job finished while waiting for a character */
2250 break;
2251
2252 if (prev_c == Ctrl_BSL)
2253 {
2254 if (c == Ctrl_N)
2255 {
2256 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2257 term_enter_normal_mode();
2258 ret = FAIL;
2259 goto theend;
2260 }
2261 /* Send both keys to the terminal. */
2262 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2263 }
2264 else if (c == Ctrl_C)
2265 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002266 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2268 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002269 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 {
2271 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002272 /* "'termwinkey' .": send 'termwinkey' to the job */
2273 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002275 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002276 {
2277 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2278 c = Ctrl_BSL;
2279 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280 else if (c == 'N')
2281 {
2282 /* CTRL-W N : go to Terminal-Normal mode. */
2283 term_enter_normal_mode();
2284 ret = FAIL;
2285 goto theend;
2286 }
2287 else if (c == '"')
2288 {
2289 term_paste_register(prev_c);
2290 continue;
2291 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002292 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293 {
2294 stuffcharReadbuff(Ctrl_W);
2295 stuffcharReadbuff(c);
2296 ret = OK;
2297 goto theend;
2298 }
2299 }
2300# ifdef WIN3264
2301 if (!enc_utf8 && has_mbyte && c >= 0x80)
2302 {
2303 WCHAR wc;
2304 char_u mb[3];
2305
2306 mb[0] = (unsigned)c >> 8;
2307 mb[1] = c;
2308 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2309 c = wc;
2310 }
2311# endif
2312 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2313 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002314 if (c == K_MOUSEMOVE)
2315 /* We are sure to come back here, don't reset the cursor color
2316 * and shape to avoid flickering. */
2317 restore_cursor = FALSE;
2318
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002319 ret = OK;
2320 goto theend;
2321 }
2322 }
2323 ret = FAIL;
2324
2325theend:
2326 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002327 if (restore_cursor)
2328 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002329
2330 /* Move a snapshot of the screen contents to the buffer, so that completion
2331 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002332 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2333 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002334
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002335 return ret;
2336}
2337
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002338 static void
2339may_toggle_cursor(term_T *term)
2340{
2341 if (in_terminal_loop == term)
2342 {
2343 if (term->tl_cursor_visible)
2344 cursor_on();
2345 else
2346 cursor_off();
2347 }
2348}
2349
2350/*
2351 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002352 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002353 */
2354 static int
2355color2index(VTermColor *color, int fg, int *boldp)
2356{
2357 int red = color->red;
2358 int blue = color->blue;
2359 int green = color->green;
2360
Bram Moolenaar46359e12017-11-29 22:33:38 +01002361 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002363 /* First 16 colors and default: use the ANSI index, because these
2364 * colors can be redefined. */
2365 if (t_colors >= 16)
2366 return color->ansi_index;
2367 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002368 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002369 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002370 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002371 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2372 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2373 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002374 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002375 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2376 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2377 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2378 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2379 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2380 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2381 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2382 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2383 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2384 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2385 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 }
2387 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 if (t_colors >= 256)
2390 {
2391 if (red == blue && red == green)
2392 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002393 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002395 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2396 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2397 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398 int i;
2399
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002400 if (red < 5)
2401 return 17; /* 00/00/00 */
2402 if (red > 245) /* ff/ff/ff */
2403 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 for (i = 0; i < 23; ++i)
2405 if (red < cutoff[i])
2406 return i + 233;
2407 return 256;
2408 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002409 {
2410 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2411 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002412
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002413 /* 216-color cube */
2414 for (ri = 0; ri < 5; ++ri)
2415 if (red < cutoff[ri])
2416 break;
2417 for (gi = 0; gi < 5; ++gi)
2418 if (green < cutoff[gi])
2419 break;
2420 for (bi = 0; bi < 5; ++bi)
2421 if (blue < cutoff[bi])
2422 break;
2423 return 17 + ri * 36 + gi * 6 + bi;
2424 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 }
2426 return 0;
2427}
2428
2429/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002430 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431 */
2432 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002433vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434{
2435 int attr = 0;
2436
2437 if (cellattrs.bold)
2438 attr |= HL_BOLD;
2439 if (cellattrs.underline)
2440 attr |= HL_UNDERLINE;
2441 if (cellattrs.italic)
2442 attr |= HL_ITALIC;
2443 if (cellattrs.strike)
2444 attr |= HL_STRIKETHROUGH;
2445 if (cellattrs.reverse)
2446 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002447 return attr;
2448}
2449
2450/*
2451 * Store Vterm attributes in "cell" from highlight flags.
2452 */
2453 static void
2454hl2vtermAttr(int attr, cellattr_T *cell)
2455{
2456 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2457 if (attr & HL_BOLD)
2458 cell->attrs.bold = 1;
2459 if (attr & HL_UNDERLINE)
2460 cell->attrs.underline = 1;
2461 if (attr & HL_ITALIC)
2462 cell->attrs.italic = 1;
2463 if (attr & HL_STRIKETHROUGH)
2464 cell->attrs.strike = 1;
2465 if (attr & HL_INVERSE)
2466 cell->attrs.reverse = 1;
2467}
2468
2469/*
2470 * Convert the attributes of a vterm cell into an attribute index.
2471 */
2472 static int
2473cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2474{
2475 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476
2477#ifdef FEAT_GUI
2478 if (gui.in_use)
2479 {
2480 guicolor_T fg, bg;
2481
2482 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2483 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2484 return get_gui_attr_idx(attr, fg, bg);
2485 }
2486 else
2487#endif
2488#ifdef FEAT_TERMGUICOLORS
2489 if (p_tgc)
2490 {
2491 guicolor_T fg, bg;
2492
2493 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2494 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2495
2496 return get_tgc_attr_idx(attr, fg, bg);
2497 }
2498 else
2499#endif
2500 {
2501 int bold = MAYBE;
2502 int fg = color2index(&cellfg, TRUE, &bold);
2503 int bg = color2index(&cellbg, FALSE, &bold);
2504
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002505 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002506 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002507 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002508 if (fg == 0 && term_default_cterm_fg >= 0)
2509 fg = term_default_cterm_fg + 1;
2510 if (bg == 0 && term_default_cterm_bg >= 0)
2511 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002512 }
2513
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 /* with 8 colors set the bold attribute to get a bright foreground */
2515 if (bold == TRUE)
2516 attr |= HL_BOLD;
2517 return get_cterm_attr_idx(attr, fg, bg);
2518 }
2519 return 0;
2520}
2521
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002522 static void
2523set_dirty_snapshot(term_T *term)
2524{
2525 term->tl_dirty_snapshot = TRUE;
2526#ifdef FEAT_TIMERS
2527 if (!term->tl_normal_mode)
2528 {
2529 /* Update the snapshot after 100 msec of not getting updates. */
2530 profile_setlimit(100L, &term->tl_timer_due);
2531 term->tl_timer_set = TRUE;
2532 }
2533#endif
2534}
2535
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 static int
2537handle_damage(VTermRect rect, void *user)
2538{
2539 term_T *term = (term_T *)user;
2540
2541 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2542 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002543 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002544 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545 return 1;
2546}
2547
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002548 static void
2549term_scroll_up(term_T *term, int start_row, int count)
2550{
2551 win_T *wp;
2552 VTermColor fg, bg;
2553 VTermScreenCellAttrs attr;
2554 int clear_attr;
2555
2556 /* Set the color to clear lines with. */
2557 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2558 &fg, &bg);
2559 vim_memset(&attr, 0, sizeof(attr));
2560 clear_attr = cell2attr(attr, fg, bg);
2561
2562 FOR_ALL_WINDOWS(wp)
2563 {
2564 if (wp->w_buffer == term->tl_buffer)
2565 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2566 }
2567}
2568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002569 static int
2570handle_moverect(VTermRect dest, VTermRect src, void *user)
2571{
2572 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002573 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002574
2575 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002576 * redrawing the text. But avoid doing this multiple times, postpone until
2577 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 if (dest.start_col == src.start_col
2579 && dest.end_col == src.end_col
2580 && dest.start_row < src.start_row)
2581 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002582 if (dest.start_row == 0)
2583 term->tl_postponed_scroll += count;
2584 else
2585 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002586 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002587
2588 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2589 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002590 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002591
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002592 /* Note sure if the scrolling will work correctly, let's do a complete
2593 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002594 redraw_buf_later(term->tl_buffer, NOT_VALID);
2595 return 1;
2596}
2597
2598 static int
2599handle_movecursor(
2600 VTermPos pos,
2601 VTermPos oldpos UNUSED,
2602 int visible,
2603 void *user)
2604{
2605 term_T *term = (term_T *)user;
2606 win_T *wp;
2607
2608 term->tl_cursor_pos = pos;
2609 term->tl_cursor_visible = visible;
2610
2611 FOR_ALL_WINDOWS(wp)
2612 {
2613 if (wp->w_buffer == term->tl_buffer)
2614 position_cursor(wp, &pos);
2615 }
2616 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2617 {
2618 may_toggle_cursor(term);
2619 update_cursor(term, term->tl_cursor_visible);
2620 }
2621
2622 return 1;
2623}
2624
2625 static int
2626handle_settermprop(
2627 VTermProp prop,
2628 VTermValue *value,
2629 void *user)
2630{
2631 term_T *term = (term_T *)user;
2632
2633 switch (prop)
2634 {
2635 case VTERM_PROP_TITLE:
2636 vim_free(term->tl_title);
2637 /* a blank title isn't useful, make it empty, so that "running" is
2638 * displayed */
2639 if (*skipwhite((char_u *)value->string) == NUL)
2640 term->tl_title = NULL;
2641#ifdef WIN3264
2642 else if (!enc_utf8 && enc_codepage > 0)
2643 {
2644 WCHAR *ret = NULL;
2645 int length = 0;
2646
2647 MultiByteToWideChar_alloc(CP_UTF8, 0,
2648 (char*)value->string, (int)STRLEN(value->string),
2649 &ret, &length);
2650 if (ret != NULL)
2651 {
2652 WideCharToMultiByte_alloc(enc_codepage, 0,
2653 ret, length, (char**)&term->tl_title,
2654 &length, 0, 0);
2655 vim_free(ret);
2656 }
2657 }
2658#endif
2659 else
2660 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002661 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662 if (term == curbuf->b_term)
2663 maketitle();
2664 break;
2665
2666 case VTERM_PROP_CURSORVISIBLE:
2667 term->tl_cursor_visible = value->boolean;
2668 may_toggle_cursor(term);
2669 out_flush();
2670 break;
2671
2672 case VTERM_PROP_CURSORBLINK:
2673 term->tl_cursor_blink = value->boolean;
2674 may_set_cursor_props(term);
2675 break;
2676
2677 case VTERM_PROP_CURSORSHAPE:
2678 term->tl_cursor_shape = value->number;
2679 may_set_cursor_props(term);
2680 break;
2681
2682 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002683 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002684 may_set_cursor_props(term);
2685 break;
2686
2687 case VTERM_PROP_ALTSCREEN:
2688 /* TODO: do anything else? */
2689 term->tl_using_altscreen = value->boolean;
2690 break;
2691
2692 default:
2693 break;
2694 }
2695 /* Always return 1, otherwise vterm doesn't store the value internally. */
2696 return 1;
2697}
2698
2699/*
2700 * The job running in the terminal resized the terminal.
2701 */
2702 static int
2703handle_resize(int rows, int cols, void *user)
2704{
2705 term_T *term = (term_T *)user;
2706 win_T *wp;
2707
2708 term->tl_rows = rows;
2709 term->tl_cols = cols;
2710 if (term->tl_vterm_size_changed)
2711 /* Size was set by vterm_set_size(), don't set the window size. */
2712 term->tl_vterm_size_changed = FALSE;
2713 else
2714 {
2715 FOR_ALL_WINDOWS(wp)
2716 {
2717 if (wp->w_buffer == term->tl_buffer)
2718 {
2719 win_setheight_win(rows, wp);
2720 win_setwidth_win(cols, wp);
2721 }
2722 }
2723 redraw_buf_later(term->tl_buffer, NOT_VALID);
2724 }
2725 return 1;
2726}
2727
2728/*
2729 * Handle a line that is pushed off the top of the screen.
2730 */
2731 static int
2732handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2733{
2734 term_T *term = (term_T *)user;
2735
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002736 /* First remove the lines that were appended before, the pushed line goes
2737 * above it. */
2738 cleanup_scrollback(term);
2739
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002740 /* If the number of lines that are stored goes over 'termscrollback' then
2741 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002742 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002743 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002744 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002745 int i;
2746
2747 curbuf = term->tl_buffer;
2748 for (i = 0; i < todo; ++i)
2749 {
2750 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2751 ml_delete(1, FALSE);
2752 }
2753 curbuf = curwin->w_buffer;
2754
2755 term->tl_scrollback.ga_len -= todo;
2756 mch_memmove(term->tl_scrollback.ga_data,
2757 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2758 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002759 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002760 }
2761
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002762 if (ga_grow(&term->tl_scrollback, 1) == OK)
2763 {
2764 cellattr_T *p = NULL;
2765 int len = 0;
2766 int i;
2767 int c;
2768 int col;
2769 sb_line_T *line;
2770 garray_T ga;
2771 cellattr_T fill_attr = term->tl_default_color;
2772
2773 /* do not store empty cells at the end */
2774 for (i = 0; i < cols; ++i)
2775 if (cells[i].chars[0] != 0)
2776 len = i + 1;
2777 else
2778 cell2cellattr(&cells[i], &fill_attr);
2779
2780 ga_init2(&ga, 1, 100);
2781 if (len > 0)
2782 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2783 if (p != NULL)
2784 {
2785 for (col = 0; col < len; col += cells[col].width)
2786 {
2787 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2788 {
2789 ga.ga_len = 0;
2790 break;
2791 }
2792 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2793 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2794 (char_u *)ga.ga_data + ga.ga_len);
2795 cell2cellattr(&cells[col], &p[col]);
2796 }
2797 }
2798 if (ga_grow(&ga, 1) == FAIL)
2799 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2800 else
2801 {
2802 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2803 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2804 }
2805 ga_clear(&ga);
2806
2807 line = (sb_line_T *)term->tl_scrollback.ga_data
2808 + term->tl_scrollback.ga_len;
2809 line->sb_cols = len;
2810 line->sb_cells = p;
2811 line->sb_fill_attr = fill_attr;
2812 ++term->tl_scrollback.ga_len;
2813 ++term->tl_scrollback_scrolled;
2814 }
2815 return 0; /* ignored */
2816}
2817
2818static VTermScreenCallbacks screen_callbacks = {
2819 handle_damage, /* damage */
2820 handle_moverect, /* moverect */
2821 handle_movecursor, /* movecursor */
2822 handle_settermprop, /* settermprop */
2823 NULL, /* bell */
2824 handle_resize, /* resize */
2825 handle_pushline, /* sb_pushline */
2826 NULL /* sb_popline */
2827};
2828
2829/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002830 * Do the work after the channel of a terminal was closed.
2831 * Must be called only when updating_screen is FALSE.
2832 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2833 */
2834 static int
2835term_after_channel_closed(term_T *term)
2836{
2837 /* Unless in Terminal-Normal mode: clear the vterm. */
2838 if (!term->tl_normal_mode)
2839 {
2840 int fnum = term->tl_buffer->b_fnum;
2841
2842 cleanup_vterm(term);
2843
2844 if (term->tl_finish == TL_FINISH_CLOSE)
2845 {
2846 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002847 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002848
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002849 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002850 ch_log(NULL, "terminal job finished, closing window");
2851 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002852 // Avoid closing the window if we temporarily use it.
2853 if (do_set_w_closing)
2854 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002855 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002856 if (do_set_w_closing)
2857 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002858 aucmd_restbuf(&aco);
2859 return TRUE;
2860 }
2861 if (term->tl_finish == TL_FINISH_OPEN
2862 && term->tl_buffer->b_nwindows == 0)
2863 {
2864 char buf[50];
2865
2866 /* TODO: use term_opencmd */
2867 ch_log(NULL, "terminal job finished, opening window");
2868 vim_snprintf(buf, sizeof(buf),
2869 term->tl_opencmd == NULL
2870 ? "botright sbuf %d"
2871 : (char *)term->tl_opencmd, fnum);
2872 do_cmdline_cmd((char_u *)buf);
2873 }
2874 else
2875 ch_log(NULL, "terminal job finished");
2876 }
2877
2878 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2879 return FALSE;
2880}
2881
2882/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 * Called when a channel has been closed.
2884 * If this was a channel for a terminal window then finish it up.
2885 */
2886 void
2887term_channel_closed(channel_T *ch)
2888{
2889 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002890 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891 int did_one = FALSE;
2892
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002893 for (term = first_term; term != NULL; term = next_term)
2894 {
2895 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002896 if (term->tl_job == ch->ch_job)
2897 {
2898 term->tl_channel_closed = TRUE;
2899 did_one = TRUE;
2900
Bram Moolenaard23a8232018-02-10 18:45:26 +01002901 VIM_CLEAR(term->tl_title);
2902 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002903#ifdef WIN3264
2904 if (term->tl_out_fd != NULL)
2905 {
2906 fclose(term->tl_out_fd);
2907 term->tl_out_fd = NULL;
2908 }
2909#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002911 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002913 /* Cannot open or close windows now. Can happen when
2914 * 'lazyredraw' is set. */
2915 term->tl_channel_recently_closed = TRUE;
2916 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002917 }
2918
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002919 if (term_after_channel_closed(term))
2920 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002921 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002922 }
2923
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002924 if (did_one)
2925 {
2926 redraw_statuslines();
2927
2928 /* Need to break out of vgetc(). */
2929 ins_char_typebuf(K_IGNORE);
2930 typebuf_was_filled = TRUE;
2931
2932 term = curbuf->b_term;
2933 if (term != NULL)
2934 {
2935 if (term->tl_job == ch->ch_job)
2936 maketitle();
2937 update_cursor(term, term->tl_cursor_visible);
2938 }
2939 }
2940}
2941
2942/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002943 * To be called after resetting updating_screen: handle any terminal where the
2944 * channel was closed.
2945 */
2946 void
2947term_check_channel_closed_recently()
2948{
2949 term_T *term;
2950 term_T *next_term;
2951
2952 for (term = first_term; term != NULL; term = next_term)
2953 {
2954 next_term = term->tl_next;
2955 if (term->tl_channel_recently_closed)
2956 {
2957 term->tl_channel_recently_closed = FALSE;
2958 if (term_after_channel_closed(term))
2959 // start over, the list may have changed
2960 next_term = first_term;
2961 }
2962 }
2963}
2964
2965/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002966 * Fill one screen line from a line of the terminal.
2967 * Advances "pos" to past the last column.
2968 */
2969 static void
2970term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2971{
2972 int off = screen_get_current_line_off();
2973
2974 for (pos->col = 0; pos->col < max_col; )
2975 {
2976 VTermScreenCell cell;
2977 int c;
2978
2979 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2980 vim_memset(&cell, 0, sizeof(cell));
2981
2982 c = cell.chars[0];
2983 if (c == NUL)
2984 {
2985 ScreenLines[off] = ' ';
2986 if (enc_utf8)
2987 ScreenLinesUC[off] = NUL;
2988 }
2989 else
2990 {
2991 if (enc_utf8)
2992 {
2993 int i;
2994
2995 /* composing chars */
2996 for (i = 0; i < Screen_mco
2997 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2998 {
2999 ScreenLinesC[i][off] = cell.chars[i + 1];
3000 if (cell.chars[i + 1] == 0)
3001 break;
3002 }
3003 if (c >= 0x80 || (Screen_mco > 0
3004 && ScreenLinesC[0][off] != 0))
3005 {
3006 ScreenLines[off] = ' ';
3007 ScreenLinesUC[off] = c;
3008 }
3009 else
3010 {
3011 ScreenLines[off] = c;
3012 ScreenLinesUC[off] = NUL;
3013 }
3014 }
3015#ifdef WIN3264
3016 else if (has_mbyte && c >= 0x80)
3017 {
3018 char_u mb[MB_MAXBYTES+1];
3019 WCHAR wc = c;
3020
3021 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3022 (char*)mb, 2, 0, 0) > 1)
3023 {
3024 ScreenLines[off] = mb[0];
3025 ScreenLines[off + 1] = mb[1];
3026 cell.width = mb_ptr2cells(mb);
3027 }
3028 else
3029 ScreenLines[off] = c;
3030 }
3031#endif
3032 else
3033 ScreenLines[off] = c;
3034 }
3035 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3036
3037 ++pos->col;
3038 ++off;
3039 if (cell.width == 2)
3040 {
3041 if (enc_utf8)
3042 ScreenLinesUC[off] = NUL;
3043
3044 /* don't set the second byte to NUL for a DBCS encoding, it
3045 * has been set above */
3046 if (enc_utf8 || !has_mbyte)
3047 ScreenLines[off] = NUL;
3048
3049 ++pos->col;
3050 ++off;
3051 }
3052 }
3053}
3054
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003055#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003056 static void
3057update_system_term(term_T *term)
3058{
3059 VTermPos pos;
3060 VTermScreen *screen;
3061
3062 if (term->tl_vterm == NULL)
3063 return;
3064 screen = vterm_obtain_screen(term->tl_vterm);
3065
3066 /* Scroll up to make more room for terminal lines if needed. */
3067 while (term->tl_toprow > 0
3068 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3069 {
3070 int save_p_more = p_more;
3071
3072 p_more = FALSE;
3073 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003074 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003075 p_more = save_p_more;
3076 --term->tl_toprow;
3077 }
3078
3079 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3080 && pos.row < Rows; ++pos.row)
3081 {
3082 if (pos.row < term->tl_rows)
3083 {
3084 int max_col = MIN(Columns, term->tl_cols);
3085
3086 term_line2screenline(screen, &pos, max_col);
3087 }
3088 else
3089 pos.col = 0;
3090
3091 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3092 }
3093
3094 term->tl_dirty_row_start = MAX_ROW;
3095 term->tl_dirty_row_end = 0;
3096 update_cursor(term, TRUE);
3097}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003098#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003099
3100/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003101 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3102 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103 * Terminal-Normal mode.
3104 */
3105 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003106term_do_update_window(win_T *wp)
3107{
3108 term_T *term = wp->w_buffer->b_term;
3109
3110 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3111}
3112
3113/*
3114 * Called to update a window that contains an active terminal.
3115 */
3116 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003117term_update_window(win_T *wp)
3118{
3119 term_T *term = wp->w_buffer->b_term;
3120 VTerm *vterm;
3121 VTermScreen *screen;
3122 VTermState *state;
3123 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003124 int rows, cols;
3125 int newrows, newcols;
3126 int minsize;
3127 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003128
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003129 vterm = term->tl_vterm;
3130 screen = vterm_obtain_screen(vterm);
3131 state = vterm_obtain_state(vterm);
3132
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003133 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3134 * SOME_VALID only redraw what was marked dirty. */
3135 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003136 {
3137 term->tl_dirty_row_start = 0;
3138 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003139
3140 if (term->tl_postponed_scroll > 0
3141 && term->tl_postponed_scroll < term->tl_rows / 3)
3142 /* Scrolling is usually faster than redrawing, when there are only
3143 * a few lines to scroll. */
3144 term_scroll_up(term, 0, term->tl_postponed_scroll);
3145 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003146 }
3147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003148 /*
3149 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003150 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003151 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003152 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153
Bram Moolenaar498c2562018-04-15 23:45:15 +02003154 newrows = 99999;
3155 newcols = 99999;
3156 FOR_ALL_WINDOWS(twp)
3157 {
3158 /* When more than one window shows the same terminal, use the
3159 * smallest size. */
3160 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003161 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003162 newrows = MIN(newrows, twp->w_height);
3163 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003164 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003165 }
3166 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3167 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3168
3169 if (term->tl_rows != newrows || term->tl_cols != newcols)
3170 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003172 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003174 newrows);
3175 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003176
3177 // Updating the terminal size will cause the snapshot to be cleared.
3178 // When not in terminal_loop() we need to restore it.
3179 if (term != in_terminal_loop)
3180 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 }
3182
3183 /* The cursor may have been moved when resizing. */
3184 vterm_state_get_cursorpos(state, &pos);
3185 position_cursor(wp, &pos);
3186
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003187 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3188 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003190 if (pos.row < term->tl_rows)
3191 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003192 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003193
Bram Moolenaar13568252018-03-16 20:46:58 +01003194 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 }
3196 else
3197 pos.col = 0;
3198
Bram Moolenaarf118d482018-03-13 13:14:00 +01003199 screen_line(wp->w_winrow + pos.row
3200#ifdef FEAT_MENU
3201 + winbar_height(wp)
3202#endif
3203 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003204 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003205 term->tl_dirty_row_start = MAX_ROW;
3206 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207}
3208
3209/*
3210 * Return TRUE if "wp" is a terminal window where the job has finished.
3211 */
3212 int
3213term_is_finished(buf_T *buf)
3214{
3215 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3216}
3217
3218/*
3219 * Return TRUE if "wp" is a terminal window where the job has finished or we
3220 * are in Terminal-Normal mode, thus we show the buffer contents.
3221 */
3222 int
3223term_show_buffer(buf_T *buf)
3224{
3225 term_T *term = buf->b_term;
3226
3227 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3228}
3229
3230/*
3231 * The current buffer is going to be changed. If there is terminal
3232 * highlighting remove it now.
3233 */
3234 void
3235term_change_in_curbuf(void)
3236{
3237 term_T *term = curbuf->b_term;
3238
3239 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3240 {
3241 free_scrollback(term);
3242 redraw_buf_later(term->tl_buffer, NOT_VALID);
3243
3244 /* The buffer is now like a normal buffer, it cannot be easily
3245 * abandoned when changed. */
3246 set_string_option_direct((char_u *)"buftype", -1,
3247 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3248 }
3249}
3250
3251/*
3252 * Get the screen attribute for a position in the buffer.
3253 * Use a negative "col" to get the filler background color.
3254 */
3255 int
3256term_get_attr(buf_T *buf, linenr_T lnum, int col)
3257{
3258 term_T *term = buf->b_term;
3259 sb_line_T *line;
3260 cellattr_T *cellattr;
3261
3262 if (lnum > term->tl_scrollback.ga_len)
3263 cellattr = &term->tl_default_color;
3264 else
3265 {
3266 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3267 if (col < 0 || col >= line->sb_cols)
3268 cellattr = &line->sb_fill_attr;
3269 else
3270 cellattr = line->sb_cells + col;
3271 }
3272 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3273}
3274
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003275/*
3276 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003277 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278 */
3279 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003280cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003281{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003282 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283}
3284
3285/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003286 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 */
3288 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003289init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 VTermColor *fg, *bg;
3292 int fgval, bgval;
3293 int id;
3294
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003295 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3296 term->tl_default_color.width = 1;
3297 fg = &term->tl_default_color.fg;
3298 bg = &term->tl_default_color.bg;
3299
3300 /* Vterm uses a default black background. Set it to white when
3301 * 'background' is "light". */
3302 if (*p_bg == 'l')
3303 {
3304 fgval = 0;
3305 bgval = 255;
3306 }
3307 else
3308 {
3309 fgval = 255;
3310 bgval = 0;
3311 }
3312 fg->red = fg->green = fg->blue = fgval;
3313 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003314 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315
3316 /* The "Terminal" highlight group overrules the defaults. */
3317 id = syn_name2id((char_u *)"Terminal");
3318
Bram Moolenaar46359e12017-11-29 22:33:38 +01003319 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003320#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3321 if (0
3322# ifdef FEAT_GUI
3323 || gui.in_use
3324# endif
3325# ifdef FEAT_TERMGUICOLORS
3326 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003327# ifdef FEAT_VTP
3328 /* Finally get INVALCOLOR on this execution path */
3329 || (!p_tgc && t_colors >= 256)
3330# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003331# endif
3332 )
3333 {
3334 guicolor_T fg_rgb = INVALCOLOR;
3335 guicolor_T bg_rgb = INVALCOLOR;
3336
3337 if (id != 0)
3338 syn_id2colors(id, &fg_rgb, &bg_rgb);
3339
3340# ifdef FEAT_GUI
3341 if (gui.in_use)
3342 {
3343 if (fg_rgb == INVALCOLOR)
3344 fg_rgb = gui.norm_pixel;
3345 if (bg_rgb == INVALCOLOR)
3346 bg_rgb = gui.back_pixel;
3347 }
3348# ifdef FEAT_TERMGUICOLORS
3349 else
3350# endif
3351# endif
3352# ifdef FEAT_TERMGUICOLORS
3353 {
3354 if (fg_rgb == INVALCOLOR)
3355 fg_rgb = cterm_normal_fg_gui_color;
3356 if (bg_rgb == INVALCOLOR)
3357 bg_rgb = cterm_normal_bg_gui_color;
3358 }
3359# endif
3360 if (fg_rgb != INVALCOLOR)
3361 {
3362 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3363
3364 fg->red = (unsigned)(rgb >> 16);
3365 fg->green = (unsigned)(rgb >> 8) & 255;
3366 fg->blue = (unsigned)rgb & 255;
3367 }
3368 if (bg_rgb != INVALCOLOR)
3369 {
3370 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3371
3372 bg->red = (unsigned)(rgb >> 16);
3373 bg->green = (unsigned)(rgb >> 8) & 255;
3374 bg->blue = (unsigned)rgb & 255;
3375 }
3376 }
3377 else
3378#endif
3379 if (id != 0 && t_colors >= 16)
3380 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003381 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003382 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003383 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003384 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 else
3387 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003388#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003389 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003390#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003391
3392 /* In an MS-Windows console we know the normal colors. */
3393 if (cterm_normal_fg_color > 0)
3394 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003395 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003396# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003397 tmp = fg->red;
3398 fg->red = fg->blue;
3399 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003400# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003402# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003403 else
3404 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003405# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003406
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003407 if (cterm_normal_bg_color > 0)
3408 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003409 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003410# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 tmp = bg->red;
3412 bg->red = bg->blue;
3413 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003414# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003416# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003417 else
3418 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003419# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003421}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003423#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3424/*
3425 * Set the 16 ANSI colors from array of RGB values
3426 */
3427 static void
3428set_vterm_palette(VTerm *vterm, long_u *rgb)
3429{
3430 int index = 0;
3431 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003432
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003433 for (; index < 16; index++)
3434 {
3435 VTermColor color;
3436 color.red = (unsigned)(rgb[index] >> 16);
3437 color.green = (unsigned)(rgb[index] >> 8) & 255;
3438 color.blue = (unsigned)rgb[index] & 255;
3439 vterm_state_set_palette_color(state, index, &color);
3440 }
3441}
3442
3443/*
3444 * Set the ANSI color palette from a list of colors
3445 */
3446 static int
3447set_ansi_colors_list(VTerm *vterm, list_T *list)
3448{
3449 int n = 0;
3450 long_u rgb[16];
3451 listitem_T *li = list->lv_first;
3452
3453 for (; li != NULL && n < 16; li = li->li_next, n++)
3454 {
3455 char_u *color_name;
3456 guicolor_T guicolor;
3457
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003458 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003459 if (color_name == NULL)
3460 return FAIL;
3461
3462 guicolor = GUI_GET_COLOR(color_name);
3463 if (guicolor == INVALCOLOR)
3464 return FAIL;
3465
3466 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3467 }
3468
3469 if (n != 16 || li != NULL)
3470 return FAIL;
3471
3472 set_vterm_palette(vterm, rgb);
3473
3474 return OK;
3475}
3476
3477/*
3478 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3479 */
3480 static void
3481init_vterm_ansi_colors(VTerm *vterm)
3482{
3483 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3484
3485 if (var != NULL
3486 && (var->di_tv.v_type != VAR_LIST
3487 || var->di_tv.vval.v_list == NULL
3488 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003489 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003490}
3491#endif
3492
Bram Moolenaar52acb112018-03-18 19:20:22 +01003493/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003494 * Handles a "drop" command from the job in the terminal.
3495 * "item" is the file name, "item->li_next" may have options.
3496 */
3497 static void
3498handle_drop_command(listitem_T *item)
3499{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003500 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003501 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003502 int bufnr;
3503 win_T *wp;
3504 tabpage_T *tp;
3505 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003506 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003507
3508 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3509 FOR_ALL_TAB_WINDOWS(tp, wp)
3510 {
3511 if (wp->w_buffer->b_fnum == bufnr)
3512 {
3513 /* buffer is in a window already, go there */
3514 goto_tabpage_win(tp, wp);
3515 return;
3516 }
3517 }
3518
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003519 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003520
3521 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3522 && opt_item->li_tv.vval.v_dict != NULL)
3523 {
3524 dict_T *dict = opt_item->li_tv.vval.v_dict;
3525 char_u *p;
3526
Bram Moolenaar8f667172018-12-14 15:38:31 +01003527 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003528 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003529 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003530 if (p != NULL)
3531 {
3532 if (check_ff_value(p) == FAIL)
3533 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3534 else
3535 ea.force_ff = *p;
3536 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003537 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003538 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003539 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003540 if (p != NULL)
3541 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003542 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003543 if (ea.cmd != NULL)
3544 {
3545 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3546 ea.force_enc = 11;
3547 tofree = ea.cmd;
3548 }
3549 }
3550
Bram Moolenaar8f667172018-12-14 15:38:31 +01003551 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003552 if (p != NULL)
3553 get_bad_opt(p, &ea);
3554
3555 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3556 ea.force_bin = FORCE_BIN;
3557 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3558 ea.force_bin = FORCE_BIN;
3559 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3560 ea.force_bin = FORCE_NOBIN;
3561 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3562 ea.force_bin = FORCE_NOBIN;
3563 }
3564
3565 /* open in new window, like ":split fname" */
3566 if (ea.cmd == NULL)
3567 ea.cmd = (char_u *)"split";
3568 ea.arg = fname;
3569 ea.cmdidx = CMD_split;
3570 ex_splitview(&ea);
3571
3572 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003573}
3574
3575/*
3576 * Handles a function call from the job running in a terminal.
3577 * "item" is the function name, "item->li_next" has the arguments.
3578 */
3579 static void
3580handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3581{
3582 char_u *func;
3583 typval_T argvars[2];
3584 typval_T rettv;
3585 int doesrange;
3586
3587 if (item->li_next == NULL)
3588 {
3589 ch_log(channel, "Missing function arguments for call");
3590 return;
3591 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003592 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003593
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003594 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003595 {
3596 ch_log(channel, "Invalid function name: %s", func);
3597 return;
3598 }
3599
3600 argvars[0].v_type = VAR_NUMBER;
3601 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3602 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003603 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003604 2, argvars, /* argv_func */ NULL,
3605 /* firstline */ 1, /* lastline */ 1,
3606 &doesrange, /* evaluate */ TRUE,
3607 /* partial */ NULL, /* selfdict */ NULL) == OK)
3608 {
3609 clear_tv(&rettv);
3610 ch_log(channel, "Function %s called", func);
3611 }
3612 else
3613 ch_log(channel, "Calling function %s failed", func);
3614}
3615
3616/*
3617 * Called by libvterm when it cannot recognize an OSC sequence.
3618 * We recognize a terminal API command.
3619 */
3620 static int
3621parse_osc(const char *command, size_t cmdlen, void *user)
3622{
3623 term_T *term = (term_T *)user;
3624 js_read_T reader;
3625 typval_T tv;
3626 channel_T *channel = term->tl_job == NULL ? NULL
3627 : term->tl_job->jv_channel;
3628
3629 /* We recognize only OSC 5 1 ; {command} */
3630 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3631 return 0; /* not handled */
3632
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003633 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003634 if (reader.js_buf == NULL)
3635 return 1;
3636 reader.js_fill = NULL;
3637 reader.js_used = 0;
3638 if (json_decode(&reader, &tv, 0) == OK
3639 && tv.v_type == VAR_LIST
3640 && tv.vval.v_list != NULL)
3641 {
3642 listitem_T *item = tv.vval.v_list->lv_first;
3643
3644 if (item == NULL)
3645 ch_log(channel, "Missing command");
3646 else
3647 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003648 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003649
Bram Moolenaara997b452018-04-17 23:24:06 +02003650 /* Make sure an invoked command doesn't delete the buffer (and the
3651 * terminal) under our fingers. */
3652 ++term->tl_buffer->b_locked;
3653
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003654 item = item->li_next;
3655 if (item == NULL)
3656 ch_log(channel, "Missing argument for %s", cmd);
3657 else if (STRCMP(cmd, "drop") == 0)
3658 handle_drop_command(item);
3659 else if (STRCMP(cmd, "call") == 0)
3660 handle_call_command(term, channel, item);
3661 else
3662 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003663 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003664 }
3665 }
3666 else
3667 ch_log(channel, "Invalid JSON received");
3668
3669 vim_free(reader.js_buf);
3670 clear_tv(&tv);
3671 return 1;
3672}
3673
3674static VTermParserCallbacks parser_fallbacks = {
3675 NULL, /* text */
3676 NULL, /* control */
3677 NULL, /* escape */
3678 NULL, /* csi */
3679 parse_osc, /* osc */
3680 NULL, /* dcs */
3681 NULL /* resize */
3682};
3683
3684/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003685 * Use Vim's allocation functions for vterm so profiling works.
3686 */
3687 static void *
3688vterm_malloc(size_t size, void *data UNUSED)
3689{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003690 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003691}
3692
3693 static void
3694vterm_memfree(void *ptr, void *data UNUSED)
3695{
3696 vim_free(ptr);
3697}
3698
3699static VTermAllocatorFunctions vterm_allocator = {
3700 &vterm_malloc,
3701 &vterm_memfree
3702};
3703
3704/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003705 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003706 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003707 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003708 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003709create_vterm(term_T *term, int rows, int cols)
3710{
3711 VTerm *vterm;
3712 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003713 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003714 VTermValue value;
3715
Bram Moolenaar756ef112018-04-10 12:04:27 +02003716 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003717 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003718 if (vterm == NULL)
3719 return FAIL;
3720
3721 // Allocate screen and state here, so we can bail out if that fails.
3722 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003723 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003724 if (state == NULL || screen == NULL)
3725 {
3726 vterm_free(vterm);
3727 return FAIL;
3728 }
3729
Bram Moolenaar52acb112018-03-18 19:20:22 +01003730 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3731 /* TODO: depends on 'encoding'. */
3732 vterm_set_utf8(vterm, 1);
3733
3734 init_default_colors(term);
3735
3736 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003737 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003738 &term->tl_default_color.fg,
3739 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003740
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003741 if (t_colors >= 16)
3742 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3743
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003744 /* Required to initialize most things. */
3745 vterm_screen_reset(screen, 1 /* hard */);
3746
3747 /* Allow using alternate screen. */
3748 vterm_screen_enable_altscreen(screen, 1);
3749
3750 /* For unix do not use a blinking cursor. In an xterm this causes the
3751 * cursor to blink if it's blinking in the xterm.
3752 * For Windows we respect the system wide setting. */
3753#ifdef WIN3264
3754 if (GetCaretBlinkTime() == INFINITE)
3755 value.boolean = 0;
3756 else
3757 value.boolean = 1;
3758#else
3759 value.boolean = 0;
3760#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003761 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3762 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003763
3764 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003765}
3766
3767/*
3768 * Return the text to show for the buffer name and status.
3769 */
3770 char_u *
3771term_get_status_text(term_T *term)
3772{
3773 if (term->tl_status_text == NULL)
3774 {
3775 char_u *txt;
3776 size_t len;
3777
3778 if (term->tl_normal_mode)
3779 {
3780 if (term_job_running(term))
3781 txt = (char_u *)_("Terminal");
3782 else
3783 txt = (char_u *)_("Terminal-finished");
3784 }
3785 else if (term->tl_title != NULL)
3786 txt = term->tl_title;
3787 else if (term_none_open(term))
3788 txt = (char_u *)_("active");
3789 else if (term_job_running(term))
3790 txt = (char_u *)_("running");
3791 else
3792 txt = (char_u *)_("finished");
3793 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3794 term->tl_status_text = alloc((int)len);
3795 if (term->tl_status_text != NULL)
3796 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3797 term->tl_buffer->b_fname, txt);
3798 }
3799 return term->tl_status_text;
3800}
3801
3802/*
3803 * Mark references in jobs of terminals.
3804 */
3805 int
3806set_ref_in_term(int copyID)
3807{
3808 int abort = FALSE;
3809 term_T *term;
3810 typval_T tv;
3811
3812 for (term = first_term; term != NULL; term = term->tl_next)
3813 if (term->tl_job != NULL)
3814 {
3815 tv.v_type = VAR_JOB;
3816 tv.vval.v_job = term->tl_job;
3817 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3818 }
3819 return abort;
3820}
3821
3822/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003823 * Cache "Terminal" highlight group colors.
3824 */
3825 void
3826set_terminal_default_colors(int cterm_fg, int cterm_bg)
3827{
3828 term_default_cterm_fg = cterm_fg - 1;
3829 term_default_cterm_bg = cterm_bg - 1;
3830}
3831
3832/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003833 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003834 * Returns NULL when the buffer is not for a terminal window and logs a message
3835 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003836 */
3837 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003838term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003839{
3840 buf_T *buf;
3841
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003842 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003843 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01003844 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003845 --emsg_off;
3846 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003847 {
3848 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003849 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003850 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003851 return buf;
3852}
3853
Bram Moolenaard96ff162018-02-18 22:13:29 +01003854 static int
3855same_color(VTermColor *a, VTermColor *b)
3856{
3857 return a->red == b->red
3858 && a->green == b->green
3859 && a->blue == b->blue
3860 && a->ansi_index == b->ansi_index;
3861}
3862
3863 static void
3864dump_term_color(FILE *fd, VTermColor *color)
3865{
3866 fprintf(fd, "%02x%02x%02x%d",
3867 (int)color->red, (int)color->green, (int)color->blue,
3868 (int)color->ansi_index);
3869}
3870
3871/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003872 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003873 *
3874 * Each screen cell in full is:
3875 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3876 * {characters} is a space for an empty cell
3877 * For a double-width character "+" is changed to "*" and the next cell is
3878 * skipped.
3879 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3880 * when "&" use the same as the previous cell.
3881 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3882 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3883 * {color-idx} is a number from 0 to 255
3884 *
3885 * Screen cell with same width, attributes and color as the previous one:
3886 * |{characters}
3887 *
3888 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3889 *
3890 * Repeating the previous screen cell:
3891 * @{count}
3892 */
3893 void
3894f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3895{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003896 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003897 term_T *term;
3898 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003899 int max_height = 0;
3900 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003901 stat_T st;
3902 FILE *fd;
3903 VTermPos pos;
3904 VTermScreen *screen;
3905 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003906 VTermState *state;
3907 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003908
3909 if (check_restricted() || check_secure())
3910 return;
3911 if (buf == NULL)
3912 return;
3913 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02003914 if (term->tl_vterm == NULL)
3915 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003916 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02003917 return;
3918 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003919
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003920 if (argvars[2].v_type != VAR_UNKNOWN)
3921 {
3922 dict_T *d;
3923
3924 if (argvars[2].v_type != VAR_DICT)
3925 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003926 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003927 return;
3928 }
3929 d = argvars[2].vval.v_dict;
3930 if (d != NULL)
3931 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01003932 max_height = dict_get_number(d, (char_u *)"rows");
3933 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003934 }
3935 }
3936
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003937 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003938 if (fname == NULL)
3939 return;
3940 if (mch_stat((char *)fname, &st) >= 0)
3941 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003942 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003943 return;
3944 }
3945
Bram Moolenaard96ff162018-02-18 22:13:29 +01003946 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3947 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003948 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003949 return;
3950 }
3951
3952 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3953
3954 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003955 state = vterm_obtain_state(term->tl_vterm);
3956 vterm_state_get_cursorpos(state, &cursor_pos);
3957
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003958 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3959 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003960 {
3961 int repeat = 0;
3962
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003963 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3964 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003965 {
3966 VTermScreenCell cell;
3967 int same_attr;
3968 int same_chars = TRUE;
3969 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003970 int is_cursor_pos = (pos.col == cursor_pos.col
3971 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003972
3973 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3974 vim_memset(&cell, 0, sizeof(cell));
3975
3976 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3977 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003978 int c = cell.chars[i];
3979 int pc = prev_cell.chars[i];
3980
3981 /* For the first character NUL is the same as space. */
3982 if (i == 0)
3983 {
3984 c = (c == NUL) ? ' ' : c;
3985 pc = (pc == NUL) ? ' ' : pc;
3986 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02003987 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003988 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02003989 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003990 break;
3991 }
3992 same_attr = vtermAttr2hl(cell.attrs)
3993 == vtermAttr2hl(prev_cell.attrs)
3994 && same_color(&cell.fg, &prev_cell.fg)
3995 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003996 if (same_chars && cell.width == prev_cell.width && same_attr
3997 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003998 {
3999 ++repeat;
4000 }
4001 else
4002 {
4003 if (repeat > 0)
4004 {
4005 fprintf(fd, "@%d", repeat);
4006 repeat = 0;
4007 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004008 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004009
4010 if (cell.chars[0] == NUL)
4011 fputs(" ", fd);
4012 else
4013 {
4014 char_u charbuf[10];
4015 int len;
4016
4017 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4018 && cell.chars[i] != NUL; ++i)
4019 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004020 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004021 fwrite(charbuf, len, 1, fd);
4022 }
4023 }
4024
4025 /* When only the characters differ we don't write anything, the
4026 * following "|", "@" or NL will indicate using the same
4027 * attributes. */
4028 if (cell.width != prev_cell.width || !same_attr)
4029 {
4030 if (cell.width == 2)
4031 {
4032 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004033 }
4034 else
4035 fputs("+", fd);
4036
4037 if (same_attr)
4038 {
4039 fputs("&", fd);
4040 }
4041 else
4042 {
4043 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4044 if (same_color(&cell.fg, &prev_cell.fg))
4045 fputs("&", fd);
4046 else
4047 {
4048 fputs("#", fd);
4049 dump_term_color(fd, &cell.fg);
4050 }
4051 if (same_color(&cell.bg, &prev_cell.bg))
4052 fputs("&", fd);
4053 else
4054 {
4055 fputs("#", fd);
4056 dump_term_color(fd, &cell.bg);
4057 }
4058 }
4059 }
4060
4061 prev_cell = cell;
4062 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004063
4064 if (cell.width == 2)
4065 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004066 }
4067 if (repeat > 0)
4068 fprintf(fd, "@%d", repeat);
4069 fputs("\n", fd);
4070 }
4071
4072 fclose(fd);
4073}
4074
4075/*
4076 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4077 */
4078 static void
4079dump_is_corrupt(garray_T *gap)
4080{
4081 ga_concat(gap, (char_u *)"CORRUPT");
4082}
4083
4084 static void
4085append_cell(garray_T *gap, cellattr_T *cell)
4086{
4087 if (ga_grow(gap, 1) == OK)
4088 {
4089 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4090 ++gap->ga_len;
4091 }
4092}
4093
4094/*
4095 * Read the dump file from "fd" and append lines to the current buffer.
4096 * Return the cell width of the longest line.
4097 */
4098 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004099read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004100{
4101 int c;
4102 garray_T ga_text;
4103 garray_T ga_cell;
4104 char_u *prev_char = NULL;
4105 int attr = 0;
4106 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004107 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004108 term_T *term = curbuf->b_term;
4109 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004110 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004111
4112 ga_init2(&ga_text, 1, 90);
4113 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4114 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004115 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004116 cursor_pos->row = -1;
4117 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004118
4119 c = fgetc(fd);
4120 for (;;)
4121 {
4122 if (c == EOF)
4123 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004124 if (c == '\r')
4125 {
4126 // DOS line endings? Ignore.
4127 c = fgetc(fd);
4128 }
4129 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004130 {
4131 /* End of a line: append it to the buffer. */
4132 if (ga_text.ga_data == NULL)
4133 dump_is_corrupt(&ga_text);
4134 if (ga_grow(&term->tl_scrollback, 1) == OK)
4135 {
4136 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4137 + term->tl_scrollback.ga_len;
4138
4139 if (max_cells < ga_cell.ga_len)
4140 max_cells = ga_cell.ga_len;
4141 line->sb_cols = ga_cell.ga_len;
4142 line->sb_cells = ga_cell.ga_data;
4143 line->sb_fill_attr = term->tl_default_color;
4144 ++term->tl_scrollback.ga_len;
4145 ga_init(&ga_cell);
4146
4147 ga_append(&ga_text, NUL);
4148 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4149 ga_text.ga_len, FALSE);
4150 }
4151 else
4152 ga_clear(&ga_cell);
4153 ga_text.ga_len = 0;
4154
4155 c = fgetc(fd);
4156 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004157 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004158 {
4159 int prev_len = ga_text.ga_len;
4160
Bram Moolenaar9271d052018-02-25 21:39:46 +01004161 if (c == '>')
4162 {
4163 if (cursor_pos->row != -1)
4164 dump_is_corrupt(&ga_text); /* duplicate cursor */
4165 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4166 cursor_pos->col = ga_cell.ga_len;
4167 }
4168
Bram Moolenaard96ff162018-02-18 22:13:29 +01004169 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4170 c = fgetc(fd);
4171 if (c != EOF)
4172 ga_append(&ga_text, c);
4173 for (;;)
4174 {
4175 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004176 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004177 || c == EOF || c == '\n')
4178 break;
4179 ga_append(&ga_text, c);
4180 }
4181
4182 /* save the character for repeating it */
4183 vim_free(prev_char);
4184 if (ga_text.ga_data != NULL)
4185 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4186 ga_text.ga_len - prev_len);
4187
Bram Moolenaar9271d052018-02-25 21:39:46 +01004188 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004189 {
4190 /* use all attributes from previous cell */
4191 }
4192 else if (c == '+' || c == '*')
4193 {
4194 int is_bg;
4195
4196 cell.width = c == '+' ? 1 : 2;
4197
4198 c = fgetc(fd);
4199 if (c == '&')
4200 {
4201 /* use same attr as previous cell */
4202 c = fgetc(fd);
4203 }
4204 else if (isdigit(c))
4205 {
4206 /* get the decimal attribute */
4207 attr = 0;
4208 while (isdigit(c))
4209 {
4210 attr = attr * 10 + (c - '0');
4211 c = fgetc(fd);
4212 }
4213 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004214
4215 /* is_bg == 0: fg, is_bg == 1: bg */
4216 for (is_bg = 0; is_bg <= 1; ++is_bg)
4217 {
4218 if (c == '&')
4219 {
4220 /* use same color as previous cell */
4221 c = fgetc(fd);
4222 }
4223 else if (c == '#')
4224 {
4225 int red, green, blue, index = 0;
4226
4227 c = fgetc(fd);
4228 red = hex2nr(c);
4229 c = fgetc(fd);
4230 red = (red << 4) + hex2nr(c);
4231 c = fgetc(fd);
4232 green = hex2nr(c);
4233 c = fgetc(fd);
4234 green = (green << 4) + hex2nr(c);
4235 c = fgetc(fd);
4236 blue = hex2nr(c);
4237 c = fgetc(fd);
4238 blue = (blue << 4) + hex2nr(c);
4239 c = fgetc(fd);
4240 if (!isdigit(c))
4241 dump_is_corrupt(&ga_text);
4242 while (isdigit(c))
4243 {
4244 index = index * 10 + (c - '0');
4245 c = fgetc(fd);
4246 }
4247
4248 if (is_bg)
4249 {
4250 cell.bg.red = red;
4251 cell.bg.green = green;
4252 cell.bg.blue = blue;
4253 cell.bg.ansi_index = index;
4254 }
4255 else
4256 {
4257 cell.fg.red = red;
4258 cell.fg.green = green;
4259 cell.fg.blue = blue;
4260 cell.fg.ansi_index = index;
4261 }
4262 }
4263 else
4264 dump_is_corrupt(&ga_text);
4265 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004266 }
4267 else
4268 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004269 }
4270 else
4271 dump_is_corrupt(&ga_text);
4272
4273 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004274 if (cell.width == 2)
4275 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004276 }
4277 else if (c == '@')
4278 {
4279 if (prev_char == NULL)
4280 dump_is_corrupt(&ga_text);
4281 else
4282 {
4283 int count = 0;
4284
4285 /* repeat previous character, get the count */
4286 for (;;)
4287 {
4288 c = fgetc(fd);
4289 if (!isdigit(c))
4290 break;
4291 count = count * 10 + (c - '0');
4292 }
4293
4294 while (count-- > 0)
4295 {
4296 ga_concat(&ga_text, prev_char);
4297 append_cell(&ga_cell, &cell);
4298 }
4299 }
4300 }
4301 else
4302 {
4303 dump_is_corrupt(&ga_text);
4304 c = fgetc(fd);
4305 }
4306 }
4307
4308 if (ga_text.ga_len > 0)
4309 {
4310 /* trailing characters after last NL */
4311 dump_is_corrupt(&ga_text);
4312 ga_append(&ga_text, NUL);
4313 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4314 ga_text.ga_len, FALSE);
4315 }
4316
4317 ga_clear(&ga_text);
4318 vim_free(prev_char);
4319
4320 return max_cells;
4321}
4322
4323/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004324 * Return an allocated string with at least "text_width" "=" characters and
4325 * "fname" inserted in the middle.
4326 */
4327 static char_u *
4328get_separator(int text_width, char_u *fname)
4329{
4330 int width = MAX(text_width, curwin->w_width);
4331 char_u *textline;
4332 int fname_size;
4333 char_u *p = fname;
4334 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004335 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004336
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004337 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004338 if (textline == NULL)
4339 return NULL;
4340
4341 fname_size = vim_strsize(fname);
4342 if (fname_size < width - 8)
4343 {
4344 /* enough room, don't use the full window width */
4345 width = MAX(text_width, fname_size + 8);
4346 }
4347 else if (fname_size > width - 8)
4348 {
4349 /* full name doesn't fit, use only the tail */
4350 p = gettail(fname);
4351 fname_size = vim_strsize(p);
4352 }
4353 /* skip characters until the name fits */
4354 while (fname_size > width - 8)
4355 {
4356 p += (*mb_ptr2len)(p);
4357 fname_size = vim_strsize(p);
4358 }
4359
4360 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4361 textline[i] = '=';
4362 textline[i++] = ' ';
4363
4364 STRCPY(textline + i, p);
4365 off = STRLEN(textline);
4366 textline[off] = ' ';
4367 for (i = 1; i < (width - fname_size) / 2; ++i)
4368 textline[off + i] = '=';
4369 textline[off + i] = NUL;
4370
4371 return textline;
4372}
4373
4374/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004375 * Common for "term_dumpdiff()" and "term_dumpload()".
4376 */
4377 static void
4378term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4379{
4380 jobopt_T opt;
4381 buf_T *buf;
4382 char_u buf1[NUMBUFLEN];
4383 char_u buf2[NUMBUFLEN];
4384 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004385 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004386 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004387 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004388 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004389 char_u *textline = NULL;
4390
4391 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004392 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004393 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004394 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004395 if (fname1 == NULL || (do_diff && fname2 == NULL))
4396 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004397 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004398 return;
4399 }
4400 fd1 = mch_fopen((char *)fname1, READBIN);
4401 if (fd1 == NULL)
4402 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004403 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004404 return;
4405 }
4406 if (do_diff)
4407 {
4408 fd2 = mch_fopen((char *)fname2, READBIN);
4409 if (fd2 == NULL)
4410 {
4411 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004412 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004413 return;
4414 }
4415 }
4416
4417 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004418 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4419 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4420 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4421 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4422 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004423
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004424 if (opt.jo_term_name == NULL)
4425 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004426 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004427
Bram Moolenaarb571c632018-03-21 22:27:59 +01004428 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004429 if (fname_tofree != NULL)
4430 {
4431 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4432 opt.jo_term_name = fname_tofree;
4433 }
4434 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004435
Bram Moolenaar13568252018-03-16 20:46:58 +01004436 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004437 if (buf != NULL && buf->b_term != NULL)
4438 {
4439 int i;
4440 linenr_T bot_lnum;
4441 linenr_T lnum;
4442 term_T *term = buf->b_term;
4443 int width;
4444 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004445 VTermPos cursor_pos1;
4446 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004447
Bram Moolenaar52acb112018-03-18 19:20:22 +01004448 init_default_colors(term);
4449
Bram Moolenaard96ff162018-02-18 22:13:29 +01004450 rettv->vval.v_number = buf->b_fnum;
4451
4452 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004453 width = read_dump_file(fd1, &cursor_pos1);
4454
4455 /* position the cursor */
4456 if (cursor_pos1.row >= 0)
4457 {
4458 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4459 coladvance(cursor_pos1.col);
4460 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004461
4462 /* Delete the empty line that was in the empty buffer. */
4463 ml_delete(1, FALSE);
4464
4465 /* For term_dumpload() we are done here. */
4466 if (!do_diff)
4467 goto theend;
4468
4469 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4470
Bram Moolenaar4a696342018-04-05 18:45:26 +02004471 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004472 if (textline == NULL)
4473 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004474 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4475 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4476 vim_free(textline);
4477
4478 textline = get_separator(width, fname2);
4479 if (textline == NULL)
4480 goto theend;
4481 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4482 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004483 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004484
4485 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004486 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004487 if (width2 > width)
4488 {
4489 vim_free(textline);
4490 textline = alloc(width2 + 1);
4491 if (textline == NULL)
4492 goto theend;
4493 width = width2;
4494 textline[width] = NUL;
4495 }
4496 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4497
4498 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4499 {
4500 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4501 {
4502 /* bottom part has fewer rows, fill with "-" */
4503 for (i = 0; i < width; ++i)
4504 textline[i] = '-';
4505 }
4506 else
4507 {
4508 char_u *line1;
4509 char_u *line2;
4510 char_u *p1;
4511 char_u *p2;
4512 int col;
4513 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4514 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4515 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4516 ->sb_cells;
4517
4518 /* Make a copy, getting the second line will invalidate it. */
4519 line1 = vim_strsave(ml_get(lnum));
4520 if (line1 == NULL)
4521 break;
4522 p1 = line1;
4523
4524 line2 = ml_get(lnum + bot_lnum);
4525 p2 = line2;
4526 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4527 {
4528 int len1 = utfc_ptr2len(p1);
4529 int len2 = utfc_ptr2len(p2);
4530
4531 textline[col] = ' ';
4532 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004533 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004534 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004535 else if (lnum == cursor_pos1.row + 1
4536 && col == cursor_pos1.col
4537 && (cursor_pos1.row != cursor_pos2.row
4538 || cursor_pos1.col != cursor_pos2.col))
4539 /* cursor in first but not in second */
4540 textline[col] = '>';
4541 else if (lnum == cursor_pos2.row + 1
4542 && col == cursor_pos2.col
4543 && (cursor_pos1.row != cursor_pos2.row
4544 || cursor_pos1.col != cursor_pos2.col))
4545 /* cursor in second but not in first */
4546 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004547 else if (cellattr1 != NULL && cellattr2 != NULL)
4548 {
4549 if ((cellattr1 + col)->width
4550 != (cellattr2 + col)->width)
4551 textline[col] = 'w';
4552 else if (!same_color(&(cellattr1 + col)->fg,
4553 &(cellattr2 + col)->fg))
4554 textline[col] = 'f';
4555 else if (!same_color(&(cellattr1 + col)->bg,
4556 &(cellattr2 + col)->bg))
4557 textline[col] = 'b';
4558 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4559 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4560 textline[col] = 'a';
4561 }
4562 p1 += len1;
4563 p2 += len2;
4564 /* TODO: handle different width */
4565 }
4566 vim_free(line1);
4567
4568 while (col < width)
4569 {
4570 if (*p1 == NUL && *p2 == NUL)
4571 textline[col] = '?';
4572 else if (*p1 == NUL)
4573 {
4574 textline[col] = '+';
4575 p2 += utfc_ptr2len(p2);
4576 }
4577 else
4578 {
4579 textline[col] = '-';
4580 p1 += utfc_ptr2len(p1);
4581 }
4582 ++col;
4583 }
4584 }
4585 if (add_empty_scrollback(term, &term->tl_default_color,
4586 term->tl_top_diff_rows) == OK)
4587 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4588 ++bot_lnum;
4589 }
4590
4591 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4592 {
4593 /* bottom part has more rows, fill with "+" */
4594 for (i = 0; i < width; ++i)
4595 textline[i] = '+';
4596 if (add_empty_scrollback(term, &term->tl_default_color,
4597 term->tl_top_diff_rows) == OK)
4598 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4599 ++lnum;
4600 ++bot_lnum;
4601 }
4602
4603 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004604
4605 /* looks better without wrapping */
4606 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004607 }
4608
4609theend:
4610 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004611 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004612 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004613 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004614 fclose(fd2);
4615}
4616
4617/*
4618 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4619 * bottom files.
4620 * Return FAIL when this is not possible.
4621 */
4622 int
4623term_swap_diff()
4624{
4625 term_T *term = curbuf->b_term;
4626 linenr_T line_count;
4627 linenr_T top_rows;
4628 linenr_T bot_rows;
4629 linenr_T bot_start;
4630 linenr_T lnum;
4631 char_u *p;
4632 sb_line_T *sb_line;
4633
4634 if (term == NULL
4635 || !term_is_finished(curbuf)
4636 || term->tl_top_diff_rows == 0
4637 || term->tl_scrollback.ga_len == 0)
4638 return FAIL;
4639
4640 line_count = curbuf->b_ml.ml_line_count;
4641 top_rows = term->tl_top_diff_rows;
4642 bot_rows = term->tl_bot_diff_rows;
4643 bot_start = line_count - bot_rows;
4644 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4645
4646 /* move lines from top to above the bottom part */
4647 for (lnum = 1; lnum <= top_rows; ++lnum)
4648 {
4649 p = vim_strsave(ml_get(1));
4650 if (p == NULL)
4651 return OK;
4652 ml_append(bot_start, p, 0, FALSE);
4653 ml_delete(1, FALSE);
4654 vim_free(p);
4655 }
4656
4657 /* move lines from bottom to the top */
4658 for (lnum = 1; lnum <= bot_rows; ++lnum)
4659 {
4660 p = vim_strsave(ml_get(bot_start + lnum));
4661 if (p == NULL)
4662 return OK;
4663 ml_delete(bot_start + lnum, FALSE);
4664 ml_append(lnum - 1, p, 0, FALSE);
4665 vim_free(p);
4666 }
4667
4668 if (top_rows == bot_rows)
4669 {
4670 /* rows counts are equal, can swap cell properties */
4671 for (lnum = 0; lnum < top_rows; ++lnum)
4672 {
4673 sb_line_T temp;
4674
4675 temp = *(sb_line + lnum);
4676 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4677 *(sb_line + bot_start + lnum) = temp;
4678 }
4679 }
4680 else
4681 {
4682 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4683 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4684
4685 /* need to copy cell properties into temp memory */
4686 if (temp != NULL)
4687 {
4688 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4689 mch_memmove(term->tl_scrollback.ga_data,
4690 temp + bot_start,
4691 sizeof(sb_line_T) * bot_rows);
4692 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4693 temp + top_rows,
4694 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4695 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4696 + line_count - top_rows,
4697 temp,
4698 sizeof(sb_line_T) * top_rows);
4699 vim_free(temp);
4700 }
4701 }
4702
4703 term->tl_top_diff_rows = bot_rows;
4704 term->tl_bot_diff_rows = top_rows;
4705
4706 update_screen(NOT_VALID);
4707 return OK;
4708}
4709
4710/*
4711 * "term_dumpdiff(filename, filename, options)" function
4712 */
4713 void
4714f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4715{
4716 term_load_dump(argvars, rettv, TRUE);
4717}
4718
4719/*
4720 * "term_dumpload(filename, options)" function
4721 */
4722 void
4723f_term_dumpload(typval_T *argvars, typval_T *rettv)
4724{
4725 term_load_dump(argvars, rettv, FALSE);
4726}
4727
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004728/*
4729 * "term_getaltscreen(buf)" function
4730 */
4731 void
4732f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4733{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004734 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004735
4736 if (buf == NULL)
4737 return;
4738 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4739}
4740
4741/*
4742 * "term_getattr(attr, name)" function
4743 */
4744 void
4745f_term_getattr(typval_T *argvars, typval_T *rettv)
4746{
4747 int attr;
4748 size_t i;
4749 char_u *name;
4750
4751 static struct {
4752 char *name;
4753 int attr;
4754 } attrs[] = {
4755 {"bold", HL_BOLD},
4756 {"italic", HL_ITALIC},
4757 {"underline", HL_UNDERLINE},
4758 {"strike", HL_STRIKETHROUGH},
4759 {"reverse", HL_INVERSE},
4760 };
4761
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004762 attr = tv_get_number(&argvars[0]);
4763 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004764 if (name == NULL)
4765 return;
4766
4767 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4768 if (STRCMP(name, attrs[i].name) == 0)
4769 {
4770 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4771 break;
4772 }
4773}
4774
4775/*
4776 * "term_getcursor(buf)" function
4777 */
4778 void
4779f_term_getcursor(typval_T *argvars, typval_T *rettv)
4780{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004781 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004782 term_T *term;
4783 list_T *l;
4784 dict_T *d;
4785
4786 if (rettv_list_alloc(rettv) == FAIL)
4787 return;
4788 if (buf == NULL)
4789 return;
4790 term = buf->b_term;
4791
4792 l = rettv->vval.v_list;
4793 list_append_number(l, term->tl_cursor_pos.row + 1);
4794 list_append_number(l, term->tl_cursor_pos.col + 1);
4795
4796 d = dict_alloc();
4797 if (d != NULL)
4798 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02004799 dict_add_number(d, "visible", term->tl_cursor_visible);
4800 dict_add_number(d, "blink", blink_state_is_inverted()
4801 ? !term->tl_cursor_blink : term->tl_cursor_blink);
4802 dict_add_number(d, "shape", term->tl_cursor_shape);
4803 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004804 list_append_dict(l, d);
4805 }
4806}
4807
4808/*
4809 * "term_getjob(buf)" function
4810 */
4811 void
4812f_term_getjob(typval_T *argvars, typval_T *rettv)
4813{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004814 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004815
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004816 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004817 {
4818 rettv->v_type = VAR_SPECIAL;
4819 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004820 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004821 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004822
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004823 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004824 rettv->vval.v_job = buf->b_term->tl_job;
4825 if (rettv->vval.v_job != NULL)
4826 ++rettv->vval.v_job->jv_refcount;
4827}
4828
4829 static int
4830get_row_number(typval_T *tv, term_T *term)
4831{
4832 if (tv->v_type == VAR_STRING
4833 && tv->vval.v_string != NULL
4834 && STRCMP(tv->vval.v_string, ".") == 0)
4835 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004836 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004837}
4838
4839/*
4840 * "term_getline(buf, row)" function
4841 */
4842 void
4843f_term_getline(typval_T *argvars, typval_T *rettv)
4844{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004845 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004846 term_T *term;
4847 int row;
4848
4849 rettv->v_type = VAR_STRING;
4850 if (buf == NULL)
4851 return;
4852 term = buf->b_term;
4853 row = get_row_number(&argvars[1], term);
4854
4855 if (term->tl_vterm == NULL)
4856 {
4857 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4858
4859 /* vterm is finished, get the text from the buffer */
4860 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4861 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4862 }
4863 else
4864 {
4865 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4866 VTermRect rect;
4867 int len;
4868 char_u *p;
4869
4870 if (row < 0 || row >= term->tl_rows)
4871 return;
4872 len = term->tl_cols * MB_MAXBYTES + 1;
4873 p = alloc(len);
4874 if (p == NULL)
4875 return;
4876 rettv->vval.v_string = p;
4877
4878 rect.start_col = 0;
4879 rect.end_col = term->tl_cols;
4880 rect.start_row = row;
4881 rect.end_row = row + 1;
4882 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4883 }
4884}
4885
4886/*
4887 * "term_getscrolled(buf)" function
4888 */
4889 void
4890f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4891{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004892 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004893
4894 if (buf == NULL)
4895 return;
4896 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4897}
4898
4899/*
4900 * "term_getsize(buf)" function
4901 */
4902 void
4903f_term_getsize(typval_T *argvars, typval_T *rettv)
4904{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004905 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004906 list_T *l;
4907
4908 if (rettv_list_alloc(rettv) == FAIL)
4909 return;
4910 if (buf == NULL)
4911 return;
4912
4913 l = rettv->vval.v_list;
4914 list_append_number(l, buf->b_term->tl_rows);
4915 list_append_number(l, buf->b_term->tl_cols);
4916}
4917
4918/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004919 * "term_setsize(buf, rows, cols)" function
4920 */
4921 void
4922f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4923{
4924 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4925 term_T *term;
4926 varnumber_T rows, cols;
4927
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004928 if (buf == NULL)
4929 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004930 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004931 return;
4932 }
4933 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004934 return;
4935 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004936 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02004937 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004938 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02004939 cols = cols <= 0 ? term->tl_cols : cols;
4940 vterm_set_size(term->tl_vterm, rows, cols);
4941 /* handle_resize() will resize the windows */
4942
4943 /* Get and remember the size we ended up with. Update the pty. */
4944 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4945 term_report_winsize(term, term->tl_rows, term->tl_cols);
4946}
4947
4948/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004949 * "term_getstatus(buf)" function
4950 */
4951 void
4952f_term_getstatus(typval_T *argvars, typval_T *rettv)
4953{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004954 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004955 term_T *term;
4956 char_u val[100];
4957
4958 rettv->v_type = VAR_STRING;
4959 if (buf == NULL)
4960 return;
4961 term = buf->b_term;
4962
4963 if (term_job_running(term))
4964 STRCPY(val, "running");
4965 else
4966 STRCPY(val, "finished");
4967 if (term->tl_normal_mode)
4968 STRCAT(val, ",normal");
4969 rettv->vval.v_string = vim_strsave(val);
4970}
4971
4972/*
4973 * "term_gettitle(buf)" function
4974 */
4975 void
4976f_term_gettitle(typval_T *argvars, typval_T *rettv)
4977{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004978 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004979
4980 rettv->v_type = VAR_STRING;
4981 if (buf == NULL)
4982 return;
4983
4984 if (buf->b_term->tl_title != NULL)
4985 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4986}
4987
4988/*
4989 * "term_gettty(buf)" function
4990 */
4991 void
4992f_term_gettty(typval_T *argvars, typval_T *rettv)
4993{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004994 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004995 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004996 int num = 0;
4997
4998 rettv->v_type = VAR_STRING;
4999 if (buf == NULL)
5000 return;
5001 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005002 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005003
5004 switch (num)
5005 {
5006 case 0:
5007 if (buf->b_term->tl_job != NULL)
5008 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005009 break;
5010 case 1:
5011 if (buf->b_term->tl_job != NULL)
5012 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005013 break;
5014 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005015 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005016 return;
5017 }
5018 if (p != NULL)
5019 rettv->vval.v_string = vim_strsave(p);
5020}
5021
5022/*
5023 * "term_list()" function
5024 */
5025 void
5026f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5027{
5028 term_T *tp;
5029 list_T *l;
5030
5031 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5032 return;
5033
5034 l = rettv->vval.v_list;
5035 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5036 if (tp != NULL && tp->tl_buffer != NULL)
5037 if (list_append_number(l,
5038 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5039 return;
5040}
5041
5042/*
5043 * "term_scrape(buf, row)" function
5044 */
5045 void
5046f_term_scrape(typval_T *argvars, typval_T *rettv)
5047{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005048 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005049 VTermScreen *screen = NULL;
5050 VTermPos pos;
5051 list_T *l;
5052 term_T *term;
5053 char_u *p;
5054 sb_line_T *line;
5055
5056 if (rettv_list_alloc(rettv) == FAIL)
5057 return;
5058 if (buf == NULL)
5059 return;
5060 term = buf->b_term;
5061
5062 l = rettv->vval.v_list;
5063 pos.row = get_row_number(&argvars[1], term);
5064
5065 if (term->tl_vterm != NULL)
5066 {
5067 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005068 if (screen == NULL) // can't really happen
5069 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005070 p = NULL;
5071 line = NULL;
5072 }
5073 else
5074 {
5075 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5076
5077 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5078 return;
5079 p = ml_get_buf(buf, lnum + 1, FALSE);
5080 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5081 }
5082
5083 for (pos.col = 0; pos.col < term->tl_cols; )
5084 {
5085 dict_T *dcell;
5086 int width;
5087 VTermScreenCellAttrs attrs;
5088 VTermColor fg, bg;
5089 char_u rgb[8];
5090 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5091 int off = 0;
5092 int i;
5093
5094 if (screen == NULL)
5095 {
5096 cellattr_T *cellattr;
5097 int len;
5098
5099 /* vterm has finished, get the cell from scrollback */
5100 if (pos.col >= line->sb_cols)
5101 break;
5102 cellattr = line->sb_cells + pos.col;
5103 width = cellattr->width;
5104 attrs = cellattr->attrs;
5105 fg = cellattr->fg;
5106 bg = cellattr->bg;
5107 len = MB_PTR2LEN(p);
5108 mch_memmove(mbs, p, len);
5109 mbs[len] = NUL;
5110 p += len;
5111 }
5112 else
5113 {
5114 VTermScreenCell cell;
5115 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5116 break;
5117 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5118 {
5119 if (cell.chars[i] == 0)
5120 break;
5121 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5122 }
5123 mbs[off] = NUL;
5124 width = cell.width;
5125 attrs = cell.attrs;
5126 fg = cell.fg;
5127 bg = cell.bg;
5128 }
5129 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005130 if (dcell == NULL)
5131 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005132 list_append_dict(l, dcell);
5133
Bram Moolenaare0be1672018-07-08 16:50:37 +02005134 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005135
5136 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5137 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005138 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005139 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5140 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005141 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005142
Bram Moolenaare0be1672018-07-08 16:50:37 +02005143 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5144 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005145
5146 ++pos.col;
5147 if (width == 2)
5148 ++pos.col;
5149 }
5150}
5151
5152/*
5153 * "term_sendkeys(buf, keys)" function
5154 */
5155 void
5156f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5157{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005158 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005159 char_u *msg;
5160 term_T *term;
5161
5162 rettv->v_type = VAR_UNKNOWN;
5163 if (buf == NULL)
5164 return;
5165
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005166 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005167 if (msg == NULL)
5168 return;
5169 term = buf->b_term;
5170 if (term->tl_vterm == NULL)
5171 return;
5172
5173 while (*msg != NUL)
5174 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005175 int c;
5176
5177 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5178 {
5179 c = TO_SPECIAL(msg[1], msg[2]);
5180 msg += 3;
5181 }
5182 else
5183 {
5184 c = PTR2CHAR(msg);
5185 msg += MB_CPTR2LEN(msg);
5186 }
5187 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005188 }
5189}
5190
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005191#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5192/*
5193 * "term_getansicolors(buf)" function
5194 */
5195 void
5196f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5197{
5198 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5199 term_T *term;
5200 VTermState *state;
5201 VTermColor color;
5202 char_u hexbuf[10];
5203 int index;
5204 list_T *list;
5205
5206 if (rettv_list_alloc(rettv) == FAIL)
5207 return;
5208
5209 if (buf == NULL)
5210 return;
5211 term = buf->b_term;
5212 if (term->tl_vterm == NULL)
5213 return;
5214
5215 list = rettv->vval.v_list;
5216 state = vterm_obtain_state(term->tl_vterm);
5217 for (index = 0; index < 16; index++)
5218 {
5219 vterm_state_get_palette_color(state, index, &color);
5220 sprintf((char *)hexbuf, "#%02x%02x%02x",
5221 color.red, color.green, color.blue);
5222 if (list_append_string(list, hexbuf, 7) == FAIL)
5223 return;
5224 }
5225}
5226
5227/*
5228 * "term_setansicolors(buf, list)" function
5229 */
5230 void
5231f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5232{
5233 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5234 term_T *term;
5235
5236 if (buf == NULL)
5237 return;
5238 term = buf->b_term;
5239 if (term->tl_vterm == NULL)
5240 return;
5241
5242 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5243 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005244 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005245 return;
5246 }
5247
5248 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005249 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005250}
5251#endif
5252
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005253/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005254 * "term_setrestore(buf, command)" function
5255 */
5256 void
5257f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5258{
5259#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005260 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005261 term_T *term;
5262 char_u *cmd;
5263
5264 if (buf == NULL)
5265 return;
5266 term = buf->b_term;
5267 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005268 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005269 if (cmd != NULL)
5270 term->tl_command = vim_strsave(cmd);
5271 else
5272 term->tl_command = NULL;
5273#endif
5274}
5275
5276/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005277 * "term_setkill(buf, how)" function
5278 */
5279 void
5280f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5281{
5282 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5283 term_T *term;
5284 char_u *how;
5285
5286 if (buf == NULL)
5287 return;
5288 term = buf->b_term;
5289 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005290 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005291 if (how != NULL)
5292 term->tl_kill = vim_strsave(how);
5293 else
5294 term->tl_kill = NULL;
5295}
5296
5297/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005298 * "term_start(command, options)" function
5299 */
5300 void
5301f_term_start(typval_T *argvars, typval_T *rettv)
5302{
5303 jobopt_T opt;
5304 buf_T *buf;
5305
5306 init_job_options(&opt);
5307 if (argvars[1].v_type != VAR_UNKNOWN
5308 && get_job_options(&argvars[1], &opt,
5309 JO_TIMEOUT_ALL + JO_STOPONEXIT
5310 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5311 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5312 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5313 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005314 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005315 + JO2_NORESTORE + JO2_TERM_KILL
5316 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005317 return;
5318
Bram Moolenaar13568252018-03-16 20:46:58 +01005319 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005320
5321 if (buf != NULL && buf->b_term != NULL)
5322 rettv->vval.v_number = buf->b_fnum;
5323}
5324
5325/*
5326 * "term_wait" function
5327 */
5328 void
5329f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5330{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005331 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005332
5333 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005334 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005335 if (buf->b_term->tl_job == NULL)
5336 {
5337 ch_log(NULL, "term_wait(): no job to wait for");
5338 return;
5339 }
5340 if (buf->b_term->tl_job->jv_channel == NULL)
5341 /* channel is closed, nothing to do */
5342 return;
5343
5344 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005345 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005346 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5347 {
5348 /* The job is dead, keep reading channel I/O until the channel is
5349 * closed. buf->b_term may become NULL if the terminal was closed while
5350 * waiting. */
5351 ch_log(NULL, "term_wait(): waiting for channel to close");
5352 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5353 {
5354 mch_check_messages();
5355 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005356 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005357 if (!buf_valid(buf))
5358 /* If the terminal is closed when the channel is closed the
5359 * buffer disappears. */
5360 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005361 }
5362 mch_check_messages();
5363 parse_queued_messages();
5364 }
5365 else
5366 {
5367 long wait = 10L;
5368
5369 mch_check_messages();
5370 parse_queued_messages();
5371
5372 /* Wait for some time for any channel I/O. */
5373 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005374 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005375 ui_delay(wait, TRUE);
5376 mch_check_messages();
5377
5378 /* Flushing messages on channels is hopefully sufficient.
5379 * TODO: is there a better way? */
5380 parse_queued_messages();
5381 }
5382}
5383
5384/*
5385 * Called when a channel has sent all the lines to a terminal.
5386 * Send a CTRL-D to mark the end of the text.
5387 */
5388 void
5389term_send_eof(channel_T *ch)
5390{
5391 term_T *term;
5392
5393 for (term = first_term; term != NULL; term = term->tl_next)
5394 if (term->tl_job == ch->ch_job)
5395 {
5396 if (term->tl_eof_chars != NULL)
5397 {
5398 channel_send(ch, PART_IN, term->tl_eof_chars,
5399 (int)STRLEN(term->tl_eof_chars), NULL);
5400 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5401 }
5402# ifdef WIN3264
5403 else
5404 /* Default: CTRL-D */
5405 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5406# endif
5407 }
5408}
5409
Bram Moolenaar113e1072019-01-20 15:30:40 +01005410#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005411 job_T *
5412term_getjob(term_T *term)
5413{
5414 return term != NULL ? term->tl_job : NULL;
5415}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005416#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005417
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005418# if defined(WIN3264) || defined(PROTO)
5419
5420/**************************************
5421 * 2. MS-Windows implementation.
5422 */
5423
5424# ifndef PROTO
5425
5426#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5427#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005428#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429
5430void* (*winpty_config_new)(UINT64, void*);
5431void* (*winpty_open)(void*, void*);
5432void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5433BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5434void (*winpty_config_set_mouse_mode)(void*, int);
5435void (*winpty_config_set_initial_size)(void*, int, int);
5436LPCWSTR (*winpty_conin_name)(void*);
5437LPCWSTR (*winpty_conout_name)(void*);
5438LPCWSTR (*winpty_conerr_name)(void*);
5439void (*winpty_free)(void*);
5440void (*winpty_config_free)(void*);
5441void (*winpty_spawn_config_free)(void*);
5442void (*winpty_error_free)(void*);
5443LPCWSTR (*winpty_error_msg)(void*);
5444BOOL (*winpty_set_size)(void*, int, int, void*);
5445HANDLE (*winpty_agent_process)(void*);
5446
5447#define WINPTY_DLL "winpty.dll"
5448
5449static HINSTANCE hWinPtyDLL = NULL;
5450# endif
5451
5452 static int
5453dyn_winpty_init(int verbose)
5454{
5455 int i;
5456 static struct
5457 {
5458 char *name;
5459 FARPROC *ptr;
5460 } winpty_entry[] =
5461 {
5462 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5463 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5464 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5465 {"winpty_config_set_mouse_mode",
5466 (FARPROC*)&winpty_config_set_mouse_mode},
5467 {"winpty_config_set_initial_size",
5468 (FARPROC*)&winpty_config_set_initial_size},
5469 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5470 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5471 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5472 {"winpty_free", (FARPROC*)&winpty_free},
5473 {"winpty_open", (FARPROC*)&winpty_open},
5474 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5475 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5476 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5477 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5478 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5479 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5480 {NULL, NULL}
5481 };
5482
5483 /* No need to initialize twice. */
5484 if (hWinPtyDLL)
5485 return OK;
5486 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5487 * winpty.dll. */
5488 if (*p_winptydll != NUL)
5489 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5490 if (!hWinPtyDLL)
5491 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5492 if (!hWinPtyDLL)
5493 {
5494 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005495 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005496 : (char_u *)WINPTY_DLL);
5497 return FAIL;
5498 }
5499 for (i = 0; winpty_entry[i].name != NULL
5500 && winpty_entry[i].ptr != NULL; ++i)
5501 {
5502 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5503 winpty_entry[i].name)) == NULL)
5504 {
5505 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005506 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005507 return FAIL;
5508 }
5509 }
5510
5511 return OK;
5512}
5513
5514/*
5515 * Create a new terminal of "rows" by "cols" cells.
5516 * Store a reference in "term".
5517 * Return OK or FAIL.
5518 */
5519 static int
5520term_and_job_init(
5521 term_T *term,
5522 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005523 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005524 jobopt_T *opt,
5525 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005526{
5527 WCHAR *cmd_wchar = NULL;
5528 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005529 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005530 channel_T *channel = NULL;
5531 job_T *job = NULL;
5532 DWORD error;
5533 HANDLE jo = NULL;
5534 HANDLE child_process_handle;
5535 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005536 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005537 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005538 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005539 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005540
5541 if (dyn_winpty_init(TRUE) == FAIL)
5542 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005543 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5544 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005545
5546 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005547 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005548 cmd = argvar->vval.v_string;
5549 }
5550 else if (argvar->v_type == VAR_LIST)
5551 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005552 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005553 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005554 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005555 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005556 if (cmd == NULL || *cmd == NUL)
5557 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005558 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005559 goto failed;
5560 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005561
5562 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005563 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005564 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005565 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005566 if (opt->jo_cwd != NULL)
5567 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005568
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005569 win32_build_env(opt->jo_env, &ga_env, TRUE);
5570 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005571
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005572 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5573 if (term->tl_winpty_config == NULL)
5574 goto failed;
5575
5576 winpty_config_set_mouse_mode(term->tl_winpty_config,
5577 WINPTY_MOUSE_MODE_FORCE);
5578 winpty_config_set_initial_size(term->tl_winpty_config,
5579 term->tl_cols, term->tl_rows);
5580 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5581 if (term->tl_winpty == NULL)
5582 goto failed;
5583
5584 spawn_config = winpty_spawn_config_new(
5585 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5586 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5587 NULL,
5588 cmd_wchar,
5589 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005590 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591 &winpty_err);
5592 if (spawn_config == NULL)
5593 goto failed;
5594
5595 channel = add_channel();
5596 if (channel == NULL)
5597 goto failed;
5598
5599 job = job_alloc();
5600 if (job == NULL)
5601 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005602 if (argvar->v_type == VAR_STRING)
5603 {
5604 int argc;
5605
5606 build_argv_from_string(cmd, &job->jv_argv, &argc);
5607 }
5608 else
5609 {
5610 int argc;
5611
5612 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5613 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005614
5615 if (opt->jo_set & JO_IN_BUF)
5616 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5617
5618 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5619 &child_thread_handle, &error, &winpty_err))
5620 goto failed;
5621
5622 channel_set_pipes(channel,
5623 (sock_T)CreateFileW(
5624 winpty_conin_name(term->tl_winpty),
5625 GENERIC_WRITE, 0, NULL,
5626 OPEN_EXISTING, 0, NULL),
5627 (sock_T)CreateFileW(
5628 winpty_conout_name(term->tl_winpty),
5629 GENERIC_READ, 0, NULL,
5630 OPEN_EXISTING, 0, NULL),
5631 (sock_T)CreateFileW(
5632 winpty_conerr_name(term->tl_winpty),
5633 GENERIC_READ, 0, NULL,
5634 OPEN_EXISTING, 0, NULL));
5635
5636 /* Write lines with CR instead of NL. */
5637 channel->ch_write_text_mode = TRUE;
5638
5639 jo = CreateJobObject(NULL, NULL);
5640 if (jo == NULL)
5641 goto failed;
5642
5643 if (!AssignProcessToJobObject(jo, child_process_handle))
5644 {
5645 /* Failed, switch the way to terminate process with TerminateProcess. */
5646 CloseHandle(jo);
5647 jo = NULL;
5648 }
5649
5650 winpty_spawn_config_free(spawn_config);
5651 vim_free(cmd_wchar);
5652 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005653 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005654
Bram Moolenaarcd929f72018-12-24 21:38:45 +01005655 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5656 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005657
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005658#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5659 if (opt->jo_set2 & JO2_ANSI_COLORS)
5660 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5661 else
5662 init_vterm_ansi_colors(term->tl_vterm);
5663#endif
5664
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005665 channel_set_job(channel, job, opt);
5666 job_set_options(job, opt);
5667
5668 job->jv_channel = channel;
5669 job->jv_proc_info.hProcess = child_process_handle;
5670 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5671 job->jv_job_object = jo;
5672 job->jv_status = JOB_STARTED;
5673 job->jv_tty_in = utf16_to_enc(
5674 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5675 job->jv_tty_out = utf16_to_enc(
5676 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5677 ++job->jv_refcount;
5678 term->tl_job = job;
5679
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005680 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5681 * open the file here and handle it in. opt->jo_io was changed in
5682 * setup_job_options(), use the original flags here. */
5683 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5684 {
5685 char_u *fname = opt->jo_io_name[PART_OUT];
5686
5687 ch_log(channel, "Opening output file %s", fname);
5688 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5689 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005690 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005691 }
5692
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005693 return OK;
5694
5695failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005696 ga_clear(&ga_cmd);
5697 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005698 vim_free(cmd_wchar);
5699 vim_free(cwd_wchar);
5700 if (spawn_config != NULL)
5701 winpty_spawn_config_free(spawn_config);
5702 if (channel != NULL)
5703 channel_clear(channel);
5704 if (job != NULL)
5705 {
5706 job->jv_channel = NULL;
5707 job_cleanup(job);
5708 }
5709 term->tl_job = NULL;
5710 if (jo != NULL)
5711 CloseHandle(jo);
5712 if (term->tl_winpty != NULL)
5713 winpty_free(term->tl_winpty);
5714 term->tl_winpty = NULL;
5715 if (term->tl_winpty_config != NULL)
5716 winpty_config_free(term->tl_winpty_config);
5717 term->tl_winpty_config = NULL;
5718 if (winpty_err != NULL)
5719 {
5720 char_u *msg = utf16_to_enc(
5721 (short_u *)winpty_error_msg(winpty_err), NULL);
5722
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005723 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005724 winpty_error_free(winpty_err);
5725 }
5726 return FAIL;
5727}
5728
5729 static int
5730create_pty_only(term_T *term, jobopt_T *options)
5731{
5732 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5733 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5734 char in_name[80], out_name[80];
5735 channel_T *channel = NULL;
5736
Bram Moolenaarcd929f72018-12-24 21:38:45 +01005737 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5738 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005739
5740 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5741 GetCurrentProcessId(),
5742 curbuf->b_fnum);
5743 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5744 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5745 PIPE_UNLIMITED_INSTANCES,
5746 0, 0, NMPWAIT_NOWAIT, NULL);
5747 if (hPipeIn == INVALID_HANDLE_VALUE)
5748 goto failed;
5749
5750 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5751 GetCurrentProcessId(),
5752 curbuf->b_fnum);
5753 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5754 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5755 PIPE_UNLIMITED_INSTANCES,
5756 0, 0, 0, NULL);
5757 if (hPipeOut == INVALID_HANDLE_VALUE)
5758 goto failed;
5759
5760 ConnectNamedPipe(hPipeIn, NULL);
5761 ConnectNamedPipe(hPipeOut, NULL);
5762
5763 term->tl_job = job_alloc();
5764 if (term->tl_job == NULL)
5765 goto failed;
5766 ++term->tl_job->jv_refcount;
5767
5768 /* behave like the job is already finished */
5769 term->tl_job->jv_status = JOB_FINISHED;
5770
5771 channel = add_channel();
5772 if (channel == NULL)
5773 goto failed;
5774 term->tl_job->jv_channel = channel;
5775 channel->ch_keep_open = TRUE;
5776 channel->ch_named_pipe = TRUE;
5777
5778 channel_set_pipes(channel,
5779 (sock_T)hPipeIn,
5780 (sock_T)hPipeOut,
5781 (sock_T)hPipeOut);
5782 channel_set_job(channel, term->tl_job, options);
5783 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5784 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5785
5786 return OK;
5787
5788failed:
5789 if (hPipeIn != NULL)
5790 CloseHandle(hPipeIn);
5791 if (hPipeOut != NULL)
5792 CloseHandle(hPipeOut);
5793 return FAIL;
5794}
5795
5796/*
5797 * Free the terminal emulator part of "term".
5798 */
5799 static void
5800term_free_vterm(term_T *term)
5801{
5802 if (term->tl_winpty != NULL)
5803 winpty_free(term->tl_winpty);
5804 term->tl_winpty = NULL;
5805 if (term->tl_winpty_config != NULL)
5806 winpty_config_free(term->tl_winpty_config);
5807 term->tl_winpty_config = NULL;
5808 if (term->tl_vterm != NULL)
5809 vterm_free(term->tl_vterm);
5810 term->tl_vterm = NULL;
5811}
5812
5813/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005814 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005815 */
5816 static void
5817term_report_winsize(term_T *term, int rows, int cols)
5818{
5819 if (term->tl_winpty)
5820 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5821}
5822
5823 int
5824terminal_enabled(void)
5825{
5826 return dyn_winpty_init(FALSE) == OK;
5827}
5828
5829# else
5830
5831/**************************************
5832 * 3. Unix-like implementation.
5833 */
5834
5835/*
5836 * Create a new terminal of "rows" by "cols" cells.
5837 * Start job for "cmd".
5838 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005839 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005840 * Return OK or FAIL.
5841 */
5842 static int
5843term_and_job_init(
5844 term_T *term,
5845 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005846 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005847 jobopt_T *opt,
5848 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005849{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01005850 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5851 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005852
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005853#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5854 if (opt->jo_set2 & JO2_ANSI_COLORS)
5855 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5856 else
5857 init_vterm_ansi_colors(term->tl_vterm);
5858#endif
5859
Bram Moolenaar13568252018-03-16 20:46:58 +01005860 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02005861 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005862 if (term->tl_job != NULL)
5863 ++term->tl_job->jv_refcount;
5864
5865 return term->tl_job != NULL
5866 && term->tl_job->jv_channel != NULL
5867 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5868}
5869
5870 static int
5871create_pty_only(term_T *term, jobopt_T *opt)
5872{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01005873 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5874 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005875
5876 term->tl_job = job_alloc();
5877 if (term->tl_job == NULL)
5878 return FAIL;
5879 ++term->tl_job->jv_refcount;
5880
5881 /* behave like the job is already finished */
5882 term->tl_job->jv_status = JOB_FINISHED;
5883
5884 return mch_create_pty_channel(term->tl_job, opt);
5885}
5886
5887/*
5888 * Free the terminal emulator part of "term".
5889 */
5890 static void
5891term_free_vterm(term_T *term)
5892{
5893 if (term->tl_vterm != NULL)
5894 vterm_free(term->tl_vterm);
5895 term->tl_vterm = NULL;
5896}
5897
5898/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005899 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005900 */
5901 static void
5902term_report_winsize(term_T *term, int rows, int cols)
5903{
5904 /* Use an ioctl() to report the new window size to the job. */
5905 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5906 {
5907 int fd = -1;
5908 int part;
5909
5910 for (part = PART_OUT; part < PART_COUNT; ++part)
5911 {
5912 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01005913 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005914 break;
5915 }
5916 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5917 mch_signal_job(term->tl_job, (char_u *)"winch");
5918 }
5919}
5920
5921# endif
5922
5923#endif /* FEAT_TERMINAL */